0

My Code Igniter PHP page returns json_encode query when page is load with success data. I made a json_encode when no records found. But i dont know how to pass my no record error to jQuery

PHP

if (($query->num_rows() > 0) && ($counter > 0)){            
        echo(json_encode($query->result()));                      
        $counter = 0;                        
    } else {            
        //return false;
        $response["error"] = 1;
        $response["error_msg"] = "NO records found";
        echo json_encode($response);
    }}

JQuery

$.ajax({
  url: <? base_url() ?> +'main/data',
  dataType: "JSON",
  type: "POST",
  success: function(retdata) { //working 
    $.each(retdata, function(i) {
           $("#main_div").append('<div>' + retdata[i].name + '<br>' + retdata[i].marks+ '</div>'); 

    });
  }
});

1
  • In your jQuery success callback: if(retdata.hasOwnProperty('error')){/* ... */} Commented Apr 5, 2016 at 9:56

1 Answer 1

1

controller:

public function controller_function()
{
    //$query = your get query code
    $response = array(
        'result'    => array(),
        'error_msg' => '',
    );
    if ($query->num_rows() > 0)
    {
        $response['result'] = $query->result();
    }
    else
    {
        $response['error_msg'] = 'NO records found';
    }
    echo json_encode($response);
}

Javascript:

$.ajax({
    url: <? base_url() ?> +'main/data',
    dataType: "JSON",
    type: "POST",
    success: function (retdata)
    {
        if (retdata.error_msg)
        {
            alert(retdata.error_msg);
        }
        else
        {
            $.each(retdata.result, function (i)
            {
                $("#main_div").append('<div>' + retdata.result[i].name + '<br>' + retdata.result[i].marks + '</div>');
            });
        }
    }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.