JQuery ajax get error :unexpected token : - javascript

I have to do an ajax get to retrieve data from OData service, this is my code :
$.ajax({
url : "https://systempath/servicename",
type: "GET", //or POST?
dataType: "jsonp",
xhrFields:
{
withCredentials: true
},
beforeSend: function (request)
{
request.setRequestHeader("Authorization", "Basic");
},
success: function(){alert("ok")},
error: function(){alert("error")}
})
But i get this error :
Uncaught SyntaxError: Unexpected token :
If i consult the network, i find my response in JSON format, but the error function is executed not the success function.
This is my response:

The issue with your code is the dataType that you defined, make sure that the responses headers are corrects with your req. Test with the dataType:'text', this might works fine.

Related

Ajax error getting called instead of success

<script>
function editComment(id) {
var content = $('#Content').val();
var modelData = { 'Id': id, 'Content': content };
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("EditC", "Comment")',
data: JSON.stringify({ model: modelData }),
contentType: 'application/json',
success: function () {
alert("YES");
},
error: function () {
alert("Error");
}
});
}
</script>
Here the server is returning 200 OK, but for some reason the error function is getting called. Both type and contentType seem to be correct. Any idea how to fix this?
Edit:
After adding
error: function (xhr, textStatus, error) {
console.log(xhr.responseText);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
this is what is being logged:
parsererror
parsererror
SyntaxError: Unexpected end of JSON input
at parse (<anonymous>)
at ajaxConvert (jquery-3.4.1.js:9013:19)
at done (jquery-3.4.1.js:9483:15)
at XMLHttpRequest.<anonymous> (jquery-3.4.1.js:9785:9)
Moving to an answer for future readers...
The server is indeed returning a successful response, but an empty successful response:
return new HttpStatusCodeResult(200);
However, the client-side code is expecting valid JSON:
dataType: 'json',
As a result, after the successful response is received, internally the jQuery code attempts to parse that response as JSON and that fails, resulting in triggering the error callback.
Since there's no response body (and in most cases even when there is, as long as the server returns the correct MIME type), you don't need or want to specify a dataType in the jQuery AJAX operation. Simply remove this part:
dataType: 'json',

Ajax POST error (400 BAD REQUEST)

and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"

jquery ajax Uncaught SyntaxError: Unexpected token : while calling an api

I am trying to get a json response from the comicvine api but am getting the following error. comicvine.gamespot.com/:1 Uncaught SyntaxError: Unexpected token :
I see my json result, formatted, in the response body but am getting the console error above.
export function getSeriesFromComicVine() {
const url = "http://comicvine.gamespot.com/api/characters/?api_key=f18c6362ec6d4c0d7b6d550f36478c1cd6c04a49&filter=gender:male,name:hawkeye&format=json&callback=?";
$.ajax({
url: url,
// data: {test: "test"},
type: 'GET',
crossDomain: true,
jsonpCallback: 'callback',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: "myJsonMethod"
success: function (data) {
console.log(data);
}
});
}
You need to set format=jsonp not json
the jsonp callback parameter name needs to be json_callback according to comicvine.gamespot.com - I found this out by going to url https://comicvine.gamespot.com/api/characters/?api_key=[your api key]&filter=gender:male,name:hawkeye&format=jsonp in the browser, and it told me what was missing - very friendly API - the response had an error value
"'jsonp' format requires a 'json_callback' argument"
and no need for callback=? in the url - seeing as jquery adds the callback parameter and it isn't named callback
function getSeriesFromComicVine() {
const url = "https://comicvine.gamespot.com/api/characters/?api_key=[your api key]&filter=gender:male,name:hawkeye&format=jsonp";
$.ajax({
url: url,
type: 'GET',
dataType: 'jsonp',
jsonp: "json_callback",
success: function (data) {
console.log(data);
}
});
}

ajax post method treated as get by restclient

I got an url let’s say abc its type is post. if I try to call it as $.ajax method post it is showing method not allowed 405 error. it I sent by method get it is working fine but the business is not done how to solve the issue?
js code:
$.ajax({
type: "POST",
url: url,
data: data,
beforeSend: function (request){
request.setRequestHeader("X-CSRF-TOKEN", token)
},
success: function(res){
console.log(res)
},
error: function(){
JSON.parse(this.error.arguments[0].responseText).error.message.value
},
dataType: "json"
});
You should use 'method' instead of 'type'. Try this:
$.ajax({
method: "POST",
url: url,
data: data,
beforeSend: function (request){
request.setRequestHeader("X-CSRF-TOKEN", token)
},
success: function(res){
console.log(res)
},
error: function(){
JSON.parse(this.error.arguments[0].responseText).error.message.value
},
dataType: "json"
});
Or you can use the jQuery.post method.
405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource. 405 Method Not Allowed

JQuery web service authorization

My client has a web service API which I must connect to first with a payload of username and password to get SecurityToken, then use this SecurityToken as part of the header sent for all following API calls, so I was wondering how I can do this using JQuery $.ajax method. Any example is highly appreciated.
Here is what I've tried so far in authenticating but it is always returning error in response so I am not sure if it is correct:
$(document).ready(function(){
$.ajax
({
type: "POST",
url: "http://portal.domainname.com/auth",
dataType: 'json',
async: false,
data: '{"Login : admin#email.com", "Password : test"}',
success: function (){
alert('Success');
},
error: function(xhr, error){
console.debug(xhr); console.debug(error);
}
});
});
Problem with the above code is that it always return 200 OK status but token is never returned in response
I think you want to send data as an object, rather than a string, since string implies it's a query string:
data: JSON.stringify({
Login: "admin#email.com",
Password : "test"
}),
Also, if you are getting a 200, then it means the response was successful (and you should use the success callback), however all your logic is in the error callback instead. You probably want:
success: function(data) {
// Do something with data
},
For me the JSON that you are sending is not valid json:
data: '{"Login : admin#email.com", "Password : test"}',
it should be
data: '{"Login" : "admin#email.com", "Password" : "test"}',

Categories

Resources