React AJAX post request does not go to success/error method - ajax

I have a React Component which calls an AJAX POST request.
The POST request creates an entry in the database as expected. (status 201 returned) However the success/error methods of the same are not called.
$.ajax({
url: '/api/put/comment/',
dataType: 'json',
type: 'POST',
data: comment,
beforeSend: function(xhr) {
console.log('before send');
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
},
success: function(data) {
console.log('success');
this.loadData();
},
error: function(xhr, status, err) {
console.log('error');
this.setState({data:comments});
console.error(this.props.url, status, err.toString());
}
});
The request is called through a button click. Also the browser hangs once the request is made, and the solution is to open a new tab.
Also i do not see the POST request on the Network tab of Chrome, but see it on the backend.
Any hints?

Try using ES6 arrow functions or bind your functions with this
$.ajax({
url: '/api/put/comment/',
dataType: 'json',
type: 'POST',
data: comment,
beforeSend:(xhr) => {
console.log('before send');
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
},
success:(data) => {
console.log('success');
this.loadData();
},
error:(xhr, status, err) => {
console.log('error');
this.setState({data:comments});
console.error(this.props.url, status, err.toString());
}
});

Related

Get response from pending webservice with ajax

I have a web service which is executed with pending status in the browser , how can i get it's response because it did not go into succes function nor the error one.
Here is my code :
$.ajax({
type: "get",
url: "https://domain_name/listenrealtime",
data: {username: '', password:"" },
headers: {},
success: function (data) {
console.log("success test");
console.log(data);
},
error: function(data){
console.log("error test");
}
})
here is a capture from the browser:
enter image description here

Go to new view on AJAX success using ActionResult

I have an AJAX call that posts data to the server to save to the DB. When this is complete, I want to call another ActionResult in the success callback to switch the user to a brand new view. This needs no data passed to it, I just need the success in the Ajax to call this method. Is this possible? I played with some of the URL helpers but I can seem to make this work, it just does nothing.
$.ajax({
url: 'Mapping/',
type: 'POST',
data: JSON.stringify({
data
}),
contentType: 'application/json; charset=utf-8',
success: function(result) {
if (result.success === true) {
alert('Yes');
} else {
alert('No');
}
},
failure: function() {
alert('No');
}
So this would be in the first part of the success callback where it is currently set at aler('Yes').
Do something like this:
$.ajax({
url: 'Mapping/',
type: 'POST',
data: JSON.stringify({
data
}),
contentType: 'application/json; charset=utf-8',
success: function(result) {
if (result.success === 'true') {
window.location.href = 'Success/';
} else {
//handle the failure from the response
}
},
failure: function() {
//handle the failure of the request itself
}

jQuery Ajax request error function issue

I'm making an Ajax request that works perfectly fine. The issue I'm having is that I attached the "error" method onto the call and when I modify the URL to try to make it throw an error....I get no error. Here is my code:
function instagramAjax () {
$.ajax ({
url: "url that works",
dataType: "jsonp",
success: function(returnedData) {
//my success code that works
},//end success
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error " + errorThrown);
}
});//end ajax request
}//end instagramAjax function
What is the url that you'd set?
This handler is not called for cross-domain script and cross-domain JSONP requests.
window.MyCallback = function (data) {
console.log(data);
};
function instagramAjax () {
$.ajax ({
url: "url that works",
dataType: "jsonp",
crossDomain: true,
jsonpCallback: 'MyCallback',
success: function(returnedData) {
//my success code that works
},//end success
error: function (xhr, status, err) {
console.log(status, err);
}
});//end ajax request
}//end instagramAjax function
or you can do it:
function instagramAjax () {
$.ajax ({
url: "url that works",
dataType: "jsonp",
crossDomain: true,
jsonp: 'MyCallback',
success: function(returnedData) {
//my success code that works
},//end success
error: function (xhr, status, err) {
console.log(status, err);
}
});//end ajax request
}//end instagramAjax function

How to use an ajax call's response to manipulate a dynamic page?

I am trying to submit a form with the user's inserted data and get the html back from the page called (update.asp).
How do I get the html response and how do I write it to a div on the page? The response would be "success".
If my page throws a 500 or other type of error, how can I handle that?
$('input#btnUpdate').click( function() {
$.ajax({
url: 'update.asp',
type: 'post',
dataType: 'json',
data: $('form#myForm').serialize(),
success: function(data) {
// how do i catch the response? is this the right place?
},
error: function(data) {
// how do I catch the error code here?
}
});
The response from the server in both cases would be passed to the callback as the data variable in your example. Try using console.log(data) inside of your callbacks to see the result in your developer console.
$('input#btnUpdate').click( function() {
$.ajax({
url: 'update.asp',
type: 'post',
dataType: 'json',
data: $('#myForm').serialize(),
success: function(response) {
$("#yourDIV").html(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError); //output, 500
}
});
});
More on this: ajax()

MVC2: Ajax call runs always in error function. Why? Whats wrong?

aspx site:
<script type="text/javascript">
function AjaxTest() {
var codeVal = "hello world";
if (codeVal) {
$.ajax({
type: "POST",
url: "CheckAge",
data: { code: codeVal },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("in ajax success");
},
error: function () {
alert("error");
}
});
}
}
Its double checked that the javascript function is called.
Controller:
[HttpPost]
public JsonResult CheckAge(String code)
{
return Json("abc");
}
It ended up always in the ajax - error - function.
The Controller function isnt called anyway. Why?
Why get I always an error?
What is wrong?
Check your url that you are posting to. It seems that you are missing the controller part. E.g. it should read /{controller}/{action}.
If that script is directly in the view (i.e. not in an external javascript file) you could have something like:
$.ajax({
type: "POST",
url: <%= Url.Action("CheckAge", "ControllerName") %>,
data: { code: codeVal },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("in ajax success");
},
error: function () {
alert("error");
}
});
Also, I find it advantageous to use firebug to debug ajax stuff. You can set break points in your javascript and also see all the requests and responses.
HTHs,
Charles
EDIT: Try simplifying things... e.g.
$.post('<%= Url.Action("CheckAge", "ControllerName") %>',
{ code: codeVal },
function (data) {
alert("in ajax success");
},
"json");

Resources