I have JSON file generated on my server , but I want to access that data from other host . What should I do on my server , or JSON file to make that data accessible from other domains like JSONP ?
Assuming it's exposed by some web-accessible method, you need to accept a callback (or similar) parameter which then just becomes a wrapper to the JSON data. e.g.
If you had:
/some/service.json
Which returned:
{"this":"is","JSON":"data"}
You then allow the service to be passed a callback:
/some/service.json?callback=foo
Which in turn results in:
foo({"this":"is","JSON":"data"})
That's all there really is to making the response adhere with JSONP.
i think this below code help you
$.ajax({
type: "POST",
url: "xyz.com",
data: jsondata,
dataType: "jsonp",
success: function(data) {
if(data.flag == true){
alert(data.msg);
} else {
alert("not sucess");
}
}
});
Related
So i am not sure if i am doing this right.
I want to send markup over HTML (i am trying to create a widget)
Here is the mocky response that i am expecting
so I create a simple jquery get like this
var jsonp_url = "http://www.mocky.io/v2/5c9e901a3000004a00ee98a1?callback=myfunction";
$.ajax({
url: jsonp_url,
type: 'GET',
jsonp: "callback",
contentType: "application/json",
success: function (data) {
$('#example-widget-container').html(data.html)
},
error: function (data) {
alert('woops!'); //or whatever
}
});
then created myFunction
function myfunction(data) {
console.log(data);
}
The problem being that while, i get the response it comes as a string instead of a json or function. i am not sure how to extract the json from this (unless i do string manupulation).
Any pointers would be helpful.
JSFiddle here
P.S. Per https://www.mocky.io/ ,
Jsonp Support - Add
?callback=myfunction to your mocky URL to enable jsonp.
Delete function myfunction.
In the URL, replace callback=myfunction with callback=?.
jQuery will generate a function (your success function) and a function name for you.
To successfully use JSONP (e.g. via jquery - $.ajax ... etc.) must always be that the requested page is designed to provide data corresponding to this format?
In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also will I get an error?
This question might seem trivial to some users, but I'm starting right now to learn these technologies, and the matter is a bit complicated.
Based on these (ref1 ref2) references it would seem that there must be consistency between the request with JSONP and implementation of the server response.
Edit
I have this jQuery request
$.ajax({
url: "https://sites.google.com/site/problemsstore/javascript/test.js",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
And I have loaded in https://sites.google.com/site/mysite/javascript/test.js?attredirects=0&d=1 this test.js file:
function myCall(data) {
console.log('succeed');
}
myCall({ some : "data" });
When I am connected I hope to obtain as console's output: succeed succeed.
Instead this is what I get:
succeed
failed
Edit2
$.ajax({
url: "https://sites.google.com/site/bentofelicianolopez/jscript-jsonp/test.js?attredirects=0&d=1",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
jsonp: 'myCall',
//contentType: 'application/json',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
The .js file:
myCall({ some : "data" });
The output:
failed test4.html:94:9
ReferenceError: myCall is not defined /*this is the syntactical error of which I said*/
test.js:1:1
To successfully use JSONP (e.g. via jquery - $ .ajax ... etc.) must always be, that the requested page is designed to provide data corresponding to this format?
Yes. A request for JSONP will only work if the response is expressed as JSONP.
In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also I will get an error?
You can have a static JavaScript program that conforms to the JSONP format (it requires hardcoding the callback function name), so not necessarily.
So I am using ajax to post a serialised form to a php script and then on success alert the returned data.
My code works fine on my local environment, but uploaded, the eval() function mucks everything up.
here is my code:
function post_that_shit(formIdToSerialize, postUrl) {
var serializedData = $("#"+formIdToSerialize).serialize();
var post_url = postUrl+".php";
//alert(serializedData + "\n" + post_url);
$.ajax({
url: post_url,
type: "POST",
data: serializedData,
success: function(data){
data = eval('('+data+')' );
console.log(data.msg);
if(data.reload == 'yes'){
window.location.reload();
}
if(data.relocate != 'no'){
window.location.href = data.relocate;
//alert(data.relocate);
}
if(data.msg != 'no'){
$(".message").html(data.msg);
//alert(data.msg);
}
//alert('relocate: '+data.relocate);
}
});
}
So it is pretty simple.
The php echo out a json encoded array like so:
echo json_encode(array('msg' => $errors, 'relocate' => 'no'));
And depending on what is echoed, the msg is displayed or the user relocated.
Why do I get the error of SyntaxError: Unexpected token ')' when I use the code online?
Locally it works just fine :(
Thanx for your help
Chris
You don't need to use eval(). Just set the dataType option to 'json' and the data will be internally parsed to an object by jQuery
$.ajax({
url: post_url,
type: "POST",
dataType:'json',
data: serializedData,
success: function(data){
console.log(typeof data); // returns "object"
In addition setting the proper content type header for application/json at server also helps
I don't know why you need the eval() function in that place. It's a wrong coding. Your solution is put the data type to JSON and the ajax function treats automatically as a json:
$.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedData,
success: function(data){
console.log(data.msg);
if(data.reload == 'yes'){
window.location.reload();
}
if(data.relocate != 'no'){
window.location.href = data.relocate;
//alert(data.relocate);
}
if(data.msg != 'no'){
$(".message").html(data.msg);
//alert(data.msg);
}
//alert('relocate: '+data.relocate);
}
});
First of all, eval is evil. Don't use it... never ever! It's like a bomb ready to detonate.
Secondly, parsing json can be done natively in Javascript. No need for eval.
You can use JSON.parse and it will return you an object parsed by the string containing the json text.
eval is used to evaluate code, in other words, it is executing javascript not json. When eval returns an object, it is simply a side effect of JSON being a subset of JavaScript. In other words, any string formatted as json can be evaluated to JavaScript. But JavaScript cannot be formatted to JSON. There is no representation of Date, Function and many more complex objects. That said, when using eval, you're actually executing JavaScript and that is the big problem here. It could execute potentially dangerous code while parsing JSON simply requires parsing data into a data structure and nothing more.
Here more about JSON: https://fr.wikipedia.org/wiki/JavaScript_Object_Notation
So it would allow anyone to add somewhat some javascript that would then get executed by your use of eval. It could allow someone to execute code on the browser of other users. It could be used to steal passwords for example or steal any kind of private information that wouldn't be accessible otherwise.
jQuery on the other hand allow you to parse json natively by using the dataType attribute as 'json'. Like this:
$.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedData,
success: function(data){
console.log(data.msg);
Or using JSON.parse
$.ajax({
url: post_url,
type: "POST",
data: serializedData,
success: function(data){
data = JSON.parse(data)
console.log(data.msg);
Also as charlie pointed out, parsing by ourselves JSON means that we have to wrap it in a try catch, because parsing might fail if the json isn't valid.
But using jQuery gives us a way to handle that easily.
You could rewrite your code such as this:
var req = $.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedDate
});
req.done(function (data) {
// Success
});
req.fail(function () {
// Error something went wrong
});
The advantage of using the promise form is that you can chain calls to have clean async code instead of the callback hell and infinite function nesting.
I am using below code to access rest service hosted on another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
I am able to get the data correctly, but I get this error in firebug in mozilla:
SyntaxError: missing ; before statement
{"Hello":"World"}
Can anyone suggest me what I am doing wrong here? Even though Json data is valid. I tried all the suggestions posted in this question But still I am getting same error.
If it's really JSON you ask for, don't set "jsonp" as dataType, and don't provide a callback :
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
the format of JSON and JSONP are slightæy different
JKSONP is a function invocation expression
callback({"hellow":"world"});
whereas JSON is simply a serialized object
{"Hello":"world"}
fromyour posting it would seem that the server is returning JSON and not JSONP
So you either need to change the server to reply correctly (The actual callback name is a get parameter to the request). You should do this if you are using the ajax call across domains
If you are not using ajax across domains stick to regular JSON
I have a mobile application and I have a lot of data that I am putting in to a JSON object to store in localStorage. I need to get this data to PHP to process it. I have chosen to use jQuery.ajax to send the data as a JSON object to PHP. However, when I run the function, it gives a success message, but does not go to the url specified. I have a lot of PHP experience but this is my first JS intensive project.
Here is my JS code:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
ATRdataJSON is a JSON object that has several JSON objects nested inside.
The URL may not be pointing where you think it's pointing. Try:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "/email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
i'm afraid you cannot send the json object without stringifying it, it may be sent but as a string [object] try to check it first then you may make sure of the url is absolute to make sure it goes to the right controller.