Uncaught SyntaxError: Unexpected token u with Ajax post - javascript

I am stumped as to how to solve/diagnose ajax/jquery error.
This is my function:
var LogIn = {
Email: $("#Name").val(),
MobileNo: $("#txtMobileNumber").val(),
PinCode: '',
Message: '',
Success:false
};
$.ajax({
type: "POST",
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json",
url: "https://a different server domain/api/LoginRequest",
data: JSON.stringify(LogIn),
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
I get this error:

jQuery doesn't support using POST and jsonp and the reason for that is very simple: when you inject a <script> tag into the DOM (which is what jQuery does when you use jsonp), the browser will send a GET request to the remote endpoint which has been referred to in the src property of this tag.
So basically you will need to use GET instead:
type: "GET"
Also since the data is sent as query string parameters you should remove the content type:
contentType: "application/json",
and do not JSON.stringify the data.
And here's the full example:
$.ajax({
type: "GET",
crossDomain: true,
dataType: 'jsonp',
url: "https://a different server domain/api/LoginRequest",
data: LogIn,
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
Of course this will work only if the remote endpoint supports JSONP and the GET verb.
Personally I would recommend using CORS instead of JSONP as it would give you much more options. You will be able to use POST in this case. Please refer to the following material as it seems you are using ASP.NET Web API on the server and trying to make a cross domain AJAX call: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

Related

IE8: Access denied

I am trying to access and API using jquery/post but its not working in IE8. Its throwing Access denied error in IE8 only.
js code:
var url = 'http://somecomp.cartodb.com:80/api/v1/map?map_key=xxxxxxxxxxxxxxxxxxxx&stat_tag=API';
var data = //some long data of length greater than 3000
$.ajax({
crossOrigin: !0,
type: "POST",
method: "POST",
dataType: "json",
contentType: "application/json",
url: url,
data: JSON.stringify(data),
success: function(a) {
console.log('success');
},
error: function(a) {
console.log('error');
}
})
If I add ?callback=? at the end of url, it still fires the error callback but with statusText: 'success' and code: 200
here is full code: http://textuploader.com/ato0w
Change dataType to jsonp will allow you to make cross-domiain requests. This will work only with GET requests.
If you're using CORS for accessing cross-origin resource, try to add the following line:
$.ajax({
crossDomain: true, // replace "crossOrigin: !0;"
});
If this not working for you, try to add the following line above $.ajax() call.
jQuery.support.cors = true;

ERROR: bad URI when sending data as JSON with GET method to a Rails resource

Hello I'm performing a GET request on a RESTful Rails resource, like so:
function getGroups(category) {
$.ajax({
type: 'GET',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "category":category }),
success: function(data) {alert(data)},
contentType: "application/json",
dataType: 'json'
});
});
getGroups("own_groups");
The problem is that Webrick server errors out like this:
ERROR bad URI
`/groups.json?{%22access_token%22:%22569669d8df0456%22,%22category%22:%22own_groups%22}'.
It must be something related with how the JSON data is parsed, because I am having no problems with another GET request WITHOUT JSON data, and a POST request WITH JSON data...
Update: adding code for POST request (where JSON.stringify is required)
function addGroup(name, description) {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "group_name":name, "group_description":description}),
success: function(data) { alert("ok")},
contentType: "application/json",
dataType: 'json'
});
};
addGroup("nice group", "full of people");
Do not use JSON.stringify. Simply put:
data: {"access_token":"569669d8df0456", "category":category },
Moreover, you do not need to specify complete url http://localhost:3000/groups.json, it can be just simply groups.json

Facebook Graph jQuery AJAX call to post a photo on user's behalf

I'm trying to post a photo on the users behalf. I've been searching the web for the last 4 hours and I'm out of ideas.
JS:
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.0/me/photos',
data: JSON.stringify({
url: 'https://www.facebook.com/images/fb_icon_325x325.png',
access_token: token
}),
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a+'|'+b+'|'+c);
}
})
the error function outputs the following:
[object Object]|error|Bad Request
I think there must be something wrong with the ajax request itself, but I can't figure out what it is. I've reconstructed my request using the Facebook Graph API explorer and everything works fine there. Any ideas?
Need to define the correct data type in the ajax request ( jsonp ), just try this will work :
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.0/me/photos',
data: JSON.stringify({
url: 'https://www.facebook.com/images/fb_icon_325x325.png',
access_token: token
}),
dataType: "jsonp", //Just add this line ( jsonp not json ),
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a+'|'+b+'|'+c);
}
})

AJAX is not sending request

I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
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.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Categories