I need a jsonp response from cross domain url. My jsonp code is here
$.ajax({
dataType: 'jsonp',
async: false,
contentType: "application/json",
jsonpCallback: "domaincheck",
data:{
id:k,
domain:l
},
url: 'http://example.com/param',
success: function (data) {
console.log(JSON.stringify(data));
},
In the php file, the output is like this:
<?php
echo $_GET['callback']."([Correct])";
?>
I knew that the data what I am returning back is incorrect. Because I think we should pass response as json data only. But in this case, sending only "correct" as response, how should we set it, so that we get the response correctly.
The error what I get in console is this:
Uncaught SyntaxError: Unexpected identifier
Related
In php i do echo json_encode($dump);
If echo it out using php i get {"load":"0.64 0.58 0.52 2\/361 12978\n","procs":"8\n"}
Than i make CORS Request using dataType:jsonp
$(function () {
$.ajax({
type: "POST",
ContentType: 'application/json; charset=utf-8',
url: 'http://labs.isaumya.com/loadtest/load',
dataType: "jsonp",
success: function (response) {
console.log(response.data);
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
I get this error on the console:
DEMO
You are dealing with JSON, not JSONP. dataType: "jsonp", should be dataType: "json",
You can remove the data parameter entirely if your server outputs the correct content-type header for JSON (application/json).
JSONP is a hack to work around the Same Origin Policy from before CORS was designed and implemented by browsers. CORS is the modern approach to making cross origin requests. You use it instead of JSONP.
Both CORS and JSONP are technologies that must be supported by the server. http://labs.isaumya.com/loadtest/load doesn't appear to support either. You will have to modify the server if you want it to supply data in JSONP format or grant permission with CORS.
Unrelated to your actual problem:
You have no data parameter so you aren't sending JSON to to the server, remove the ContentType parameter. Since you aren't POSTing any data, you should probably be making a GET request, not a POST request.
I need to save a json object to a file.
Therefore I'm using another PHP script which writes the data to a file. Data and filename are sent by an ajax POST request.
var results = $('results');
var filename = $('#filename').val();
$.ajax({
url: 'jsonWriter.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify([{data: data, filename: filename }]),
success: function(data) {
results.html(data);
},
error: function(jqXhr, textStatus, error) {
results.html("<p class=\"error\">ERROR: " + textStatus + ", " + error + "</p>");
}
});
When I monitor the request in Fiddler, it looks fine and the posted data is correct.
However, somehow the error function is invoked. It outputs
ERROR: parsererror, SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
I copied the posted JSON data from Fiddler into different online parsers, which ensured it is valid.
Why is the error function invoked anyway?
It looks to me like you are expecting the server to return text content, since you are applying it with .html:
success: function(data) {
results.html(data);
},
However, you are telling jQuery to expect JSON data:
dataType: "json",
jQuery is therefore attempting to parse your content returned from the server as JSON and failing. You need to change dataType to either text or html.
I want to get data from the webservices through jquery ajax call(cross domain). After fetching data from webservices, i need to show it as a dataTable using php.
Can anyone help me regarding this or just give me some sampe examples.
my ajax function is as follows:
$.ajax({
type: "POST",
url:"my webservice url",
//data: json,
//contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: 'json',
async:false,
success: function(data, textStatus, jqXHR)
{
alert("Download success");
alert(data);
},
error : function(jqXHR, exception)
{
alert(jqXHR.status);
}
});
$.ajax({
url:"yourPageName.php",
dataType: 'jsonp', // N.B! JSONP It is lower Case OK?
success:function(json){
// json (an Array)
alert("Success");
},
error:function(){
alert("Error");
},
});
For more info please visit here http://api.jquery.com/jQuery.ajax/
Jsonp is better way to do it. But if you really do with json you can add
header("Access-Control-Allow-Origin: *");
to your php code. This way your server will response any request and domain. You can customize
"*" to accept domain.
But be aware this will cause security issue.
I'm trying to post data via ajax, this is my info:
var jsondata =
{"address" : [
{ "id": addid, "streetaddress": streetaddress, "city": city, "state": state, "zipcode": zipcode, "latitude": latitude},
]
};
var jsontosend = JSON.stringify(jsondata, null, 2);
ajax function:
$.ajax({
type: "POST",
url: "process.php",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
data: jsontosend,
success: function(msg){
alert(msg);
}
});
return false;
alert('Data sent');
}
on the php end, when i print_r($_POST) it just says
array(0) {
}
I'm alerting (jsontosend) and its showing me everything perfectly, as well as in firebug using post mothod, its showing all the params sent in a perfect clean manner.
The only way it passes any data is if I use GET method.
Any advice is greatly appreciated!
EDIT: adding POST data from firebug.
this is whats being alerted from the alert function:
{"address":[{"id":1473294,"streetaddress":"3784 Howard Ave","city":"Washington DC","state":"DC","zipcode":20895,"latitude":39.027820587}]}
this is what firebug is showing as whats being passed when using POST method:
myData=%7B%0A++++%22address%22%3A+%5B%0A++++++++%7B%0A++++++++++++%22id%22%3A+76076%2C%0A++++++++++++%22streetaddress%22%3A+%223784+Howard+Ave%22%2C%0A++++++++++++%22city%22%3A+%22Washington+DC%22%2C%0A++++++++++++%22state%22%3A+%22DC%22%2C%0A++++++++++++%22zipcode%22%3A+20895%2C%0A++++++++++++%22latitude%22%3A+39.027820587%0A++++++++%7D%0A++++%5D%0A%7D
and this is the response for var_dump of $_POST:
array(0) {
}
this is a var_dump of $_POST['myData']
NULL
I'm skeptical of the way you're using the contentType property. Try taking out contentType. The default content type is
application/x-www-form-urlencoded (http://api.jquery.com/jQuery.ajax/).
Also, use something like {mydata: jsontosend} for your data property.
$.ajax({
type: "POST",
url: "process.php",
//contentType: "application/json; charset=utf-8",
dataType: "JSON",
data: {mydata: jsontosend},
success: function(msg){
alert(msg);
}
});
Use
data:{myData: jsontosend}
It should send myData as a parameter in your request.
PHP doesn't understand application/json requests (by default).
See this question: How to post JSON to PHP with curl
I found that the comment provided by dkulkarni was the best solution here. It is necessary to read directly from the input stream to get POST data of any complexity. Changing the value of $.ajax({contentType: ''}) did not work for me..
In order to troubleshoot this problem I had set up a controller method to echo back the JSON I was posting to my server. Changing the ContentType header made no difference.
But after reading dkulkarni's comment I changed my server code from this:
return $_POST;
to this:
$data = file_get_contents('php://input');
return json_decode($data);
It worked perfectly.
As dkulkarni commented in his post (Jan 24 at 7:53), the only way to retrieve JSON sent with Content-Type application/json seems to be to retrieve it directly from the input stream.
I made a lot of tests with different approaches, but always when I set Content-Type to JSON, the $_POST in PHP is empty.
My problem is I need to set Content-Type to JSON, because the server (where I don't have access) expects it, otherwise it returns unsupported datatype. I suppose they are retrieving directly from input stream.
Why I have to reproduce that in own PHP file? Because I need to make a proxy for testing issues, but thats not the point of this thread.
Taking contentType out is not a good idea. You DO want to send this data in JSON format. Key is to do what has been mentioned above, instead of trying to access the data on the receiving end (the target php file) with $data= $_POST it is critical to use $data = file_get_contents('php://input');
Here is an example of the entire round trip for a scenario with php and knockout.js:
JS (on requesting page):
function() {
var payload = ko.toJSON({ YOUR KNOCKOUT OBJECT });
jQuery.ajax({
url: 'target.php',
type: "POST",
data: payload,
datatype: "json",
processData: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result);
}
});
};
And then in target.php (the page receiving the request):
$data = file_get_contents('php://input');
$payload_jsonDecoded = json_decode($data
Try removing ' dataType: "JSON" ' from the ajax request and check.
This is my called by post to mi php in the server
$.ajax({
async: false,
type: "POST",
url: "services/ModelsService.php",
data: "{IdModelo: "+$("#brand").val()+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(values){
//do something
}
});
Now when i'm going to uses the value send from the js. always failed appears blank. But the data it's sending good because when i debug the called with charles debugging proxy works well the request
this is my php file
$json = json_decode($_POST,true);
echo $json[1]; //this bring me always blank
What i'm doing wrong in my code
echo $json['IdModelo'];
This is how you get it.
Passing the second argument true to json_decode will return an associative array so you should access array values using associative (string) index.