PHP & JSON - Trouble to print a value on client side - php

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]);

Related

how to receive ajax response as array in php [duplicate]

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.

can ajax success return string from php?

I want to compare two values (both are simple strings) on ajax success. Value1 is echo from php, value2 is javascript variable. But when I try something like:
$.ajax({
type: "POST",
url: proccessPage,
data: dataString,
dataType: "text",
success:function(result){
alert (result);
}
});
I will get message "[object Object]". When i try change alert (result); for
var response = $(result);
document.getElementById("div1").innerHTML = result;
then div with id "div1" has proper value. I know I can make the div hidden and use value from it, but is there some way to work with result directly? Or somehow convert result to string? Code in php:
if (isset($_POST['submit']) && $_POST['submit']=="true")
echo "string";
Thanks.
In your script, change the datatype to html.
dataType: "text",
to
dataType: "html",
The dataType of text is perfectly ok. Make certain that your PHP script is setting the mime type for the return to text/plain.
PHP Code:
header('Content-type: text/plain');
jQuery will process the return according to what the server says it is. The dataType field is only a hint. http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
If all else fails use something like Firefox with Firebug. It will give you the ability to place a break pint within your success closure and then you may inspect the value of your result variable.
I am having success by creating a json response from the PHP function, and loading it with whatever I need. Comparing known values from the Json Object handles your [object Object] return issue by giving you known object properties- declared with JSON:
$response = json_encode( array( 'success' => true , 'value1' => $my_result,);
header( "Content-Type: application/json" );
echo $response;
exit;
I use the success bool to ensure that $my_result is a successful response, because AJAX may execute properly, but this allows me to specifically check valid value1
Now, back in your $.ajax:
...
success: function(result){
if(result['success']) {
document.getElementById("removeme").innerHTML = (result['value1'] == value2)? value1 : "Uh-oh. Something went wrong!";
}
}
...
Or you can put whatever is appropriate in your success function body, whatever you need to compare or do. I just gave 1 example to show a complete implementation.
The first A in AJAX means asynchronous, this means that your request will be executed as normal but the callback only gets executed when the requests gets a response. the script doesn't pause waiting for the response.
with that said, if you want to use information from an AJAX request you must use it in its callback, or it will not be available.
something like this:
$.ajax({
type: "POST",
url: proccessPage,
data: dataString,
dataType: "text",
success:function(result){
document.getElementById("removeme").innerHTML = result;
}
});

Print array from PHP in the jQuery

How can print date and age (in following array) separate by $.ajax()?
php:
$array = array(
'date' => 2011/9/14,
'age' => 48,
);
return $array // this send for ajax call in the jQuery
I want this output by jquery:2011/9/14 & 48
Use $.ajax Methods and setting parameter dataType to JSON for receive data type JSON from PHP file.
Jquery Code:
$.ajax({
url: "getdata.php",
type: "post",
dataType: "json",
success: function(data){
alert("Date:" + data.date + "\n" + "Age:" + data.age);
}
});
if your array data contains string make sure it's closured with quote then make data type JSON with json_encode() function.
PHP Code (getdata.php):
$array= array('date'=>'2011/9/14','age'=>48);
echo json_encode($array);
Echo the encoded array in php page say mypage.php
using
echo json_encode($array);
And use jQuery.getJson in the client side
$.getJSON('mypage.php', function(data) {
alert(data['date']);
alert(data['age']);
});
You need to encode the array as a valid JSON string using the PHP function json_encode. You can then use the jQuery function $.parseJSON to convert it into a JavaScript object. From there you'll be able to do whatever you want with it.
If you do this, you'll end up with an object like:
ajaxDataObj = {
date: '2011/9/14',
age: 48
}
**Edit**
Please see stratton's comment below about using $.getJSON for a more compact solution.
Also, Ben Everard's comment on your original post about using echo rather than return is critical.
You can't just return $array to the browser, the result will be "Array" as string.
YOu have to use return json_encode($array); which returns a string that could be parsed by browser.
If the server-client communication is working alright, then you should do something like this on the client side:
$.ajax({
//configuration...
'success':function(response){
var dateAge = response.date+' & '+response.age;
//put or append the string somewhere.
}
});

Traverse JSON data with jQuery

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

How to use JSON with Jquery?

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.

Categories