This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have the following JSON that I receive from a URL, we call the URL here www.blabla.com/testjson
And it returns:
[{"Identifier":1,"Naam":"NOT Given","Adres":"Kopenhagen 9","Postcode":"0000LL","Plaats":"NOT Given","Longitude":"0.00000","Latitude":"0.00000"},
{"Identifier":2,"Naam":"NOT Given","Adres":"NOT Given 1","Postcode":"0000LL","Plaats":"Rotterdam","Longitude":"0.00000","Latitude":"0.00000"},
{"Identifier":3,"Naam":"NOT Given","Adres":"NOT Given 6","Postcode":"0000LL","Plaats":"Rotterdam","Longitude":"0.00000","Latitude":"0.00000"},
{"Identifier":4,"Naam":"NOT Given","Adres":"NOT Given 1","Postcode":"0000LL","Plaats":"Den Haag","Longitude":"0.00000","Latitude":"0.00000"},
{"Identifier":5,"Naam":"NOT Given","Adres":"NOT Given 218","Postcode":"0000LL","Plaats":"Zoetermeer","Longitude":"0.00000","Latitude":"0.00000"}
];
I want to retrieve this JSON en return this result, but I get UNDEFINED, this is my code:
$.each("www.blabla.com/testjson", function(index, element) {
$('.result').append(element.Naam);
alert(element.Naam);
});
You also need to check if the user cookies are true or else it won't return something, I don't do this because I work with phonegap and jquery mobile. Can that be the problem?
Try using the method $.getJSON:
$.getJSON('http://www.blabla.com/testjson.json', function(data) {
$.each(data, function(key, val) {
$('.result').append(val.Naam);
alert(val.Naam);
});
});
For more information, check the online doc: http://api.jquery.com/jQuery.getJSON/
PS: Make sure that you added the website www.blabla.com to your whitelist exception.
For more information about Phonegap whitelist exceptions, check the online doc (the following link is for Phonegap / Cordova version 2.1.0): http://docs.phonegap.com/en/2.1.0/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide
Your code will loop over each character of the param string "www.blabla.com/testjson", returning 'undefined' because by writing element.Naam you're trying to access a non existent property named 'Naam' of a character string.
You need to load the external json content by using an ajax call and parse it.
Here is a longer alternative to Littm's answer if you're interested in handling errors too:
$(document).ready(function()
{
$.ajax(
{
type: "GET",
url: "data.json",
data: "nocache=" + Math.random(),
// dataType: "json",
// the above requires 'application/json' as Content-Type headers
// see 'reference A' in the footer notes
// if you active this, please modify following code accordingly
success: function (source, textStatus, jqXHR)
{
var data = jQuery.parseJSON(source);
$.each(data, function(index, value)
{
alert(index+" "+value.Naam);
});
},
error: function(data)
{
// alert("ERROR");
}
});
});
Notes:
1. Reference A
EDIT:
To get more info from error, add the following:
$(document).ajaxError(
function (event, jqXHR, ajaxSettings, thrownError)
{
console.log(event);
console.log(jqXHR);
console.log(ajaxSettings);
console.log(thrownError);
});
Then use the chrome console.
EDIT:
If I type the url you provided in a browser, I am redirected to a login page.
I think that your ajax code is getting this HTML document, too.
Try to check your session: you can add a div in your code and load the content of your url using curl inside this new div. Until you don't see your json code inside this div, your session variables are not working properly.
If curl will get correctly your file content, so will do ajax.
EDIT:
See? Your problem is to correctly login into the webservice from which you are trying to get the json file.
Your friend is right.
You have to set correctly your $_SESSION in PHP which basically use cookies to retain session info.
Try to correctly:
session_start() ;
at the beginning of your php code, before using ajax.
References:
- php.net session_start
- PHP session not working with JQuery Ajax?
Please note that this will work only within the same domain:
Why jquery ajax not sending session cookie
If you are using different subdomains you can try to use
setcookie
References:
- php.net setcookie
- Cross domain cookie access (or session)
As far as I know there's no way to set cookies within different domains.
If you are in this situation, I suggest you to have a look at SimpleSAMLPHP descbribed here:
cross domain cookies
Good luck :)
Related
DISCLAIMER: This question is a question about question. So that makes this question a meta question. It does not have any connection to the previously asked questions. If you find any resemblance, lemme tell you one thing- it's purely coincidental.
I want to make an AJAX request from my web page. I have been trying to do this, but none of the methods worked perfectly. The only post that I found something close to reality is this.
I tried various other methods from SO & other similar sites, but all of those posts said only one thing to me.
"No 'Access-Control-Allow-Origin' header is present on the requested resource."
I know now you are gonna mark this question as duplicate since there are loads of questions similar to this. Now..Lemme tell ya' one thing. I tried every piece of sh*t I found in SO, but none of 'em gave me the result that I was looking for. It's not because they all are wrong. It because I ain't got no knowlegde on how to use 'em. Then finally...I settled on the link I provided above. It's easy..but I need to know certain things about the code.This is the first time I am hearing the beautifully sodding acronym- CORS. So, if anyone can help me understand the questions I raise, Up votes for all of ya'. I wanna resolve this son-of-a-b*tch question before I celebrate my birthday for the third time this year. I will tell ya' what all I have-in form of resources & questions.
1) A rotten server located at Elizabeth town.
2) I need to access it.
3) I am planning to make a HTTP GET request.
4) I have a url. (eg. http://whereismyweed.com)
5) I store it into a JavaScript variable. var stoner='http://whereismyweed.com'
6) I have a HTML div tag in my webpage. (<div id="myprecious"></div>)
7) I wanna display the response I get from the server inside of 'myprecious' div.
8) And last but not the least... my AJAX function. (Courtesy: some website I visited)
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
What is 'myData'?? What does it contain. How can I get the response for this request? What is 'setHeader'?? Does it have any significance??? How can I display the response inside myprecious div? What changes should I make in the function? Is this function correct?
Too many question, Right???? Well...I need only one common answer for it?
Your function is correct.Follow below steps do achieve your goal-
//for getting response modify your code like
success:function(response){
alert(response);
$('#myprecious').html(response); //myprecious is id of div
}
// myData variable is jSon object which contains request parameter has to send.Eg.
var myData = {'first_name':'Foo','last_name':'Bar'} // now on server first_name and last_name treated as request parameter.
// If server not required any special headers to validate request 'setHeader' does not require. by default $.ajax will take care of it. you can remove it.
/// final code looks like
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function(response ) { $('#myprecious').html(response);
},
error: function() { alert('Failed!'); }
});
I've been on this for hours already, I've read tons of articles and still cant figure it out.
Here's the deal.
I am working with Chrome extensions and I want to do a call to my server that returns me a js object. I dont want to inject this into the page, but I want to be able to use it within my content script.
NOTE: I cannot use eval() (I have tried though) and I cannot use jsonp
I am using a framework so my headers arent set here, but they set to return application-type application/javascript utf-8;
my php side looks like this:
$refererObj = 'var refererObj = {
myFunc: function () {
console.log("hello");
}
};';
echo $refererObj;
my js looks like this
$.ajax({
url: myUrl,
crossDomain: true,
data: postData,
dataType: "json",
type: "POST",
}).done(function(data){
eval(data);
console.log(data);
console.log(refererObj);
});
The first console.log gives ["var refererObj = {↵ getProducts: function () {↵…(products);↵ console.log("hello");↵ }↵};"]
The second gives "Uncaught ReferenceError: refererObj is not defined"
I get the response as a string with the javascript object and everything is all good until I actually want to "convert" the string into a usable code.
Any help would be really great.
Thanks
You actually can use eval() if you relax the default Content Security Policy with unsafe-eval. But it's a big hammer that's best avoided.
You can use JSONP, again, if you can serve it off an https server and add it to script-src of the Content Security Policy. This is slightly less of a security risk.
I doubt there is any other solution: anything you load off an external server is to be considered tainted and if you find a way to execute it - congrats, you just bypassed CSP in Chrome and should go claim your bug bounty.
Please note that in case of simply JSON data it's all moot, you can just load it with XHR and JSON.parse it. But your example contains code.
what I need to do is read the content of a "public" google spreadsheet (by public I mean that I saved the sheet clicking on "File > Publish to the web", so it's accessible without the need to be logged in into a google account), and, why not, write something into it too.
googlin' around, I found that I can access the sheet and get the xml equivalent of the sheet content with something like
https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values
It works great if I load that url into a browser. But I need to find a "javascript-way" to get and handle the returned value, ie the xml (or json, but xml would be preferable).
I tried to use an ajax call, but I think there's something messy with the protocol.. I can't get the server response correctly.
$.ajax({
type: "GET",
url: "https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values",
success: function(data){alert("yeah");},
error: function(){alert("fail..");},
dataType:"xml",
});
I also tried to get the json instead of xml, adding "?alt=json" to the url and changing the datatype, but I still have the problem..
Any idea / suggestion?
Thanks in advance, best regards
You need to request with a JSONP call and you need to specifiy a callback - method. This can be done in jQuery using:
var url = 'https://spreadsheets.google.com/feeds/list/<CODE>/od6/public/values?alt=json-in-script&callback=?';
jQuery.getJSON(url).success(function(data) {
console.log(data);
}).error(function(message) {
console.error('error' + message);
}).complete(function() {
console.log('completed!');
});
Documentation and samples for google spreedsheets .
I have an ajax script that sends some data to an external URL. The external URL is hosted on the same server, however the domain is different than the source of the ajax call.
This is working perfectly in Firefox and Chrome. However in IE The ajax call does not go through, and the Return False function does not either work (once the ajax call fails).
Below is my code:
$.get('http://myexternaldomian.com/feedback/save.php', {
answer: $('#answer').val(),
page_url: pathname
});
// Keeps the user on the page
return false;
When I try removing the http:// from the ajax url, the return false does work.
Any help on this would be greatly appreciated. Thank You
From jQuery documentation
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain, or
protocol.
and Same Origin Policy on Wiki
I'm surprised any of them are working. Browsers generally don't allow ajax calls to a domain other than the one the current page came from.
The main exception to this rule is if you make an ajax call using jsonp (json with padding). You can do this with jQuery, here's how. Look under the dataType option.
(this is copypaste from my another similar answer). You could try enabling "jQuery.support.cors=true" flag and see how it goes. I use jQuery v1.7.2.
I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.
server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
you may set flag once or everytime before using jQuery ajax function
now I can read .xml document in IE and Firefox. Other browsers I did not test.
response document can be plain/text, xml, json or anything else
Here is an example jQuery ajax call with some debug sysouts.
jQuery.support.cors = true;
$.ajax({
url: "http://localhost/getxml.php",
data: { "id":"doc1", "rows":"100" },
type: "GET",
timeout: 30000,
dataType: "text", // "xml", "json"
success: function(data) {
// show text reply as-is (debug)
alert(data);
// show xml field values (debug)
//alert( $(data).find("title").text() );
// loop JSON array (debug)
//var str="";
//$.each(data.items, function(i,item) {
// str += item.title + "\n";
//});
//alert(str);
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
http://en.wikipedia.org/wiki/Same_origin_policy
I dont think it should work on Chrome or Firefox, unless you testing on localhost or something like that, this would be against the crossdomain policy.
What you need is to proxy it inside the same domain, use php to connect to the destination you need and call the url from the same domain.
save_cross_domain.php -> connect through server to the desired url
then ajax calls save_cross_domain.php
you should add a
callback=?
to your url and handle this on the server side.
I did this once for a java servlet, and when the callback param was included I added an extra pair of parenteses around the json response..
hope it helps!
A couple of things:
The answers/conversation for this question has gone a bit out of context. Actually from the question it was more implied how to make ajax calls in IE. [Atleast modify the question title, else the question is very localized]
A couple of solutions to this cross-domain issue:
CORS[compatible after IE7]
JSONP [ here actually the browser takes in the input thinking it is a script]
server side encoding
I have the following code I am using to send data to a MailChimp Newsletter List (API v3). Everytime I remove the type: POST from the function it attempts to post the data via GET and it sends the data properly (ok response in MailChimp API dashboard). When testing this in the browser (FF) I get a .part file with "true" response.
$(function(){
$("a#test").click(function(e){
e.preventDefault()
data = {
"apikey" : "667378947",
"id" : "90298590285",
"email_address" : "test#getmoxied.net",
"output" : "json"
}
$.ajax({
type: "POST",
url: 'http://us2.api.mailchimp.com/1.3/?method=listSubscribe',
data: data,
success: function(data){
alert(data);
},
error: function(){
alert("err");
}
})
});
});
Im pulling my hair out on this one, any insight is greatly appreciated.
Thanks in advance,
JN
There is an undocumented endpoint that uses JSONP to do cross-domain ajax requests.
Just change 'post?' to 'post-json?' and add '&c=?' to the end of the standard url to get the JSONP endpoint. This doesn't requires the API key to be exposed on the client-side, or the creation of a server-side view.
I wrote a jQuery plugin that uses this method, if that's useful at all
https://github.com/scdoshi/jquery-ajaxchimp
The main issue is what jc commented on your original post - this simply won't work due to Same Origin Policy issues. Firebug is not as vocal about why the GET call fails, but that's why it returns no data. If you watch that with the POST, you'll see Firefox doesn't even make the call. Chrome's js console on the other hand straight explains the Same Origin policy to you.
All in all, this is a very good thing if for no other reason than it prevents you from publicly publishing your account's API Key, which is a very bad thing to do. If the reason why doesn't immediately sink in, go read through the large number of methods available in the API and then realize that all you need to access them is that API Key.
The correct way to do this is to POST data back to your server, then make the request from there. There are several fully built PHP examples (one using jquery, even), here.
e.preventDefault();
data = {
"apikey" : "667378947",
"id" : "90298590285",
"email_address" : "test#getmoxied.net",
"output" : "json"
};
Could be? Semicolon is important. Hehe