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;
}
});
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 am currently a newbie to JSON and i think it could be really usefull below is a data format i use to send a JSON object to a server side php script
// CREATE JSON OBJECT
var EmailEntity = { "MailMembers":memberecipients , "email":"me#mail.com" } ;
// send to php server script
$.ajax({
type: "POST",
url: "engine/send-mail.php",
dataType: "JSON",
data: {JsonEmailEntity: JSON.stringify(EmailEntity)},
success: function(Databack){
alert(Databack);
}
});
Then for the sever-side (PHP)
// get json element and extract contents
$Json = $_POST['JsonEmailEntity'];
$EmailEntities = json_decode($Json,true);
$email = $EmailEntities['email'];
echo $email;
the problem is that the Javascript doesnt alert any returned any return value even when i checked it with firebug it showed that the response was actually sent but was not alerted.
would like to know where the Javascript error lies
Change:
echo $email;
to:
echo json_encode($email);
I would suspect that it may be related to this line
{JsonEmailEntity: JSON.stringify(EmailEntity)},
You do not need to stringify that variable, you can simply pass { JsonEmailEntity: JsonEmailEntity } and jQuery will convert it accordingly.
That being said, since you are decoding it on the server side I'm not sure if the error is related to it.
In Firebug, if you go to the console tab and then click on the request, from there click on the Params tab and you can see what is getting sent to the server.
Change your JavaScript ajax code:
// CREATE JSON OBJECT
var EmailEntity = { "MailMembers":memberecipients , "email":"me#mail.com" } ;
// send to php server script
$.ajax({
type: "POST",
url: "engine/send-mail.php",
data: {JsonEmailEntity: JSON.stringify(EmailEntity)},
success: function(Databack){
alert(Databack);
}
});
Because if you are specifying dataType as JSON. the success function will execute if return type is json.
Or change your Php code as below:
Change:
echo $email;
to:
echo json_encode($email);
The dataType property when calling jQuery.ajax() is the type of the data being returned by the server, not the type of the data being sent to it.
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. ...
The jQuery AJAX call is expecting a response that is itself JSON, but you're just outputting a string. jQuery implicitly tries to parse that as JSON, fails, and as a result executes the error callback.
Change this:
echo $email;
into this:
echo json_encode($email);
And it should work. At the moment you're only echoing the data, but it's not in JSON-format.
Addition:
For future reference, you can also do this:
$email['email'] = $EmailEntities['email']; //or "some#email.com";
$email['username'] = "some_user";
echo json_encode($email);
and then in Javascript:
success: function(Databack){
alert("Your username is " + Databack.username + " and your email is " + Databack.email);
}
Parsing JSON in PHP
My variable jsonvar is in the form of {"rating":"good"}
Once I push it through with this $.ajax code to submit, I'm a bit confused at what my PHP (jsonproc.php) should look like.
$.ajax({
url: 'jsonproc.php',
data: {js:jsonvar},
dataType: 'json',
type: 'post',
success: function (j) {
if (j.ok){
alert(j.msg);
} else {
alert(j.msg);
}
}
});
I have it set up as
$decoded = $_GET['js'];
$response = array(
'ok' => true,
'msg' => $decoded['rating']);
However when I echo it back,
echo json_encode($response);
using alert(j.msg) shows a "null" value.
Assuming that I am passing JSON in correctly, how can I point to the rating and get the value of "good"?
Thanks
EDIT
SOLVED, USING $_REQUEST I was able to get the JSON, however $_GET did not work.
Also, the key was using $decoded->{'rating'} as $decoded is no longer just an array i don't think or rather it's a diff type of one?
It looks like you're mixing data types here:
data: "js="+jsonvar,
jQuery will convert JSON if you pass an object, but you're mixing query string with JSON.
Try:
data: {js: jsonvar},
You may also need to do json_decode($_GET['js']).
edit: You can double check what jQuery is POSTing with Firebug/Web Inspector. Easiest way to know for sure.
Try adding this to the top of your PHP file:
header('Content-type: application/json');
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 have the following object that gets created in my javascript application.
poll_data[active_question] = {
'question': $('div.question_wrap textarea').attr('value'),
'answers': [
$('div.answer_wrap input#0').attr('value'),
$('div.answer_wrap input#1').attr('value'),
$('div.answer_wrap input#2').attr('value'),
$('div.answer_wrap input#3').attr('value'),
$('div.answer_wrap input#4').attr('value'),
$('div.answer_wrap input#5').attr('value')
]
};
active_question is set to 'poll', 0, 1, 2, 3, 4, or 5 depending on the question being worked on at the moment. I am trying to post this object to a php script using the following JS code.
$.ajax({
url: '/somewebsite/poll/create?json=show',
type: 'POST',
// dataType: 'json',
data: poll_data,
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data);
}
});
My PHP code is very simple.
echo json_encode($_POST); exit;
When I run the script and click the button that triggers the submission of the data, I receive the alert (so the actual ajax code works), but the result from my PHP script is just an empty array. I think that this is an issue with the way the object is constructed, but I am not sure, and have not been able to find a work around.
Thanks in advance.
Okay, a few things:
poll_data is not a valid JSON object. You would have to use poll_data[active_question], which IS a valid JSON object. jQuery should serialize this correctly. Remove the contentType -- I am pretty sure that is for php (not positive) but your code wouldn't work for me until I removed it. Finally, the appending of json=show to the query string doesn't do anything..it will just be ignored.
A couple minor things too: you can use .val() instead of .attr('value'), and have you looked into .serialize() to create your post data for you?
do this on server
$data;
$data->question=$_POST['question']
$data->answer=$_POST['answers']
echo json_encode($data);
do this for ajax request
$.ajax({
url: '/somewebsite/poll/create?json=show',
type:'POST',
//modified data proprty
data:poll_data[active_question],
success: function(data) {
alert(data);
}
});