Ajax success issue with React and Rails - ruby-on-rails

I've got a form that I am trying to handle with React. This is the ajax method in the handleSubmit function:
$.ajax({
data: formData,
dataType: "json",
url: '/requests',
type: "POST",
success: function(data, status, xhr) {
console.log('SHOW HERE ON RESPONSE');
this.setState({
formSubmitted: true
});
}
});
When I click on submit, I can see the POST request go through and the server responds with a 200. But the success callback is never entered, I don't see the console message.
My rails controller's action is just a simple:
return render nothing: true, status: 200 if request.xhr?
The log with the server response includes:
Completed 200 OK in 11ms (Views: 2.5ms | ActiveRecord: 2.6ms)
However when I move the stuff from the success callback in the ajax request to a complete callback then I see this error in the console:
Uncaught TypeError: this.setState is not a function

You are seeing this error, because this behaves differently inside $.ajax()'s success callback, because jQuery uses it internally.
Suppose you are executing the following ajax call in response to a click function, then:
var $this = $(this);
$.ajax({
data: formData,
dataType: "json",
url: '/requests',
type: "POST",
success: function(data, status, xhr) {
console.log('SHOW HERE ON RESPONSE');
$this.setState({
formSubmitted: true
});
}
});

In the callback, this refers to the jqXHR object of the ajax call, instead of the context you expect (in this case, the component you're calling setState on).
$.ajax allows you to set the context explicitly to avoid these types of conflicts.
$.ajax({
data: formData,
dataType: "json",
url: '/requests',
type: "POST",
context: this,
success: function(data, status, xhr) {
console.log('SHOW HERE ON RESPONSE');
this.setState({
formSubmitted: true
});
}
});
Adding context: this will fix this issue.

Related

I get 401 (Unauthorized) and Invalid HTTP status code 401 for the POST/OPTIONS call. Works on POSTMAN/RESTCLIENT

I'm new to Jquery and JqueryMobile . I'm having a bit of a trouble and was hoping someone here would help me. From what I understand, before I can actually do "POST", the browser does a "preflight" OPTIONS call. The problem with me is that the OPTIONS call fails with 401. I tested the api with RESTclient and POSTMAN and it works for just "POST".
I have one more block of code which is similar and makes a call to get the authorization token(authtoken). The only difference between this block and the other block are
1) Data block.
2) BeforeSend block.
The code for making the call.
jQuery.support.cors = true;
$.ajax({
type: "POST",
url: "https://myurl/api/APIName",
beforeSend: function (request)
{
request.setRequestHeader('AuthToken', "This is where I'll insert my authtoken");
request.setRequestHeader('Content-Type', "application/json");
$.mobile.showPageLoadingMsg();
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
data: {FirstName: "Albert", LastName: "Einstein"},
dataType: 'json',
success: function (response) {
alert(response.APIStatus.ErrorCode);
},
error: function () {
alert(response.APIStatus.ErrorCode;
}
});
The code to get Authorization Token. This block does its work without any issue.
jQuery.support.cors = true;
$.ajax({
type: "POST",
url: "https://myurl/api/THEURLTOAUTHENTICAREME",
beforeSend: function () {
$.mobile.showPageLoadingMsg();
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
data: {username: "Nickolas", Password: "Te$l#"},
dataType: 'json',
success: function (response) {
if (response.AuthToken) {
alert(response.AuthToken);
}else {
alert(response.APIStatus.Message);
}
},
error: function () {
alert("Woops");
}
});
I'm not the one whose working on the api piece of the application, but I do know the person who are working on it.
The first block needs to have an "authtoken" in the header and that's the reason why I'm doing request.setRequestHeader('AuthToken', "This is where I'll insert my authtoken");. Am I doing this wrong?
Hitting the API in Postman: http://i.imgur.com/rEk3rAr.png
Console/Inspector from Chrome: http://i.imgur.com/vfSHqR4.png
Please help me!

Why getting "Invalid JSON" added to my custom error message

Invalid JSON:
Error 1 : Non-MDX format found.
Why I am getting the Invalid JSON with my custom error message.
My code is given bellow:
$('#btnCreateView').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Mdx")',
data: $('form').serialize(),
dataType: "json",
success: function (result) {
alert("View Created Successfuly");
window.location = result.link;
},
error: function (jqXhr, textStatus, errorThrown) {
$('#ErrorMessageField').html(errorThrown);
}
});
})
In your controller action you seem to be returning a partial view:
return PartialView("Fail");
but in your AJAX request you inidicated
dataType: "json",
Obviously this is inconsistent. When jQuery attempts to parse the string returned from your controller action back into javascript object it fails because you are not sending JSON, you are sending partial HTML.

Success and Error functions not firing in Ajax call

