如果没有返回的JSON数据,则为AJAX Success函数

I know this is simple but I am struggling to get this right. I am using jQuery/AJAX to retrieve some data (JSON) from my database. I then have a success function to display the data. This works fine but I want to have alert the user if there are no returned results.

My PHP excerpt which encodes the JSON:

...

while($row = $result->fetch_all())
{
    $returnResult = $row;
}
echo json_encode(['result' => $returnResult, 'errors' => $errors]);

....

My JSON data format looks like this:

{"result":[["Grade 12","Studies","John","Doe"]],"errors":false}

My jQuery that then uses the JSON data and displays in html elements:

function getworkload(){

        $.ajax({
        type: "POST",
        url: "modules/getworkload.php",
        dataType: 'json',
        data: {id:id},
        cache: false,
        })
        .success(function(response) {
            if(!response.errors && response.result) {
                $.each(response.result, function( index, value) {
                    $("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
                    $("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
                });
            } else {
                $.each(response.errors, function( index, value) {
                    $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
                });
            }
        });
}

I have tried to replace if(!response.errors && response.result) { with the following:

  1. if(!response.errors && response.result=null) {
  2. if(!response.errors && !response.result) {
  3. if(!response.errors && response.result.length < 1) {

Instead of passing errors false in your JSON, throw an HTTP error code like 404 or 500. Then, you can put an error section in your javascript instead of checking in the success section.

Just use JSON.parse(responce) in success() at firstline and then use it.

Assuming the returned JSON is as follow,

{"result":[["Grade 12","Studies","John","Doe"]],"errors":false}

You just have to put one condition to check if the result length is 0 or not.

Like this,

if(!response.errors && response.result) {
                $.each(response.result, function( index, value) {
                    $("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
                    $("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
                });
            } else if(!response.errors && response.result && response.result.length==0) {

                 // Handle 0 result output here...

            } else {
                $.each(response.errors, function( index, value) {
                    $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
                });
            }

your code is not correctly parsing json value from php file to javascript and you have to parse json before using in javascript

  function getworkload(){

        $.ajax({
        type: "POST",
        url: "modules/getworkload.php",
        dataType: 'json',
        data: {id:id},
        cache: false,
        })
        .success(function(response) {
            console.log(response);
             var  res = JSON.parse(response);
           console.log(res);/* console json val*/
            if(!res.errors && res .result) {
                $.each(res.result, function( index, value) {
                    $("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
                    $("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
                });
            } else {
                $.each(res.errors, function( index, value) {
                    $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
                });
            }
        });
}

Let the server return the word 'nothing' for example in case of no result and split the code to three cases if result and if error and if nothing

if(isset($returnResult) && $returnResult!=null){
echo json_encode('result' => $returnResult);
}
else if (isset($errors) && $errors!=null){
echo json_encode('errors'=>$errors);
}
else { echo "nothing";}

Check that response is not nothing on success function

.success(function(response) {
if(response=='nothing'){
alert('nothing');
}
else {
//rest of the success function
}

Another suggestion is to use this if statement with in success function

.success(function(response) {
if(!response.result && !response.errors){
alert('nothing');
}
else {
//rest of the success function
}

Or

.success(function(response) {
if(response.result==null && response.errors==null){
alert('nothing');
}
else {
//rest of the success function
}

In your PHP script change your echo json_encode... to

 echo json_encode(['result' => (count($returnResult)) ? $returnResult : 0, ...]);

Then in your JS simply do

if(!response.errors && !!response.result) {...