jQuery ajax - error runs even though it ran successfully - javascript

I have the following code as aprt of my .ajax section
success: function (data) {
alert("success");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
The first alert never runs, however the data is submitted correctly using the below:
data: JSON.stringify({ "solution": JSON.stringify(data) }), // Data is HTML
In fact, the second alert comes back with a status of 200 and everything through Google Chrome console looks fine.
Any idea? Full code:
var request = jQuery.ajax({
url: "/answers/"+content_id,
type: "POST",
data: JSON.stringify({ "solution": data }),
dataType: "json",
headers: {
Authorization: 'Basic XXX',
'X-HTTP-Method-Override': 'PATCH',
'Content-Type': 'application/json'
},
success: function (data) {
alert("success");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});

The $.ajax function expects JSON data as response. If the response is not JSON, the error callback will be called. Please have a look at what you are sending out from server.

Please test some things:
Set type: "GET" instead of post. Look at this: GET OR POST
Headers data are string (name/value), and maybe your data encoding is utf8 so set
headers: {
'Authorization': 'Basic XXX', //high recommended
'X-HTTP-Method-Override': 'PATCH',
'Content-Type': "application/json; charset=utf-8" //low
},
Test another word instead of data to avoid conflict:
success: function (response)

Related

How to convert a Raw body data request for an API to ajax request

I am currently using postman to make an API request that pushes body data. I can get this to work either using "x-www-form-urlencoded" or "raw". See examples below:
I'm trying to convert this to an ajax javascript request but unsure on how to format the body/data text. Here is my script:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
headers: {
"Content-Type": "application/json"
},
data: {
" grant_type=client_credentials
&client_id=***
&client_secret=***
&resource=https://analysis.windows.net/powerbi/api "
},
success: (data) => {
console.log(data.token)
},
error: (data) => {
console.log('rr', data)
}
});
Any help would be appreciated
There's a mismatch here as you're setting the Content-Type header to JSON, yet you're sending form-urlencoded. You need to use one or the other consistently.
If you want to explicitly use JSON, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
contentType: 'application/json', // shorter than setting the headers directly, but does the same thing
data: JSON.stringify({
grant_type: 'client_credentials',
client_id: '***',
client_secret: '***'
resource: 'https://analysis.windows.net/powerbi/api'
}),
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
If you want to use a form-urlencoded string, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
data: 'grant_type=client_credentials&client_id=***&client_secret=***&resource=https://analysis.windows.net/powerbi/api',
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
Note in the above examples that the first argument to the error handler is not the request or response data as your example seems to expect. I've amended that part to accept the correct arguments.

Alert is shown for entering username and password even though am passing basic auth

I am trying to generate order id using order's api in razorpay.
My code:-
This code is in script of head:-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
The below code is in the script of the body
var jsonData = {
"currency": "INR",
"amount": "10000",
};
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: url,
data: { json: JSON.stringify(jsonData) },
xhrFields: {
withCredentials: true
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
},
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("done");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
jsonValue = jQuery.parseJSON(xhr.responseText);
console.log(xhr.Message);
},
});
The above code continuously shows me alert box with status code as 0.
I tried to reproduce your output [alert with status 0] and I was able to do it
Then I started to search for a solution and I found this answer as a nice place to start with. Following the link I found this answer and this other very useful. Setting dataType: 'jsonp' changed the game
The snippet that eventually gave me a 200 back alert is the following:
var jsonData = {
"text1" : "textData1",
"number": 10
};
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: 'https://your.endpoint',
//crossDomain: true,
data : { json: JSON.stringify(jsonData) },
contentType: "application/javascript; charset=utf-8",
success: function (response){
alert("done");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
console.log(thrownError.Message);
},
});
Since we triggered the error despite being successful, you may want to look at this answer too
I also took a look at RazorPay APIs [I never worked on them]. With regards to creating an order I saw that amount is passed as an integer, not as a string. Then I modified the script according to this answer. And by the way I guess you will need to multiply it by 100 because the amount is expressed in "currency subunits" ["For example, for an amount of ₹295, enter 29500"]

Ajax data response by POST

Well, I send POST request to server-side to get data (xls). I use fiddler and see binary in response, but Chrome tells me there is a Network Error 0x800c0007.
Server side based on WCF. Here I take HttpResponse, copy Stream from Excel to response.OutputStream, and say response.flush(). It goes without errors.
I see response with 200 Code. But chrome does not react to data.
Probably I use wrong header or need to set up Ajax in different way.
$.ajax({
url: url,
method: 'POST',
type: 'POST',
data: JSON.stringify({ 'options': options }),
contentType: 'application/json;charset=utf-8',
accepts: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
dataType: 'json',
mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": '*',
"X-HTTP-Method": "POST",
'mimeType': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
},
error: function (data) {
console.log("error: ", data);
a.resolve(null);
},
success: function (data, status, headers, config) {
if (data != null) {
a.resolve(data);
}
}
});
return a.promise();
This is my last attempt.
Is it possible to send to server data by Post and have a response with binary?

error 500 in ajax call when call to the server, but in localhost works

I have a js when i do a ajax call to one server. When i call to this service using localhost, works. But when i call to this service using the server where i upload it, its ERROR 500. The call return a json.
$.ajax({
url: "https://www.example.com/example",
dataType: "json",
data: {
'data': xml,
'message': message,
'customer_id': customer_id,
'subscr_id': subscr_id
},
type: 'POST',
success: function (devol) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert("no ha entrado");
}
});
Try to update your code below:
var model = {
'data': xml,
'message': message,
'customer_id': customer_id,
'subscr_id': subscr_id
};
$.ajax({
url: "https://www.example.com/example",
type: 'POST',
dataType: 'json',
data: JSON.stringify(model),
//headers: { 'authorization': `Bearer ${token}` },
async: false,
processData: false,
contentType: "application/json",
error: function (err) {
},
success: function (data) {
}
});
It might be because of CORS (Cross-Origin Resource Sharing)... Usually, you cannot make calls to other domains from the browser unless the other domain you are making calls allows CORS to all sites or specific sites.
enter link description here

Jquery AJAX Post: 500 (Internal Server Error)?

I am trying post a string to web service but I am getting this error (Google Chrome Extension Project):
jquery-2.1.1.min.js:4 POST http://localhost:49242/Service.asmx/test
500 (Internal Server Error)
Here is my ajax code:
var data = {};
data.param1 = words[0];
$.ajax({
data: JSON.stringify({ 'data': data.param1 }),
dataType: 'application/json',
url: 'http://localhost:49242/Service.asmx/test',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
My service:
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public string test(string param1) {
return param1;
}
I am working on this problem about 3 days. Can you help me ?
By the way, I have a question. I am posting json variable to service with ajax(like you see), but service returning xml value. Is there a problem or [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] this code block solving problem?
Your error come from your data parameter. Stringify data object instead of { 'data': data.param1 } :
var data = {};
data.param1 = words[0];
$.ajax({
data: JSON.stringify(data),
dataType: 'application/json',
url: 'http://localhost:49242/Service.asmx/test',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
Your stringifyed data will result in {"param1":"Words"}, then your service should be able to bind the param1 parameter.
I was facing this type of error on AJAX post response. I was spending too much time behind this issue and finally I caught it.
It throws a 500 internal error because the AJAX response has a lot of content from the server so it returns a timeout of execution.
So I just added the line below and it's working fine.
Page.Server.ScriptTimeout = 300;

Categories

Resources