$('#requestButton').click(function() {
$.get('ajax.php', function(data) {
alert(data);
});
});
alert() doesn't showing. What's the problem?
The problem is that your server is claiming:
content-type: application/javascript
But you are sending back a JSON document. jQuery won't populate data when it gets (what it thinks is) a JavaScript program back from the server.
You need to send the correct content type, which is application/json.
Using getJSON or specifying "json" are hacks to tell jQuery to disbelieve the content type and parse in a different data format, but you should fix the server so it tells the truth about the content instead.
Instead of :
$.get
use :
$.getJSON
As you mentioned in the comment section about returned data is json.
Or add a dataType in the $.get() call:
$.get( "ajax.php", function( data ) {
console.log(data);
}, "json" ); //<-----------add dataType here
Related
I send ajax to url , but i get error.
Here is my code:
$.ajax({
url: "http://webrates.truefx.com/rates/connect.html?q=ozrates&c=EUR/USD&f=csv&s=n",
dataType : 'jsonp',
success: function (data) {
alert(data);
}
})
Maybe i doing something wrong?
In order to access data using JSONP, the server you are requesting the data from must format its response as JSONP.
You are getting an error because the response is not JSONP (it is CSV, which you asked for explicitly when you put t=csv in the query string).
Either:
Use a different method to get the data
Change the server so it responds with JSONP formatted data
The following is the response I'm receiving in my AJAX success function:
"{"success":true,"data":{"id":1841,"title":"atitle","filename":"filename.jpg","url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename.jpg","link":"http:\/\/example.com\/?attachment_id=1841","alt":"","author":"21","description":"","caption":"","name":"filename-39","status":"inherit","uploadedTo":0,"date":1415555051000,"modified":1415555051000,"menuOrder":0,"mime":"image\/jpeg","type":"image","subtype":"jpeg","icon":"http:\/\/example.com\/wp-includes\/images\/media\/file.png","dateFormatted":"November 9, 2014","nonces":{"update":"b832c2939d5","delete":"83dda46357e","edit":"51ac41b11c6"},"editLink":"http:\/\/example.com\/wp-admin\/post.php?post=1841&action=edit","meta":false,"authorName":"Some One","filesizeInBytes":10755,"filesizeHumanReadable":"11 kB","sizes":{"thumbnail":{"height":90,"width":90,"url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename-90x90.jpg","orientation":"landscape"},"full":{"url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename.jpg","height":260,"width":236,"orientation":"portrait"}},"height":260,"width":236,"orientation":"portrait","compat":{"item":"","meta":""}}}"
I'm trying to update the src attribute of a particular image on my page using the data that is returned in this response. For example:
$( '#myimage' ).attr( 'src', response.data.url );
The problem is, I get the error Uncaught TypeError: Cannot read property 'url' of undefined
I'm sure response.data.url is wrong. How can I get the URL from the response so that I can update the image's src attribute?
You might be able to take advantage of jQuery's getJSON method. When you're using ajax, you are only receiving a string response, so you would first have to parse it as json using parseJSON. However, getJSON will do parseJSON for you.
$.getJSON('my/service', function(data) {
$('#myimage').attr('src', data.url);
});
yo could use
x=$.parseJSON(response)
and this will convert the json string to a valid json objet, if there is an error will throw an exception you can use try{}catch(e){} to fix it
try{
var x=$.parseJSON(response);
}catch(e){
console.log(e);
}
use JSON.parse to parse as an object, your returned data is string:
response=JSON.parse(response);
$( '#myimage' ).attr( 'src', response.data.url );
The simple way is to use an AJAX request like this:
$.post('remote_url', {key:value}, function(response){
if(response.success) {
$('#myimage').attr('src', response.data.url);
}
}, 'json');
In this example, I've used $.post and you didn't provide enough information about the request type so it could be a $.getJSON request as well. Also, {key:value} is an object which will be passed to the server if required. So, use it if you pass any data to server, otherwise remove it.
In this example, 'json' is being used as data type so the response will be parsed by jQuery also if you use $.getJSON then the response will be parsed but in this case, you don't need to use 'json' as the last parameter. For example:
$.getJSON('remote_url', function(response) {
if(response.success) {
$('#myimage').attr('src', response.data.url);
}
});
Note: getJSON loads JSON-encoded data from the server using a GET HTTP request. So, for a POST request use $.post instead.
This is more a question of procedure than anything else. I'm curious why this happens and I can't seem to find any documentation on this "feature" within the ECMA script documentation.
When I make an AJAX call within jQuery to my server, it returns the following JSON response to the page:
{"version":"v1","status":"OK","timestamp":"2013-02-14 10:32:45","data":"true","error":""}
With this string I have to call jQuery.parseJSON(string); to get it as an object, and the be able to reference it as an object.
However, when my server returns something like this:
{"version":"v1","status":"OK","timestamp":"2013-02-14 10:12:19","data":{"a":"asgsadfga","b":false,"c":[]},"error":""}
Javascript automatically loads this an an object without the need to parse. It would seem that because this example returns a nested object, despite the fact it was returned from the server as a string, Javascript will immediately recognize that, and parse the string for me.
Is this expected functionality, and if so, can anyone point me to the documentation of this?
EDITED:
Here is the offending AJAX call:
jQuery.ajax({
url: url,
type: 'GET',
async: false,
success: function (result) {
console.log(result)
}
Make sure that your server sets the proper Content-Type response HTTP header:
Content-Type: application/json
So that jQuery will automatically parse the JSON string returned by your server to a javascript object which will be passed as argument to your success callback.
Or if for some reason you've got some broken server side script which you have no control over you could set the dataType parameter to force jQuery to parse the result as JSON:
$.ajax({
url: '/script.cgi',
type: 'POST'
dataType: 'json',
success: function(result) {
// result will be a javascript object
}
});
But obviously the proper thing to do is to fix your server side script to return the proper Content-Type response header.
According to ajax() in jQuery API Documentation under dataType:
dataType (default: Intelligent Guess (xml, json, script, or
html))Type: String The type of data that you're expecting back from
the server. If none is specified, jQuery will try to infer it based
on the MIME type of the response (an XML MIME type will yield XML, in
1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
Hope this helps.
You should specify dataType to be json in your $.ajax call. dataType is the MIME you are expecting to receive from the server. contentType is what the server is expecting from you.
I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});
I'm sending GET request (which returns JSON).
The code looks like:
$.ajax({
url: "http://www.new.marketprice.ru/retrieveRegions.html",
dataType: "jsonp",
data: {
searchStr: request.term
},
error: function() {
console.log('epic fail');
},
success: function( data ) {
console.log(data);
}
});
It returns (into console);
Resource interpreted as Other but transferred with MIME type undefined.
epic fail
But in Network tab I see GET request with returned data:
[
{ "region":"Московская область","countryId":1,
"cityId":23,"regionId":12345,"city":"Москва","country":"Россия"},
{"region":"Ленинградская область","countryId":1,"cityId":453,
"regionId":54321,"city":"Санкт Петербург","country":"Россия"}
]
Why does error callback is called?
UPD
Okay, I set json and now no warning but error:
XMLHttpRequest cannot load http://www.new.marketprice.ru/retrieveRegions.html?searchStr=test. Origin http://new.marketprice.ru is not allowed by Access-Control-Allow-Origin
It's so strange because running script is located at same domain :(
It is only a json response not JSONP. Generally for JSONP the request will have callback method and response will be wrapped in that function name
Your headers don't specify the correct mime-type (application/json-p) and jQuery(?) is confused because it's not sure if it should process it as json or not.
See if you can get your server to respond with the correct type. The appropriate header is called Content-Type.
EDIT: whoops, and the OP is right, its not even JSON-P. Try changing what jquery is expecing to just 'json' first.
i was also in problem like this just try by using one more argument callback=? or json=jsonp