I can't figure out how to get a bunch of MySQL rows into a JSON data structure and iterate each of the row fields in java script.
Here is my query in codeigniter
function get_search_results() {
//$this->db->like('title', $searchText);
//$this->db->orderby('title');
$query = $this->db->get('movies');
if($query->num_rows() > 0) {
foreach($query->result() as $movie) {
$movies[] = $movie->title;
}
}
return $movies;
}
Encode array for json
$rows= $this->movie_model->get_search_results();
echo json_encode($rows);
My jQuery AJAX request,
$.ajax({
type: "GET",
url: "publishlinks/search_movies",
data: searchString,
...
This is how I've been trying to traverse rows in the java script. It is iterating over every character: 1 t 2 h 3 e 4 g ... 7 e
I need this: 1 the game 2 lost 3 you
success:
function(result) {
$.each(result, function(key, val) {
alert(key + ' ' + val);
})
//alert(result);
}
It looks like it is treating the result as a string instead of parsed JSON, hence iterating over it as if it was a string. This could mean that it isn't returning a clean JSON encoded string in the response, so I'd check the response to make sure it is valid JSON. jQuery is supposed to intelligently guess the content type and parse accordingly.
You could also try the dataType: "json" option on the ajax request to force it to be parsed as JSON instead of letting jQuery guess.
Use the dataType property of $.ajax
$.ajax documentation
dataType
"The type of data that you're expecting back from the
server."
Use firebug to find the type of the response variable. In your case the response is string but it should be Array (or Object?)
If you don't want jQuery to automatically eval the json then live it as it is and in the success function add the following:
var parsed = $.parseJson(response);
Here is the documentation of the parseJson method: parseJson
I think you problem is you don't fetch actual json but simple string response....
use $.getJSON or specify dataType as json in your jquery ajax request!
Do you return a JSON header with your PHP ?
header('Content-type: application/json');
Else try
result = JSON.decode(result);
before your "each" loop
Be sure to return proper content-type from your server side. For JSON that would be application/json.
$rows = $this->movie_model->get_search_results();
header('Content-type: application/json');
echo json_encode($rows);
Also add dataType: "json" to your jQuery request, just as beefsack said:
$.ajax({
type: "GET",
url: "publishlinks/search_movies",
data: searchString,
dataType: "json",
...
dataType: "json",
success:function(data){
var obj=$.parseJSON(data);
data=obj.data;
$.each(data,function(){
//json data
})
}
Related
I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.
1) How can I return the JSON encoded string to the javascript?
2) How will the javascript loop through the rows and access their fields?
To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.
To loop through an array, I usually use jQuery.each():
var recordList = yourMethodToGetRecordListWithAjax();
jQuery.each(recordList, function()
{
alert(this.Name); // For example
});
1) in the php script:
$return["foo"] = "bar";
$return["blah"] = "bleg";
print json_encode($return);
2) in the javascript:
$.ajax({
type: "POST",
url: URL,
cache: false,
data: values,
dataType: 'json',
success: function(json) {
var foo = json.foo;
if (json.blah == "bleg") {
// do stuff
}
} // end success function
}); // end ajax call
You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.
See above answer for the rest.
I'm passing a simple JSON array with 4 words to PHP. I want to store that array in a database after I serialize it. Since it's an Ajax call I can only investigate any echoed values by json_encode and alerting them in AJAX success function.
Here's my code:
var jsonString = JSON.stringify(ans);
//if I alert jsonString - it shows the proper array
$.ajax({
type: "POST",
url: "script.php",
data: jsonString,
cache: false,
success: function(data){
alert(data);
},
error: function(){
alert("error");
}
});
That's what I do in PHP with the array:
$answerAr = json_decode($_POST['data']);
$answers = serialize($answerAr);
If I echo the json_encode($answerAr) it alerts NULL in Ajax and $answers turns into 'N;'
Json_last_error returns 0.
If you're posting data directly to PHP, you'll have to use php://input and parse that; data given in JSON isn't form data, and wont auto-populate the request superglobals ($_GET, $_POST).
$data = json_decode(file_get_contents("php://input"));
Most frameworks do this transparently for you and populate a request object with data in it. You should probably check if the request sends JSON data in the body via headers (Content-Type, Accept: application/json, etc)
Alternatively, you can change your AJAX call to give it an array key:
$.ajax({
data: {data: jsonString},
// etc
});
Which will then be accessible as $_POST["data"]
Change your ajax data attribute to like this and try
data: {json: jsonString}
and in the php script you can access it by
$answerAr = json_decode($_POST['json']);
I am new to JQuery and the whole JQuery to PHP back to JQuery process.
So i have a simple ajax JQuery script:
$.ajax({
type: "POST",
url: "includes/calc.php",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
This goes to a PHP script and then I return a value, using a simple echo
echo $newprice;
The success function above uses this as 'data'. This all works and is fine.
But what if I want to return more than one value.
I think I can used json_encode();
As I understand it something like:
$dataset = array($var1, var2, var3);
echo json_encode($dataset);
But say I have two values, how do i put them both into the JSON and then how do I split them on the other end.
So say 'data' is an array, how do I tell JQuery to split it?
Sorry if this is simple
If you specify the dataType option for .ajax() as json, jQuery will automatically parse the JSON string returned by the call into an appropriate javascript object/array.
So your call might look like this:
$.ajax({
type: "POST",
url: "includes/calc.php",
dataType: "json",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
Now, let's say the response from your PHP script is a JSON string representing an object like this:
{"key1":"value1","key2":"value2"}
In your success handler you can simply access this as an object like this:
success: function(data){
alert(data.key1);
alert(data.key2);
}
Or, if the returned JSON string represents an array like this:
["value1","value2"]
Then you can access the array values in the success handler like this:
success: function(data){
alert(data[0]);
alert(data[1]);
}
If you do not want to add the dataType option, you can also opt to manually parse the returned JSON string into an object/array like this:
success: function(data){
var dataObj = JSON.parse(data);
alert(dataObj.key1);
alert(dataObj.key2);
}
$.ajax({
type: "POST",
url: "includes/calc.php",
datatype : 'json',
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data.firstvalue);
alert(data.secondvalue);
}
})
please look at that datatype. now the respose need to be json.
In your php user json_encode instead of echo.
$firstvalue = 'your first value';
$secondvalue = 'your second value';
echo json_encode(array('firstvalue' => $firstvalue,'secondvalue' => $secondvalue));
There are many ways to organize data in a JSON object. The simplest is to return a linear array of strings or numbers. Use http://jsonlint.com/ to test your data to see if it's valid JSON, or just feed a PHP array (linear or associative) into json_encode.
If data is a JSON linear array, you can treat it like any other JavaScript array in your success callback:
var first = data[0]; // first element
var second = data[1]; // second element
implode your php variables with a symbol or any custom data
like
$var[0] = '1st variable';
$var[1] = '2nd variable';
$var[2] = '3rd variable';
echo implode('_SPLIT_',$var);
Now in jquery success function
split the response with 'SPLIT'
as
var response = data.responseText.split('_SPLIT_');
var variable1 = response[0];
var variable2 = response[1];
var variable3 = response[2];
and assign as your wish
I have this PHP function :
if(($_POST['id']=="pm_read") && (isset($_POST['pm_id'])) && (ctype_digit($_POST['pm_id'])) && (isset($_SESSION['nickname']))) {
$update=mysql_query("UPDATE pm SET readed='1' WHERE id='".$_POST['pm_id']."' AND receiver='".$_SESSION['nickname']."'",$mydb);
$query=mysql_query("SELECT COUNT(id) FROM pm WHERE receiver='".$_SESSION['nickname']."' AND readed='0' AND receiver_delete='0' ORDER by date DESC",$mydb);
$arrayPm[0]=mysql_result($query,0,'COUNT(id)');
$query=mysql_query("SELECT message FROM pm WHERE id='".$_POST['pm_id']."' AND receiver='".$_SESSION['nickname']."'",$mydb);
$arrayPm[1]=mysql_result($query,0,'message');
echo json_encode($arrayPm);
}
On client side, I get this array trought a jQuery function :
$.ajax({
type: 'POST',
cache: false,
url: 'pm/pm_ajax.php',
data: 'pm_id='+$(this).attr('id')+'&id=pm_read',
success: function(data) {
... here I'll print somethings...
}
});
Unfortunatly, if I print data I get (for example) the string ["2", "message"].
So, if I try to do alert(data[0]) I'll see only [.
How can I access to this array printing the correct result? I mean :
data[0] must print 2 and data[1] must print message...
try adding
dataType:'json'
to your options in the ajax call.
Never insert unfiltered $_POST superglobal into mysql_queries. That's a security flaw.
Obviously data is being returned as a string, so data[0] is the first character. Instead you want JSON. So make sure you use header() in PHP, to set content-type: application/json
So give this a try before you echo your output:
header('content-type: application/json');
Also make sure your jquery request has
dataType: 'json',
How about this:
var obj = jQuery.parseJSON(data);
alert(obj[0]);
I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.
1) How can I return the JSON encoded string to the javascript?
2) How will the javascript loop through the rows and access their fields?
To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.
To loop through an array, I usually use jQuery.each():
var recordList = yourMethodToGetRecordListWithAjax();
jQuery.each(recordList, function()
{
alert(this.Name); // For example
});
1) in the php script:
$return["foo"] = "bar";
$return["blah"] = "bleg";
print json_encode($return);
2) in the javascript:
$.ajax({
type: "POST",
url: URL,
cache: false,
data: values,
dataType: 'json',
success: function(json) {
var foo = json.foo;
if (json.blah == "bleg") {
// do stuff
}
} // end success function
}); // end ajax call
You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.
See above answer for the rest.