How to make a successful JSON call from Javascript - javascript

I am baffled by this for very long now. I want to gain this precious knowledge of making JSON call properly. Help me Humans.
So I'm making a call exactly like this:
$.ajax({
type : "POST",
url : "http://quote.mythicalQuotes.com/unicorn/service/historical/json?callback=callme&symbols=APPL",
dataType: "text",
cache : false,
data : My_Array,
error : function(request,error){alert(request+" "+error); },
success : function(data)
{
alert("Response" + data);
}//success
}).fail(function(textStatus, errorThrown) { alert("error Error");
console.log("The following error occured: "+ textStatus, errorThrown); });
But it fails and throws 'error' alert. Good Coding!
Now pasting "http://quote.mythicalQuotes.com/unicorn/service/historical/chart/lite/json?callback=callme&symbols=APPL" on my browser URL gives me nice JSON of format:
callme(
{
"SYMB" : [
{
"DESCRIPTION" : "APPL,
"BARS" : {
"CB" :[
{
"lt" : "09-01-2011::20:00:00",
"op" : "16.31",
"cl" : "15.22",
"hi" : "16.45",
"lo" : "14.72",
"v" : "17768019"
},
{
"lt" : "09-02-2011::20:00:00",
"op" : "15.22",
"cl" : "14.22",
"hi" : "19.45",
"lo" : "10.72",
"v" : "17768000"
}
]
}
]
})
So what atrocity am I doing here which is provoking my anger toward this particular Javascript semantics/syntactics?
Couple of reasons I thought which might cause this.
1. Same origin policy.
2. Wrong JSON format being return.
3. Stupidity of my code.
Please help.

This is a JSONP-type response. Add dataType: jsonp to the JQuery AJAX request. Since you're also specifying the callback function explicitly, add jsonpCallback: callme also. See the JQuery docs for more info (scroll down to the "dataType" section).
$.ajax({
dataType: "jsonp",
jsonpCallback: "callme",
// ...
success: function(data) {
alert(data); // should show the JSON: { "SYMB" : ... }
}
});
You mentioned the cross-domain policy; the JSONP spec is a workaround for this policy blocking cross-domain requests. The idea is that, rather than returning data, the server returns a Javascript snippet containing data. The client then executes the returned function to retrieve the data. The JQuery ajax method has built-in functionality to handle all this "behind the scenes".

Related

Ajax call is throwing an Invalid Character error

I am working on a Java application using Struts 1.2. I am facing a blocking error when I make an AJAX call to a Struts action.
The struts action, getInfos.html, is called successfully but after that when I make the AJAX call I get the following error in the console:
Invalid Character/parsing error
The data variable is a correct JSON format. Why would it trigger this error?
I've gone through all the similar questions online but I don't know why it's triggering an invalid character error.
$.ajax({
type: "POST",
url: "getInfos.html",
dataType: "json",
async: false,
cache: false,
data: {
Code: "code1",
type: "type",
mand: "mand",
signature: "signature"
},
success: function(data) {
console.log('succes');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
In the execute method that is handling the ajax request, i am calling the attributes using the request
final String code = (String) request.getAttribute("code");
final String signature = (String) request.getAttribute("signature");
final String type= (String) request.getAttribute("type");
/*
Making a call to a webservice using the attributes bellow,
using **response** Object
*/
if (reponse != null &&
(CodeReponseHttp.OK.equals(reponse.getCodeReponse()))) {
jsonObj.put(SUCCESS_CALL, true);
} else {
jsonObj.put(SUCCESS_CALL, false);
}
return new JsonResult(jsonObj);
But they are set to null; which means that the ajax data is not passed into the request, when I debug the execute method and I explicitly set values to these attributes everything works fine.
new JsonResult(jsonObj) is a generic class with a constructor that accepts a JSONObject
Like Rory McCrossan Comment it could be the response you got is not a json and your code expect a json response
When i comment dataType param it work fine
$.ajax({
type : "POST",
url : "getInfos.html",
//dataType : "json",
async: false,
cache: false,
data: JSON.stringify({
Code : "code1",
type : "type",
mand : "mand",
signature : "signature"}),
success : function(data){
console.log('succes');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
The problem had been solved, after debugging, the response type was not a JSON since there is a redirection to an error page if an exception is thrown, the exception was thrown because the data attributes were null, and it turned out that they are parametres not attributes, so getting the parameters solved the problem.
request.getParameter("code");
thank you all for your collaboration.

Making AJAX call, getting "Uncaught Reference Error"

Problem
I'm trying to make an AJAX call to an API for river data, but I'm having trouble getting the JSON object to appear in my console. Instead, I get Uncaught ReferenceError: jquery21309662145180627704_1432235037636 is not defined
Update #1 - Added in missing AJAX call code
AJAX Call
$.ajax({
url: 'http://opengov.brandon.ca/OpenDataService/default.aspx?format=jsonp&dataset=riverlevel&columns=Date',
type: 'GET',
dataType: 'jsonp',
success: function(result){
console.log(result);
}
});
API documentation: http://opengov.brandon.ca/api.aspx
Query String:
?format=jsonp&dataset=riverlevel&columns=Date
Going to the url for the AJAX call, I see this:
jsonpcallback([
{
"Date" : "19/05/2015 12:26:05 PM",
"River Level (ft)" : "1170.16000",
"River Level (m)" : "356.66477"
},
{
"Date" : "15/05/2015 9:01:20 AM",
"River Level (ft)" : "1170.51000",
"River Level (m)" : "356.77145"
},
{
"Date" : "14/05/2015 9:08:09 AM",
"River Level (ft)" : "1170.84000",
"River Level (m)" : "356.87203"
},
The API you are calling isn't implementing JSONP properly.
The callback name is case sensitive, but the API is converting it to all lower case in the response. This is a problem because the name that jQuery will generate for you starts with jQuery (with a capital Q).
In order to hack around this, you need to generate your own callback name (instead of letting jQuery do it for you) and ensure that it doesn't include any capital letters.
function callbackName() {
return "jquery_callback" + Date.now();
}
$.ajax({
url: 'http://opengov.brandon.ca/OpenDataService/default.aspx?format=jsonp&dataset=riverlevel&columns=Date&callback=?',
type: 'GET',
dataType: 'jsonp',
success: function(result) {
console.log(result);
},
jsonpCallback: callbackName
});

ajax post return the html

I have this ajax function (refer below)
$.ajax({
url: "processor.php",
type:"POST",
data: { 'id' : "itemid, 'itemname' : itemname, 'itemdesc' : itemdesc" } ,
success:function(e){
if(($.trim(e) == "success")){
alert("success");
}else{
alert(e);
}
},error:function(){
alert("critical error");
}
});
assume that I already have the linked script of jquery and the content of those variables that has been declared on the data argument inside ajax function. Now I have a processor.php (refer below)
//this is the processor php
echo "success";
so base from above references, the ajax function submit a post request to processor.php and then the processor.php will respond "success" string as declared with the "echo success" but what happen is it doesn't get the success response instead the whole html tags on the current page is pop up (alert), why?? any ideas, clues, recommendation, suggestion would be greatly appreciated. Thank you.
PS: i know the response is not success but why it popup (alert) the whole html tags in the current page?
Try this i think your are passing parameter is wrong way.i just create an example change this code as per your requirement.
$.ajax({
url: "script.php",
type:"POST",
data: { id : itemid, itemname : itemname, itemdesc : itemdesc },
success: function(data, status, settings)
{
alert(The request URL and DATA);
}
,
error: function(ajaxrequest, ajaxOptions, thrownError)
{
alert("error");
}
});
there is syntax error in posted data and you probably have a redirect to new page instead of processor.php.
EDIT
Also make sure that processor.php returns only the word "success" and there is no more html tags in the source of page.
wrong syntax:
data: { 'id' : "itemid, 'itemname' : itemname, 'itemdesc' : itemdesc" }
suggested change:
data: { id : itemid, itemname : itemname, itemdesc : itemdesc }
I've been experienced that before, check your folder and file structure and if you're running server side script (such as php) or communicating with database, check your virtual host configuration.

Readin JSon File through ajax

This is my Ajax Request:
$.ajax({
type: 'POST',
url: "http://xx.json",
//data: '{id:id}',
//data: '{providername:providername}',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'loadData'
});
ok my request itself if failing coz i need to provide data in data variable above in request not sure how should I send my data to JSON to access the contents.following is json
{
"loadData" : {
"Facebook": [
{
"email" : "karthim1982#yahoo.com",
"first_name" : "Karthick"
},
{
"email" : "mallika132-iit#yahoo.co.in", "first_name" : "Mallika"
}
],
"Google" : [
{
"email" : "jameson42#gmail.com","first_name" : "Jameson"
},
{
"email" : "hariikriishnan#gmail.com","first_name" : "hari"
}
]
}
}
Please do check if anything wrong with JSON.
How can I access the Facebook 1st and 2nd Email or Google's first Email or First)name attribute
If you are asking for jsonp using jQuery, you will get a parameter called callback in the GET request, something like:
http://your.url/out.json?callback=jQuery123456789
What you need to do on the server-side is wrap the ouput in that callback, so instead of:
{"a": 1, "b": 2}
You need to provide your response like so:
jQuery123456789('{"a": 1, "b": 2}')
In your case, it looks like you're renaming the callback to loaddata. Keep in mind that jQuery will build this function for you, you don't need to define it. What you do need to define is the success callback that the data will be passed to.
For JSONP, jQuery loads the response not as an XMLHTTPRequest but as a <script> tag and secretly sets up that callback on the page. This is banking on you having control over the remote service.

Loathing IE and it's refusal to respond to JQuery Post

Ladies / Gents:
Doing a $.post which works fine in Chrome & FireFox. IE - not so much...the success callback (addTicketAndRender()) never gets hit:
http://jsfiddle.net/AeQxJ/1/
I've read something about needing to do "cache-busting" against IE with my POST, but I'm relatively new to this stuff so don't know if that's the appropriate thing to try and if so, how to do it.
Source:
function addTicketAndRender(incomingTicket) {
console.log("Add and Render");
alert(incomingTicket);
}
$(document).ready(function() {
console.log('ready');
// variables to feed trusted ticket retrieval
var trustedURL = "http://tableau.russellchristopher.org/trusted",
userName = "foo",
serverURL = "http://tableau.russellchristopher.org/";
$.post(trustedURL, {
username: userName,
server: serverURL,
client_ip: "",
target_site: "",
cache: "false"
}, function(response) {
addTicketAndRender(response);
});
});​
Little help, please?
Update1: Switched this out to an ajax post: No difference. Still good on Chrome and Firefox, still dead in IE:
$.ajax( {
url : trustedURL,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false
} ).done( addTicketAndRender );
Update2: Integrated additional cache-busting technique. Same behavior - Chrome/FF works, nothing from IE - Using Fiddler, I can see the POST go out when running the code below from http://jsfiddle.net/AeQxJ/3//. In IE, that never happens. Tested outside of jsfiddle and see the same result. Next step: Rule out stupid IE browser settings on my part by testing on a box where I haven't touched browser settings.
function addTicketAndRender(incomingTicket){
alert(incomingTicket);
}
$(document).ready(function() {
// variables to feed trusted ticket retrieval
var trustedURL = "http://tableau.russellchristopher.org/trusted",
userName = "foo",
serverURL = "http://tableau.russellchristopher.org/";
var number=Math.floor(Math.random()*1);
$.ajax( {
url : trustedURL + "?" + number,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false
} ).done( addTicketAndRender );
});​
Update 4: Ruled out my copy of IE as an issue. Added error trapping code to the POST, and ONLY when running in IE, I see this thrown:
error: function(xhr, textStatus, error){
alert(xhr.statusText);
alert(textStatus);
alert(error);
//output:
// xhr.StatusText: No Transport
// testSttus: Error
// error: No Transport
Searching on "IE No Transport jquery POST" leads me here:
jQuery Call to WebService returns "No Transport" error
Post indicates adding jQuery.support.cors = true; should resolve the issue, but when I do, errors are returned:
//output:
// xhr.StatusText: Error: Access is denied
// testSttus: Error
// error: Error: Access is denied
Change
$.post( ...
cache: "false"
...
To:
$.ajax(...
cache: false,
...
Note, The first cache is a meaningless string, while the later is a Boolean false.
If the cache: false is not working for you, the old school way was to add a get parameter to the url, like a random number, so:
var number=Math.floor(Math.random()*1)
$.ajax( {
url : trustedURL + "?" + number,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false
} ).done( addTicketAndRender );
This should help you debugging as well (change from random number to sequential). If still doesnt work I remove .done and use something like complete i.e.
$.ajax( {
url : trustedURL,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false,
complete : function() {
addTicketAndRender
}
});
One last thing, if your doing this using your jsfiddle page, make sure you remove console.log() from your code, as this will cause IE to break (it doesn't understand console.log).
$.post is only a shorthand version of $.ajax() link: http://api.jquery.com/jQuery.post/
If you need more control I suggest using $.ajax() since you have a lot more option with the "native" method. Link: http://api.jquery.com/jQuery.ajax/
Besides a good coding tips concerning jQuery.ajax() is always set $.ajax({cache: false}) somewhere as a default, since IE is (surprise) the only browser with cache: true as default
IE tends to trip on console.log(''); statements. Try to wrap it into a Log() function:
function Log(text) {
try {
console.log(text);
}
catch (e) {
}
}
If that fixes your problem, you'll want to use this approach to using console.log() throughout your project.

Categories

Resources