Jquery AJAX PHP data return - php

I'm using the ajax function in Jquery to return some values from a PHP script with the json_encode function. The returned data seems to be full of slashes, quotes and \r\n. I understand that there must be something going wrong with stripslashes or magic_quotes (which is turned on) but can't seem to manage to get a clean output

Make sure on your ajax call from jQuery, you tell it to expect a json response. It sounds like you're returning plaintext and trying to parse it manually.
$.ajax({
url: "myscript.php",
dataType: "json",
success: function(data){
console.log( data ); //this line only works with chrome (stock) or FireFox (with FireBug plugin)
}
});
That code will echo in your console (if you don't have chrome or FF with FireBug, go get one of them :P) the json encoded output. Remember when you output from PHP, all you should be doing is this:
header('Content-type: application/json');
echo json_encode( $myAssociativeArrayOfData );
exit; //make sure nothing else happens to output something
You don't need to use any special formatting or slashes. Just make sure the json code gets output as json code with the proper headers and jQuery's ajax function should convert it for you. The result will be the data variable in the success function being your json object (php array). So if you pass in an array like this: array('foo'=>'bar') in PHP, then in your success function in jquery, you could type: alert( data.foo ); and get a dialog box that says "bar".

Related

Embedding JSON in responseText

I am using jquery iframetransport (for blob uploading) and am forced to access my responses via data.responseText. I am able to embed simple JSON from my PHP such as
echo json_encode(array("response"=>"hello"));
And my console log will return
{"response" : "hello"}
But I need divs and to concat data from my PHP requests. I fail right away if I try to embed this:
echo json_encode(array("response"=>"<div>hello</div>"));
I end up with
{"response":"hello<\/div>"}
What can I do to have this kind of json data in a resposneText?
Alternatively you could cast htmlentities() to the response array. Like this:
echo json_encode(array('response' => htmlentities('<div>hello</div>')));
// {"response":"<div>hello<\/div>"}
exit;
On retrieving responses, since you're expecting JSON, add the dataType: property:
$.ajax({
url: 'blahblah.php',
dataType: 'JSON', // this one
});

Php script returns json, but I am getting parseerror

i know that there was similar questions, but i would like to get some clarification here.
With following Ajax setup:
$.ajaxSetup({
cache: true,
dataType: 'json',
error: function(xhr, status, error){
console.log(status);
},
timeout: 60000, //Timeout of 60s
type: 'POST',
url: 'test.php'
}); //Close $.ajaxSetup()
$('#openTest').bind('click', function(){
$.ajax({
data: {val: "Hello", val2: "Hello2"},
success: function(response){
console.log('complete');
console.log(response);
}
});
When 'test.php' is:
<?php
$return= array ('one'=>'one1', 'two'=>'two1');
return json_encode($return);
?>
I am getting parseerror. But when I replace 'return' with an 'echo', it works fine.
<?php
$return= array ('one'=>'one1', 'two'=>'two1');
echo json_encode($return);
?>
I will be retrieving much more complex data via this $.ajax calls, and I was expecting 'return' to works, 'echo' doesn't seems to me like good solution.
So, what are you suggesting? Is there something wrong with the Ajax setup, or call, so 'return' doesn't work, and is 'echo' a good solution?
Thanks.
return returns data to the caller of the function and since you are not in a function you cannot use return.
echo prints the data. So echo is the way to go.
when you do a return in php, it is not printed. When you do an echo, it gets printed.
Nothing is wrong with php or Ajax, it is just the context which is wrong.
Sinply put, use return when u need to catch the returned data and maybe process it. Best case for using return is in functions.
Use echo when you need to print something directly.
Here in this case using an echo and exit is what i recommend.
Return is used in functions to get the data back and use it in some fashion in your PHP. Echo is used for ajax calls because your PHP code will output the data to whatever is calling it (the browser, your ajax call, etc).
You also probably want to have header('Content-Type: application/json'); in your PHP file to make things all right and proper.
No, there is no problem with your ajax setup, it's because the return is used with PHP objects or variables and it can't return a value to other language like javascript. when you are using echo it sends the values to HTTP response so your ajax response can handle it.
The best way to do complex data is to send them in arrays like:
$arr = array();
$arr['res'] = 'something';
$arr['res2'] = 'somethingelse';
echo json_encode($arr);
and then you can handle it as object.parameter in your jquery code as I have specified it before in this example.
Always make echo or print or parsing php as html file in ajax call and then get the data, this will save you a lot of efforts.
the ajax is just reading the file, there is no way to make calls in two different languages PHP and JS.
The JS just returned the filed from the server, if it was php then it will interpreted and go to the Ajax call as html or else possible.

Sending html to Javascript from PHP via JSON obejct

I'm sending some data from php through ajax to jquery.
If $content="ABC"; everything is OK. I get alert with ABC.
If $content="<div>ABC</div>"; then Houston has a problem. Nothing happens at all.
Here is PHP code
$json = json_encode(array("content" => $content));
echo $json;
And this is Jquery
$('#'+pic_type+'_form_n_'+pic_number).ajaxSubmit({
success: function(responseimage){
result = jQuery.parseJSON(responseimage);
alert(result.content);
Any ideas ?
UPDATE!
I've removed jQuery.parseJSON
so that line has only this code
result = responseimage;
And now I get the result in alert.
The result is the following
{"content":".<div>ABC<\/div>."}</div>
So we can see that JSON is not created well. I;ve tried utf8_encode and trim , but they do nothing to the result. result is strange.
PHP (and JSON) code seems fine, provided that the variable $content actually has any content. Else the PHP script will fail and there's your problem.
Did you define the dataType as "json" in the AJAX request?
$.ajax({
url: 'json.php',
dataType: 'json',
success:function(data){
console.log(data);
}
});
I think you just need to utf8_encode your response before doing json_encode.
Just change this :
$content = utf8_encode("<div>ABC</div>");
You are delivering invalid json somehow - please put your raw response in JSONLint, it will tell you what is wrong.

Proper way to format user-entered text input for sending via JSON/AJAX to PHP?

I'm running into some problems with user-entered input that I want to send to PHP as JSON via AJAX that contains special characters, like ", ', etc. I'm sending the contents of an array (used for slickgrid), and everything works fine unless those characters are included. I know that PHP has the handy function mysql_real_escape_string, but is there any sort of jquery analogue? Here is the relevant code:
req = $.ajax({
url: url,
dataType: "text",
data: {"data": $.JSON.encode(data)},
type: "post",
success: onSaveSuccess,
error: onSaveError
});
Here's the PHP it is submitted to:
<?php
//$data = array();
//if (isset($_POST['data']))
//{
//$data = json_decode($_POST['data']);
//}
//header('Content-Type: text/javascript');
//echo json_encode($data);
print_r($_POST);
?>
To be clearer, when special characters are included, neither the success nor error events are triggered.
I looked in firebug and it doesn't appear to send anything at all when the special characters are included... Of course, it does when it's just letters or something.
It was due to the script from here apparently failing on certain kinds of input. Switching to json2.js and using JSON.stringify has solved the problem.
data: {"data": $.JSON.encode(data)},
Passes up a more complex JSON object than you need.
$data = json_decode($_POST['data']);
Is looking for a serialized JSON object but jQuery is doing a lot of work for you in the background.
Try this
data: $.JSON.encode(data),
In your AJAX call. Then in PHP
$data['myPostValue'] = $_POST['myPostValue'];
You're sending a JSON object to the $.ajax call, and it is changing it into the name value pair that the server would normally get from a post.
javascript has an escape() function. you can $.JSON.encode(escape(data)) might work

Sending PHP json_encode array to jQuery

ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery.
Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such :
//==================PHP code ==================================
$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
'message'=>$message_for_user,
'calculatedValue'=>$calculatedValue
);
echo (json_encode($responseVar));
//==================PHP code End ==================================
My javascript code is supposed to accept the values returned by php :
//==================Javascript code ==================================
$("div.calculator_result").click(function()
{
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}
}
//==================Javascript code End ==================================
Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required.
Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option:
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}, 'json');
NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this:
$.parseJSON(response)
And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed.
EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words...
$.ajax({
url: "external_file",
method:"post",
dataType: "json", // **************** Note dataType****************
success:function(response){
console.log(response)
// Response will be a javascript array, instead of a string.
},
error: function(){
alert('something went wrong.')
}
})

Categories