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.
Related
Im trying to transfer an array from jQuery to PHP but for some reason after hours of searching nothing will work. Below is what I have and what others seem to be using online but for some reason I only get the error alert. Anyone know what it is I'm doing wrong? It seems to be something to do with my jQuery code but I can put in anything there and get the same results so it is useless for telling me what I am supposed to fix. Also Im not sure if it is important but the array Im using is 2d.
FINAL WORKING CODE:
jQuery:
$.ajax({
type: "POST",
url: "phpfile.php",
data: {"myData" : myArray},
success: function(data){
alert("Success");
//appends code to end of my webpage, just for testing purposes
$('#button').after(data);
},
error: function(e){
alert("Error")
}
});
PHP:
$data = $_POST['myData'];
//creates xml file
var_dump($data);
The following is copied from the comment so this question can be marked as answered:
It seems like it should be working so I would try a simple, very basic ajax test and make sure at least that is working correctly. I would try to:
1) Get rid of the dataType json line.
2) Take the "/" out of the url.
3) Change the data to {"myData" : "testing"} or even get rid of the data line altogether.
4) Change the PHP to only be: echo "test".
Then see if you alert Success. This will hopefully tell you that your ajax is working. If so, you can start putting your code back in and see where it fails.
The mistake might be:
data: {"myData" : myjsonString}
Try this, assumming that jsonString is a string
data: "myData="+ jsonString
I've tried this many times now, using difference methods and none of them have worked for me, so I'm asking this question.
I have a small form that takes in 4 pieces of information, a persons title, first name, middle name and last name. When I hit a button, a JSON Object is formed, and sent as post data through a jQuery.ajax method.
JSON Sent to PHP file:
{
"title": "Mr",
"firstName":"Banana",
"middleName":"Slippy",
"lastName":"McDougle"
}
Ajax call on button press:
function insertPerson(obj, callback){
$.ajax({
type: "POST",
data: "json=" + JSON.stringify(obj),
url: "insertData.php",
success: function(obj){
if (callback){ callback(obj) };
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
}
I pass in a Javascript Object that is then stringyfied and posted as a parameter name 'json'.
In my php file I assign the posted string to a variable, name $json, I then decode using json_decode(), do some funky business, and send a response back to the browser.
insertData.php:
require ('connect.php');
header('Content-type: application/json');
$json_string = $_POST['json'];
$json = json_decode($json_string);
...do server related inserts/selects etc...
echo json_encode($json->title);
At the moment I just want to return the title property of the json object that was sent in the post request, but anything I return comes back as null. If I echo back the string, without decoding it, then I get the following:
{\"title\":\"Mr\",\"firstName\":\"Banana\",\"middleName\":\"Slippy\",\"lastName\":\"McDougle\"}
If I try to extract values using:
$title = $json->title;
and put that into a MYSQL statement, it's inserted as null or blank, nothing gets input.
Am I doing something wrong? Or have I somehow got an outdated version of PHP to handle JSON? And help is greatly appreciated.
Why do you want to send JSON to the PHP script? What's wrong with using a query string?
$.ajax({
type: "POST",
data: obj,
url: "insertData.php",
success: function(obj){
if (callback){ callback(obj) };
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
This will convert obj to a query string, and then you can just do $_POST['firstName'] and $_POST['lastName'].
I think this is the best shot for you.
jQuery Ajax POST example with PHP
I am trying to retrieve the following json generated in my php script uing jquery. However, I am not being able to display it. If I alert it, it just displays 'undefined'. Using $('#demo').html(data.htmlOutput) to display the html doesn't do anything either. Please can someone point out what I'm doing wrong?
$arr = array('htmlOutput' => '<b>hello</b>', 'no_rows' => 'balh');
echo json_encode($arr);
$.post('get-offers.php', $("#offerForm").serialize(), function(data) {
alert (data.htmlOutput);
alert (data.no_rows)
$('#demo').html(data.htmlOutput);
}
I can see the json response in the FB console,however, it still does nothing.
Tell jquery that you're expecting json, it's the last argument:
$.post('get-offers.php', $("#offerForm").serialize(), function(data) {
alert (data.htmlOutput);
alert (data.no_rows)
$('#demo').html(data.htmlOutput);
}, "json");
You Have tell jquery you are expecting json object, do it with the dataType as follows:
.post('get-offers.php', $("#offerForm").serialize(), function(data) {
alert (data.htmlOutput);
alert (data.no_rows)
$('#demo').html(data.htmlOutput);
},'json'); //<====
dataType: The type of data expected from the server.
docs
I would think jquery will be able to guess it is a json object, because in their docs written:
Default: Intelligent Guess (xml, json, script, text, html).
Well, I guess that that guess isn't that Intelligent... =)
Two options:
First, set 'json' as the last parameter of you $.post to tell it that it is expecting a JSON response.
Second, before your first alert, add this:
var obj = jQuery.parseJSON(data);
Then alert(obj.htmlOutput);
See if that works for you
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".
I'm getting a bit of a headache trying to figure this one out. To request some json-data from a PHP-script via Ajax, I'm using the jQuery function:
$.ajax({
type: 'GET',
cache: 'false',
url: ajaxUrl,
data: dataString,
success: updatePage
});
If I don't set content-type in the PHP header to:
header('Content-type: application/json');
Then my response from the server looks like this:
{"content":"new content"}
And the content-type is automatically set to text/html. When dataType in the jQuery ajax options is unset, it uses a default of 'intelligent guessing'. I'm strongly assuming that jQuery recognizes the response-data as json because updatePage is parsed an object. updatePage uses the JSON js library(json2.js), and does this:
function updatePage(data) {
$dataObj = JSON.parse(data);
}
When the function is called upon ajax succes, everything works fine. No errors.
Here's the strange thing, if I set my header to application/json as above, JSON.parse suddenly reports an error. The exact same error happens if i set my dataType to 'json' in the jQuery ajax request. The response I get from the PHP script when changing these things looks exactly like the one above. The error looks like this in Firebug:
JSON.parse
$dataObj = JSON.parse(data);
Kind of a long one, sorry, but If anyone knows what is wrong their help is greatly appreciated. Thanks for your time.
It's because you end up trying to double-parse the return value.
Both the explicit json data type and usage of the application/json MIME type cause jQuery to parse the returned string into a JavaScript object for you.
So, your usage of JSON.parse(), in these cases, is superfluous.