1

when i pass ajax values it says json parseererror, tried jsonp but not working. Here's my code:

HTML:

<form class="ajaxform" method="post">
    <div class="form-group form-inline">
        <label for="searchtxt">Search Here: </label>
        <input type="text" name="ajaxinput" class="form-control ajaxinput">
    </div>
    <div class="form-group">
        <a href="" class="ajaxsubmit btn btn-primary">Get Data</a>
    </div>
</form>

PHP:

$return_array = array();

$query = "select * from tbl_admin where uName like '%".$ajaxinput."%' or uEmail like '%".$ajaxinput."%'";

$abc = $db->pdoQuery($query)->results();

foreach ($abc as $key => $value) {
    # code...
    $return_array['admin_name'] = $value['uName'];
    $return_array['admin_email'] = $value['uEmail'];
    $return_array['admin_ip'] = $value['ipAddress'];

    echo json_encode($return_array);
}
exit();

JQUERY:

$('.ajaxsubmit').on('click', function(e){  
e.preventDefault();
var urlPath = siteName+'modules-nct/ajax-nct/ajax.ajax-nct.php';
var mydata = jQuery(".ajaxform").serialize();

$.ajax({
url: urlPath,
data : mydata,
dataType: 'json',

success: function(response){
  console.log(response);
  alert(response);

},
error: function(xhr, status){
  console.log(status);
}
});
});

i want data in json as i have to append it in a table. In datatype: html data comes but not that useful as it contains multiple records.

2
  • 2
    build the output array in the loop and echo once after the loop Commented Jan 29, 2018 at 7:42
  • Is this a PHP problem, a JS problem, or a JSON problem? What have you tried to resolve it? Commented Jul 12, 2023 at 7:28

1 Answer 1

3

You are echoing the result every loop. That is the reason why your js cant parse it correctly. You should echo it once(on the end of the loop.).

$return_array = array();

foreach ($abc as $key => $value) {
    $temp = array();
    $temp['admin_name'] = $value['uName'];
    $temp['admin_email'] = $value['uEmail'];
    $temp['admin_ip'] = $value['ipAddress'];

    $return_array[] = $temp;
}

 echo json_encode($return_array);
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah man! how can i make this silly mistake...it worked thank you very much.
Happy to help. :)

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.