Alert is coming before response - ajax

I have this ajax function which validates the user provided key. but the alert comes before the ajax response and due to which if the user provide a wrong key even can get access
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
var key = $('#downloadkey').val();
var dataString = {KEY:key};
$.ajax({
url: "/mediabox/home/validate_key",
type: 'POST',
data: dataString,
success: function(msg) {
if(msg=="true")
{
alert("do something");
}
else
{
alert("Your download key is either wrong or you didn't provide it.");
return false;
}
}
});
});
});

What makes you believe the alert is coming before the response? The success handler is only invoked after the response has been successfully received client-side.
To confirm, you can edit your success handler to log the response:
success: function(msg) {
console.log(msg);
if(msg=="true")
{
alert("do something");
}
else
{
alert("Your download key is either wrong or you didn't provide it.");
return false;
}
}
Also, if you're using the return false to deny access to the user by blocking the HTML action that, won't work due to the asynchronous nature of AJAX.

The success function is called when the request completes.
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.
The code within the success handler will only execute once the AJAX request is completed. If you are getting an alert before hand then that indicates that the request completed properly.

Related

How to use grails withForm through ajax call

I am using grails 2.5.2 version. I have a form submit event by ajax call where sometimes form is submitted multiple times. I have goggled for it and see about grails withForm topic. I tried to implement it but it stops the request for the first time and show invalid token message. How can I use useToken for withForm or other way to stop multiple time form submit via ajax call in grails.
My code attempts are below.
My ajax call:
jQuery.ajax({
type: 'POST',
dataType:'JSON',
data: $("#createFormModal").serialize(),
url: "${g.createLink(controller: 'studentCollection', action: 'save')}",
success: function (data) {
if(data.isError==true){
showAlertModal(data.message);
}else {
$('#createModal').modal('hide');
$('#list-table').DataTable().ajax.reload();
showSuccessMsg(data.message);
$("#createFormModal").find("input[type=text], textarea").val("");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
My controller method:
def save() {
LinkedHashMap result = new LinkedHashMap()
String outPut
withForm {
result = studentCollectionService.saveCollection(params)
}.invalidToken {
println("### invalidate Token")
result.put(CommonUtils.IS_ERROR, Boolean.TRUE)
result.put(CommonUtils.MESSAGE, "Please press the button once")
}
outPut = result as JSON
render outPut
return
}

AJAX response undefined.

I am currently creating an AJAX call which queries a controller and returns the appropriate reponse. The only issue is is that the response is coming back as undefined doe to the async nature of the AJAX cal. I am unsure as to how I tell the function to wait for the response. Here is my code:
View:
jQuery(document).on("click", "#payment .membership", function(e) {
e.preventDefault();
var price = SignUpObject.membershipClick(jQuery(this).attr("data-membership-id"));
alert(price);
});
Javascript Library Function (which is within an object):
var SignUpObject = {
membershipClick : function(membershipDetailsId) {
jQuery.ajax({
type : 'POST',
dataType : 'json',
url : 'api/membership-choice',
data : 'membershipid=' + membershipDetailsId
}).done(function(response) {
return response
});
}
}
The PHP that the AJAX call is calling returns the correct response back so I don't need to include them here. Can anyone tell me how to make the AJAX call wait for a response?
Thanks
You've got two problems:
1) You're attempting to call the response synchronously, before the (asynchronous) request has completed.
2) membershipClick does not return the request object, so you've got no means of hooking a completion callback onto it.
To fix:
1) Change the line
jQuery.ajax({...
to
return jQuery.ajax({
2) Change the line
alert(price);
to
price.done(function(response) { alert(response); });
However, the variable price would be better named something like price_request, since it stores a reference to the request, not the actual price (which is the response.)
Change
}).done(function(response) {
return response
});
For:
}), success: function(response) {
return response
};

Putting a JSON response into a hidden field and retrieving it into a function

