简体   繁体   中英

AJAX Success function if there is no returned JSON data

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) {

而不是在JSON中传递错误false,而是抛出404或500之类的HTTP错误代码。然后,您可以在JavaScript中放置一个error部分,而不是在success部分中进行检查。

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) {...

只需在第一行在success()中使用JSON.parse(responce) ,然后使用它即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM