shibbir ahmed shibbir ahmed - 5 months ago 21
Javascript Question

why json return data is showing [] (third bracket) in ajax success method?

I am validating a form using jQuery / Ajax method.

Bellow is my jQuery code and I am passing

json
data type. But in
ajax
success
method it's return any data with third braket like : [my return data]

jQuery Code :

$("#filter_c_n").change(function() {
var data = $("#filter_c_n").val();
$.ajax({
url : 'search_c_n.php',
method : 'POST',
data : {
key : data
},
datatype : 'json',
success : function(data) {
$("#filter_c_n_result").html(data);
}
});
});


Here is my php file which contain bellow code :

<?php
ob_start();
require_once("corefile.php");
user_login_check();
timeout();

$data = array();
$key = inputvalid($_POST['key']);
$data['key'] = $key;
echo json_encode($data);
?>


What is showing is bellow :

enter image description here

Answer

If you just want the string, without wrapping it in an object, use

echo json_encode($key);

There's no need for the $data array.

However, returning an associative array allows for more flexible coding, as you can return multiple items. For instance, you can include a status key, so that the client can check whether the request was successful. With the way you're returning the data, you just need to change the Javascript code to do:

$("#filter_c_n_result").html(data.key);
Comments