I'm retrieving the number of rows contained by a table in my database with the following function using JSON.
function rowCount()
{
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
datatype:"json",
type: "GET",
url: "/wagafashion/ajax/CmsRowCount.htm",
success: function(response)
{
$("#rows").val(response);
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
In the success handler, the response is arriving as expected. There is no problem on the server side.
The response is just mapped with the long type of Java which represents the number of rows in a database table.
I'm putting this response in a hidden field whose id is rows using $("#rows").val(response); in the success handler.
The above function is invoked when the form is submitted using the following jQuery function.
$(function() {
$('#dataForm').submit(function() {
rowCount(); //Invokes the above function that makes a JSON request.
var rows=$("#rows").val();
alert("rows = "+rows);
return false;
});
});
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time. It alerts the actual value only when I press the submit button once again (without a page refresh).
Also tried to replace the preceding function with the following.
$(function() {
$('#dataForm').submit(function() {
rowCount(); //Invokes the first function that makes a JSON request.
var form = $(this),
url = form.attr('action'),
rows = form.find('input[name="rows"]').val();
alert("rows = "+rows);
return false;
});
});
But it didn't work either. Why does this happen? What is the way of retrieving the correct value of that hidden field into the preceding jQuery function?
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time.
Ajax calls are asynchonrous. When you call rowCount, you start the call, but then rowCount returns and your code continues. The call doesn't complete until later (which is why ajax accepts a callback).
If you trigger the next step in what you're doing from the callback, you'll have the value. You typically do this by having rowCount accept a callback of its own, like this:
function rowCount(callback) // <==== Accept the callback
{
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
datatype:"json",
type: "GET",
url: "/wagafashion/ajax/CmsRowCount.htm",
success: function(response)
{
$("#rows").val(response);
callback(); // <==== Call the callback
},
error: function(e)
{
alert('Error: ' + e);
callback(); // <==== Probably want to give it a value telling it things failed
}
});
}
Then using it:
$(function() {
$('#dataForm').submit(function() {
var form = $(this); // <== Grab this outside the callback
rowCount(function() {
var url = form.attr('action'),
rows = form.find('input[name="rows"]').val();
alert("rows = "+rows);
});
return false;
});
});
If you want to decide whether to allow the form to be submitted on the basis of the callback, you'll have to always cancel the submission, and then trigger submitting it programmatically from the callback if you want to allow it.

Request facebook permissions/login after ajax form validation (in ajax response)

It is working right now , but I have some feedback of user saying that the facebook popup is blocked by the browser
So what I am doing right now: I have a form that is being validated via ajax (making a call to a php page) , then if the response is successful, it ask for the user login/permissions. I assume that the popup is sometime blocked because the browser consider the ajax response not as an user action.
So my code looks like this :
$("#submit").click(function (event) {
event.preventDefault();
$.ajax({
url: url,
type: type,
data: form_data,
success: function(result){
if(result==""){
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me/permissions', function (response) { ... });
} else if (response.status === 'not_authorized') {
FB.login(function (response) { ... });
}
}
}
}
});
Any idea other than putting the facebook calls before the form validation?
You can make ajax request as synchronous call. I don't like it though
btw, what kind of validation you are doing?

JQuery not return any status like Success, Failed, Completed

Experts,
The following function are successfully send data to the Controller.cs (server)
var ajaxResponse = $.ajax({
type: "post",
url: href,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (msg) {
alert("Success");
}
})
but i am not able to get updated status from the following method
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveData(TabMasterViewModel postData)
{
string message = "";
try
{
TabMasterViewModel update = new TabMasterViewModel();
update = _tabmasterService.GetSingle(r => r.colID == postData.colID);
UpdateModel(update);
_tabmasterService.Update(update);
message = "Success";
}
catch (Exception e)
{
message = e.Message;
}
return Content(message);
}
I would like to display message when failed or success. this following line never execute
success: function (msg) {
alert("Success");
}
but my server side code is executed without any error.
Please provide your valuable suggestions,
Thanks,
Imdadhusen
Instead of returning ActionResult you should be returning JsonResult
For example
public JsonResult SaveData() {
return Json(new {success=true, msg="Saved ok"});
}
then your JS
success: function (msg) {
if(msg.success)
alert("Success");
}
You are returning Content result where as in JQuery you have mentioned dataType: 'json'. I would suggest you to either return JSON result from your controller or remove the dataType from jquery call.
I am not sure about this, please give it a try.
Hit a breakpoint in Firebug on the send line of ajax script.
Hit a breakpoint in Firebug on the success method callback.
Hit a breakpoint in Visual Studio on the first line of action method.
Follow the steps to reproduce the scenario, and inspect the objects in Firebug before sending the request, continue and hit F8 to send the request, check the Net tab page in firebug and see if any request was sent or not.
If it was sent, inspect the posted request.
if until now everything is ok continue the process in the server side on VS and check if everything is right.
then check the response on the Firebug and see if nothing goes wrong.
The obvious thing first: are you sure your url is valid? (I guess it is, since you state that the data is sent successfully).
Have you tried monitoring the ajax request to see what http status you recieve?
Anyways, .ajax also has a error callback you can use in case of the request failing all together.
An apropos: where does the return from you function go?
You have to send the reply to the output buffer for it to reach the client. Simply returning will send a null response to the client (but it shouldn't matter in this case since the .ajax success callback should trigger on request readyState 4 + status 200).

Resources