rails passes json to javascript file, But javascript shows error - javascript

So i've got a rails call, It works lovely and passes this into postman (shortened because its huge)
SEEvent({"event_id":"ID","date":"Sat 20 Aug 2016, 10:00","suppress_best_available":"","sorted_ticket_types":["000000000001"],"is_resale_eligible":0,"ada_tickets_enabled":0,"suppress_any_price":"","expand_resale_module_ntf":1,"expand_resale_module":"","bba_deep_links_offer_code":
For some reason when i try and call it in my javascript file (which looks like this):
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '/event/'+ event,
success: function(json) {
debugger;
The error function is shown instead of the success. In the debugger, i have response code 4 and in the response text is all the json i need.
Any help would be amazing
I've tried changing the dataType to jsonp which also didnt work.
Sam

The error is happening possibly because this bit - SEEvent( is not valid json. The server needs to send valid json only which can be parsed straight away.

Related

Content-Type Ajax json missing

I wrote some php code that outputs some valid json, and sets the content-type header to application/json in my dev setup. However when I deploy this script to a embedded webserver it works fine except it's not capable of sending the content-type. It's not possible to run a other webserver.
Now I have the following code for Dynatable. Even though my dev and my embedded webserver, serve exactly the same file, and the only difference is the content-type. It works for my dev setup, however it doesn't work for my embedded setup.
I use the following code to load the json file to dynatable.
document.ready(
$.ajax({
url: 'phpApi.php',
success: function(data){
$('#myTable').dynatable({
dataset: {
records: data
}
});
}
}));
So can someone explain me why the content-type is so important for ajax? How can I tell my code manually its json?
Without the content-type the returned data is assumed to be plain text. There is nothing in your code to tell it otherwise.
One way to get json would be to specify the return type in the jquery code. Just add dataType: 'json' into the ajax configuration.
Or you could use eval() to transform the returned text to json.
document.ready(
$.ajax({
url: 'phpApi.php',
success: function(data){
$('#myTable').dynatable({
dataset: {
records: eval(data)
}
});
}
}));
Using JSON.stringify(eval(data)) might give you better results by making sure its json.
As pointed out below, JSON.parse(data) would probably be safer. (Eval is evil after all.)
So can someone explain me why the content-type is so important for ajax?
It's important so the client can identify what type of content the server returned, content-type: application/json tells jQUery to parse the data as an object. If no content type is returned, the client will assume the returned data is just plain text.
How can I tell my code manually its json?
Add dataType: "json" parameter to $.ajax()
document.ready(
$.ajax({
url: 'phpApi.php',
dataType: "json",
success: function(data){
$('#myTable').dynatable({
dataset: {
records: data
}
});
}
}));

AJAX failing silently

I am having a problem with one of my AJAX requests. All of this was working earlier, then I moved some files around in folders, and it must have broken something, but I have been unable to figure out what may be wrong with my pathing.
What is happening
AJAX request seems to be being ignored, nothing goes to console or the network tab, responseText is "", and I put a break point in the first line of the PHP which is never hit. It goes straight from $.ajax to the first line in my error callback. Additionally, when this PHP code is called by going straight to the page, or cron, it works fine.
I have a very similar call later to another file in the same folder that is working just fine.
What I have tried
As mentioned before, I have looked at responseText, console output, network tab, and breakpoints in my PHP (which are never reached), and I have looked around Google and stackoverflow. If I intentionally change the name to a non-existing file, I promptly get an error in the console.
Code below
$.ajax({
type: "POST",
url: "PHP/myFile.php",
data: '',
success: function () {
//Success code
},
error: function (xhr) {
var response = xhr.responseText; // response is ""
//Error code
}
});
Any ideas?
Here is the code, later in the file, which (successfully) grabs code from a file in the same folder.
$.ajax({
type: "GET",
cache: false,
url: "PHP/myOtherFile.php",
dataType: 'json',
success: function (data) {
// Success code
},
error: function () {
// Error Code
}
});
Pretty basic AJAX calls, not sure what is going on :/
Error callback is called on http errors, but also if JSON parsing on
the response fails
From: Jquery ajax error callback
From your working file, the code dataType: 'json' im blindly assuming your doing some kind of json parsing.
Try just making the "myFile.php" a simple echo 'x'; script, and check the response text. If your get something, then its because your script contains JSON parsing code, but your not passing any data to the script anyways.
Hence, the error callback would be called because the script is trying to JSON parse nothing (i.e. data: '')
I cant suggest anything else, from reading your questions description, hopefully someone else figures it out. goodluck

getting json string from web service

I have got a web service which gets list of users from an external system and returns as json. and I call that webservice via jquery ajax.; I have placed ajax code below
$.ajax({
type: "GET",
url: webMethod,
data:"",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(msg) {
alert(msg.d);
},
error: function(e) {
alert(e);
}
});
Even though, the output is in correct format, the output I get from jquery.ajax seems to be wrong. it returns big chunk of the data correctly, then adds "; (" and continues to show the output.
Basically, the output is ("around %75 of data");(rest of the data) which makes my json invalid. I am not sure whether it is related to the maxJasonLenght or not but I also set it to the maximum. there seems to be a limitation on how much data you can get from web service as if I add more data to that json, the break down point changes.
Sample Output
[{"UserName":"a.b","FullName":"a b"},{ Many other users},{"UserName":"c.d","FullName":"c d"},{"UserName":"e.f",);jsonp1364397526212("FullName":"e f"}, {"UserName":"g.h","FullName":"g f"},{other users}}
do you have any idea why I am having this issue?
Thanks
Do you set the crossDomain option to TRUE? If I'm not wrong, if you set the crossDomain option to TRUE, the response would be JSON-P.
Look at this post so you can figure out how to handle the response:
What is JSONP all about?
I hope it would help!

POSTing JSON data to Server URL

I am facing problem when I am posting a JSON data to the server using Ajax call in jQuery the function does not enter success mode. When I post using the POSTER Plugin of Firefox it gets posted successfully. Sharing the code snippet and screenshot of the same:
function showSubscribeContent()
{
alert("*1*------- SUB CLICKED");
var myJSONData = '{"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}}';
alert("*2*------- POSTING--------->"+myJSONData);
$('#subscribePage').html('<h1>POSTING...</h1>');
$.ajax({
type: 'POST',
url: 'https://tt.s2.acc.com/tt/subscribe-service/uid=sagar_mate',
data: myJSONData,
dataType: 'application/xml',
success: function(data) {
alert("*3*------- POSTED SUCCESSFULLY TO THE SERVER");
$('#subscribePage').html('<h1>POSTED</h1>');
} // Success Function
}); // Ajax Call
}
I am getting alert number 1 and 2 but not 3.
Also when I post using POSTER plugin of Firefox, it gets posted easily.
The Response is success.
I am unable to post the same data using AJAX call.
Thanks,
Ankit
Unless and until the URL in your AJAX call is of the same Domain, I don't think it will get posted successfully. POSTER plugin of Firefox doesn't put any such restriction on the domain, but browser will put this restriction on the application.
Try checking in the error: function(){alert(4);}
to see if it reaches the error handler atleast
Please clearify what you want, when using POSTER Plugin of Firefox you have specified datatype as json where as when using ajax you are using xml.
If you what to post data as JSON use JSON.stringify which accepts JSON object and convert it to string.
Try with this code
function showSubscribeContent()
{
alert("*1*------- SUB CLICKED");
var myJSONData = {"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}};
alert("*2*------- POSTING--------->"+myJSONData);
$('#subscribePage').html('<h1>POSTING...</h1>');
$.ajax({
type: 'POST',
url: 'https://tt.s2.acc.com/tt/subscribe-service/uid=sagar_mate',
data: myJSONData,
dataType: 'application/json',
success: function(data) {
alert("*3*------- POSTED SUCCESSFULLY TO THE SERVER");
$('#subscribePage').html('<h1>POSTED</h1>');
} // Success Function
}); // Ajax Call
}
Here I have changed the following lines
Converted myJSONData to a JSON object from string
var myJSONData = {"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}};
Note: try with the string(the way you were doing) if this is not working for you
Changed datatyle to JSON
dataType: 'application/json',
Adding a header in beforeSend Function worked fine for me. Security reasons of CORS.

Can not get json response using $.getJSON

I am currently developing a Ruby on rails 3 application.
My server controller function render a json object as response:
class DaysController < BaseController
...
def the_days
...
render :json => days
end
end
In my javascript,I use the following code to get json response from server( that's from the_day function in controller)
$.getJSON(
url,
{emp_id: emp_id},
function(data) {
var result = data.response;
alert(result)
alert(data)
},
"json"
);
I use firefox browswer and checked with Firebug, in Firebug Net->XHR, I see the Get request is successful, and the response "days" is there. That's both request and response are successful.
But I did not see the two alert window defined in the above $.getJSON function, why? Why I can not get the response "days" in $.getJSON function??
-----------------Edited------------------
I edited my code to this one:
$.ajax({
url: myURL,
type: 'GET',
data: {
emp_id: emp_id
},
dataType: "json",
success: function(data) {
alert("hi");
alert(data)
}
});
When I run this code, the browser is stuck at success: function(data)
If data is coming back null, but the response was otherwise successful, I'd say that you're sending the request in a manner that violates the Same Origin Policy.
The request needs to be sent to the same host/port/protocol that served the original page.
If this is only an issue in your development environment, you can test in Chrome by launching it from a Terminal application with --disable-web-security.
EDIT: Try changing the parameter name from data to something else, like dat or whatever.
Then try an alert:
alert( dat );
I've heard of some browsers having trouble with the data parameter when you utilize the data property of an AJAX call.
I'm guessing that the problem is that data does not have a response property. Try alerting just the data variable. It should be the days object itself.
I wish I could just leave a comment but I guess I don't have access to that yet.
Anyway, I'd start with something even more basic. Add some text alerts just to make sure you're actually making it to where you think you are. ie...
$.getJSON(
url,
{emp_id: emp_id},
function(data) {
alert('hi') // add this
var result = data.response;
alert('bye') // add maybe even this
alert(result)
alert(data)
},
"json"
);
Sometimes when I'm debugging I find that even my most basic assumptions are wrong.
Edit: here's some sample code from working code I recently implemented
$.ajax({
url: 'users/check_username',
type: 'GET',
data: {
username: username
},
dataType: "json",
success: function(user_exists) {
alert(user_exists) // CHANGE THIS PART
}
});
It sounds like you are not sending the correct header in your ruby application. Firebug should report the response Content Type as application/json because that is what jquery is expecting it to be.
You could try changing the datatype in your ajax call to html to see if your alerts work with that, but that doesn't really help with the json parsing.
ALL, finally, I figured out the root cause. The reason is simply because of "Invalid json data" returned in server. That's in rails controller function 'def the_days':
render :json => days
should be modified to
render :json => days.to_json
Then, everything works smoothly:) Thank you all anyhow!

Categories

Resources