Below is an Ajax call I'm using to determine which menu options to show to users (I know it's a flawed method, just up against a time crunch for a demo). When the page loads, I can step through the controller method in Visual Studio so I know it's hitting the controller and sending back the right information.
Looking at Chrome's Network console I can also see that the browser received the right response. However, neither the console.log or the alert are firing. Nothing in the success or error methods is executed either. Does anyone see what's going wrong?
View
$(document).ready(function ($) {
//Determine which links to show in navbar
window.onload = function () {
$.ajax({
type: 'GET',
url: '#Url.Action("CheckSecurity","Home")',
dataType: 'json',
succcess: function (data) {
console.log(data);
alert(data);
if (data == "admin") { $('#adminLink').show(); }
else if (data == "IT") { $('#ITLink').show(); }
else if (data == "viewer") { $('#viewerLink').show(); }
else if (data == "modifier") { $('#modifierLink').show(); }
},
error: function (data) {
alert("error");
}
});
};
Controller
[HttpGet]
public JsonResult CheckSecurity()
{
if (Security.IsAdmin(User)) return Json("admin", JsonRequestBehavior.AllowGet);
if (Security.IsItSupport(User)) return Json("IT", JsonRequestBehavior.AllowGet);
if (Security.IsViewer(User)) return Json("viewer", JsonRequestBehavior.AllowGet);
if (Security.IsModifier(User)) return Json("modifier", JsonRequestBehavior.AllowGet);
return Json("NA", JsonRequestBehavior.AllowGet);
}
Here are a couple screen shots of the Network and regular console in Chrome. Bother are from after I've stepped through the controller method and the program has returned a value back to the browser.
Network Console
Standard Console
There is an extra c in your
succcess:
So the response is a 200 request , but because you have no mapping for success defined, it is just never logged
It is success instead of succcess
NealR
Deprecation Notice:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks
will be deprecated in jQuery 1.8. To prepare your code for their
eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always()
instead.
Check the done, fail and always callbacks below.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
}).fail(function (data) {
debugger;
}).always(function(data) {
alert("complete");
});
.ajax().always(function(a, textStatus, b){});
Replaces method .complete() which was deprecated in jQuery 1.8.
In response to successful transaction, arguments are same as .done() (ie. a = data, b = jqXHR) and for failed transactions the arguments are same as .fail() (ie. a = jqXHR, b = errorThrown).
This is an alternative construct for the complete callback function above. Refer to deferred.always() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).always(function(data) {
alert("complete");
});
.ajax().done(function(data, textStatus, jqXHR){});
Replaces method .success() which was deprecated in jQuery 1.8.
This is an alternative construct for the success callback function above. Refer to deferred.done() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
});
.ajax().fail(function(jqXHR, textStatus, errorThrown){});
Replaces method .error() which was deprecated in jQuery 1.8.
This is an alternative construct for the complete callback function above. Refer to deferred.fail() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).fail(function (data) {
debugger;
});
Check here for more details
Check here for the documentation details

How to access response of ajax request, fired by clicking on a link?

I have a link, clicking on which an ajax POST request is fired up.
I do this:
$('a#create_object').click();
This fires an ajax request. The code for this ($.ajax({...})) is written somewhere in bootstrap libs and I do not want to edit thwem.
How do I access the response of the request after ajax successes?
The direct callbacks are deprecated since jQuery 1.8.0, but you can use the .done, .fail and .always callbacks !
And you have to overwrite / access the callbacks if you want to do some stuff, you cannot access it from external I mean !
$('#link').on('click', function(e) {
$.ajax({
type: "post",
url: "your-page",
data: {},
dataType: "json"
}).done(function (response) {
alert('Success');
console.log(response); // Use it here
}).fail(function (response) {
alert('Fail');
console.log(response); // Use it here
}).always(function (response) {
// Here manage something every-time, when it's done OR failed.
});
});
$('#controlId').click(function(){ $.ajax({
type: "POST",
url: "PageUrl/Function",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d); //here you can get the response on success of function
}
});
});

Simple problem on jQuery ajax method

I am trying to simply use jQuery's ajax method and method only call error callback.
$('form').submit(function() {
$.ajax({
url: this.action,
data: $(this).serialize(),
type: 'POST',
dataType: 'html',
success: function() {
debugger
alert('alert');
},
error: function(xhr, status, error) {
//status value is "error".
}
});
});
I am requesting to ASP.NET MVC action method. Method get request as expected and return partial view without any problem. Then jquery call error callback without specify detailed error info. I want to know some details about error then i can decide what can cause it.
Edit : I have tested below code and it works without problem. I just canceled form submit event.
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
url: this.action,
data: $(this).serialize(),
type: 'POST',
dataType: 'html',
success: function() {
debugger
alert('alert');
},
error: function(xhr, status, error) {
//status value is "error".
}
});
});
Still answer is expecting right answer who can tell me reason of this error.
Could it be the reference this.action is undefined? Look at the network tab of your favorite dom inspector or just the error console of firebug. Does the POST request look as expected? (Check the URL, data sent, error code, etc)
$(this).attr('action') will certainly work, assuming this points to the form.

Resources