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
});
Related
I just started to work on calls to a php file which is present in a different server. I am aware of CORS which is essential for cross domain requests. I have been trying to call this file through ajax methods refering to other websites and tutorials and I have seen discussions to find a solution but they are not working for me. Please help.
here is my calling method:
$.ajax({
type: "GET",
url: "http://cs-server.usc.edu:27952/ResponseProg.php?callback=?", //Relative or absolute path to response.php file
datatype: "jsonp",
data: dataInput,
jsonp:'jsoncallback',
crossDomain:true,
success: function(data)
{
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found")
{
var paginate=setPager(0);
$("#pgn").html(paginate);
}
},
error: function() {
$("#rtrn").html("Data not retrieved successfully");
}
});
Here is my PHP code snippet:
<?php
#code for data processing...
$rsltjson = json_encode($result,JSON_UNESCAPED_SLASHES);
echo $_GET['jsoncallback']."(".$rsltjson.");";
?>
I am trying to accomplish this by using JSONP. Should I have any headers?
Are there any errors in my code?....How can I accomplish this? dataInput is the serialized form of form data
The CORS way
You need to put the appropriate header in your php script and output only the JSON:
<?php
header('Access-Control-Allow-Origin: *');
// rest of the code
// output JSON only
echo $rsltjson;
?>
Then using a XMLHttpRequest/ajax call should retrieve the data just fine as JSON without resorting to JSONP.
Mozilla has plenty to read about it
The JSONP way
Since the whole point of JSONP is to bypass cross-domain restrictions, calling a JSONP resource with XMLHttpRequest/ajax, a method in which cross-domain security is fully applied (presumably), is completely useless.
JSONP works by injecting code directly into your page, calling a function that you defined, which is why a JSONP url takes an argument. Therefore, the correct way to call your JSONP url is this:
<script>
function myDataFunc(data) {
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found") {
var paginate=setPager(0);
$("#pgn").html(paginate);
}
}
</script>
<script src="http://cs-server.usc.edu:27952/ResponseProg.php?jsoncallback=myDataFunc"></script>
The JSONP url will return something that looks like this:
myDataFunc({"a":"fhsfg","b":"qfdgers","c":"difgij"});
Since it is included as a script, it will be executed directly in your page, calling the function myDataFunc() that you defined earlier.
Also note that your php file use the GET parameter jsoncallback while your javascript calls the url with the parameter callback, which would not work.
Finally, you use jQuery.parseJSON(), which produces this error from your code:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
The reason can be found in the jQuery docs:
jQuery.parseJSON( json )
Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
Passing in a malformed JSON string results in a JavaScript exception being thrown.
Your php script feeds your callback with a JSON object
{"a":"fhsfg","b":"qfdgers","c":"difgij"}
rather than a string representing a JSON object
'{"a":"fhsfg","b":"qfdgers","c":"difgij"}'
Note the surrounding quotes, which makes this data a string. We fix this in php by adding the quotes around the data:
echo $_GET['jsoncallback']."('".$rsltjson."');";
Obviously if your JSON data contains single quotes, you will have to escape them.
i am a new php developers i was trying to create a simple system where i use php to extract database from mysql and use json in jquery mobile.
So here is the situation,
I've created a custom .php json (to extract data from mysql) on my website and i've successfully upload it onto my website eg: www.example.com/mysqljson.php
This is my code extracting mysql data `
header('content-type:application/json');
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('mydb');
$select = mysql_query('SELECT * FROM sample');
$rows=array();
while($row=mysql_fetch_array($select))
{
$rows[] = array('id'=>$row['id'], 'id'=>$row['id'], 'username'=>$row['username'], 'mobileno'=>$row['mobileno'], 'gangsa'=>$row['gangsa'], 'total'=>$row['total']);
}
echo json_encode($rows);`
Which in returns gives me the following json # http://i.imgur.com/d4HIxAA.png?1
Everything seems fine, but when i try to use the json url for extraction on jquery mobile it doesn't return any value.
i extract the json by using the following code;
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
jsonCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
},
error: function(e) {
console.log(e.message);
}
});
}
The json.id # #current_temp and json.id.username # #current_sum dint return any result on my jquery mobile page.
I suspected i didn't extracted the json url correctly, but im not sure, could anyone help me identify the problem?
Thank you.
jsonp expects a callback function to be defined in the json being retrieved - for ecample see here.
Your data print screen is actually plain old fashioned json, not jsonp.
So I see 2 options:
change the php data to render jsonp (this assumes you have control over data source).
change your jquery request to expect plain old fastioned json (this assumes client and server are on same domain, otherwise CORS error happen), e.g,,
$.get(forecastURL)
.then(function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
})
.fail(function(e) {
console.log(e.message);
});
First of all, you don't have to use jsonp to retrieve JSON. You could just do a simple Ajax Call. jQuery convert automatically your json string to a json object if your HTTP response contains the good Content-Type. And you did this good in your PHP call.
I think your problem comes from your json data analysis in your javascript success callback. The json generated is an array containing some user objects. In your code you don't work on one item of the array but you directly call .id or .username on the array. So javascript give you undefined values.
Here is an example displaying the data for the first item (index 0) of your json array. You have after that to choose for your own purpose how to treat your array objects but it's an example:
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
success: function(json) {
console.log(json);
// See, I use [0] to get the first item of the array.
$("#current_temp").html(json[0].id);
$("#current_summ").html(json[0].username);
},
error: function(e) {
console.log(e.message);
}
});
}
I would like to create an app that will send out a get request, then take the response and display it on the page,
this is part of my learning process, ultimately i would like to have the response be parsed and turned into
elements etc. but for now i am having trouble accessing the information within the response.
How can i alert() any of the results in the response?
the results of the script below ranged from undefined, to [object ojbect]
<script type="text/javascript">
var bbz;
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "MyDomain - its defined and on the web",
success: function(response) {
bbz = response;
alert(bbz.length);
alert(bbz);
alert(bbz[0]);
}
});
</script>
It looks to me like you are expecting a JSON response...
I am assuming this because of the way you are accessing properties of the response object -
bbz = response;
alert(bbz.length);
You'll want to set your dataType to "json".
If you set the dataType property to html, you should be able to simply return HTML.
You set dataType: "jsonp" which attempts to parse a jsonp object out of the data that is to be returned. However, what you really want is the markup that is in the file you are requesting data from. In order to do this, you must state the correct return type, so that the AJAX knows what data to give you, i.e. you tell the AJAX how to parse the data.
In php, I have an array like this :
$arr['a'] = "some big data so may contain some chars that bring us headache"
$arr['b'] = "some big data same as above"
$data = json_encode($arr)
echo $data
My javascript code containing a jquery ajax call, $.ajax . It calls the file containing the above php code so, on success, the json_encoded(by php) is returned to my javascript variable . In my javascript file, I am doing like this :
jsdata = JSON.parse(data); //Getting error here
$.ajax({
type: "post",
data: jsdata,
url: "url",
crossDomain: true,
dataType: 'jsonp'
}).done(function(d) {
print("success");
});
From the above code, in the line jsdata = JSON.parse(data), I am getting errors something like
Error : UNEXPECTED TOKEN <
As the data contains lot of different content, its normal to get those errors . They need to be escaped properly . Can anyone tell me how to do that correctly . Whatever the data may be , I shouldnot get error regarding the data .
Thanks
Well, a couple of things you should probably know jsdata = JSON.parse(data); tries to parse whatever json string you assigned to data, and return it as a JS object. I think you want to do the opposite: jsdata = JSON.stringify(data);
Besides, since you are using jQuery, you could just leave that line out: jQuery will convert the data to the appropriate format before sending the request anyway, no need to bother with parsing or stringify-ing it yourself.
Yeah you forgot the ; at the end of two lines, so PHP is outputing an error, which is no JSON-compliant.
Always do this :
Catch errors and output them in a way that is understable by your application (a 5xx status can be enough)
Next time you have this, use Chrome Developper tool or Firebug to see what your app really returns
Also, you're outputing json, not jsonp which is different and what your app expects
$.ajax({
type: "post",
data: jsdata,
url: "url",
crossDomain: true,
dataType: 'jsonp',
success: function(d) {
print("success");
}
})
try it this way
This is much more simple than it might seem.
Call urlencode($arr['a']) and urlencode($arr['b']) (for each data value in $arr) before encoding the JSON and echoing $data to the JavaScript. This will URL-Encode the data in the array so that it will cause you no problems.
When you are done parsing the JSON, you will have to call the JavaScript function unescape(string) on each of the large data values. This will return them to the way they originally were. It's a sort of superhero-team-up of PHP and JavaScript!
I'm using Jquery and PHP together to make some Ajax calls. This is similar to something I'm doing:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://example/ajax",
data: { test: test },
cache: false,
async: true,
success: function( json ){
$.each( json.rows, function( i, object ){
//Example: object.date
<?php date('g:ia', $objectDate ) ?>;
});
}
});
What I need is to pass some JSON objects to PHP, for example object.date to $objectDate and then do something with them. Is this possible?
PHP is executed on the server, JS on the client. Once the server has processed the AJAX call that's it, it doesn't know anything anymore about what happens on the client.
You are already passing data from JS to PHP with your AJAX call. If you need to process that data in PHP do it before you return the call, it makes no sense to return a JSON object only to re-process it in PHP.
In summary what you should do is:
Pass some data from client to server with an AJAX call
PHP processes these data and returns a JSON object
JS processes the JSON object and, for instance, modifies the HTML of the page.
If you need to further process newly generated data with PHP do other AJAX calls.
Also, if you need JS to use any variable generated in point 2, just return it in the JSON object, that is what it is for.
Here's a basic rundown of going from JS to PHP, and PHP to JS:
To transfer an object from Javascript to PHP (and perserve it), you need to encode your data using JSON.stringify:
var data = { message: "Hello" };
$.ajax({
data: { data: JSON.stringify(data) },
// ...
});
Then, in PHP, you can use json_decode to convert the the posted JSON string into a PHP array that's really easy to work with:
$data = json_decode($_POST['data'], true);
echo $data['message'];
// prints "Hello"
To send JSON back as the response to the browser (for your success callback), use json_encode like so:
header('Content-type: application/json');
echo json_encode(array(
'message' => 'Hello, back'
));