Error with Jquery Ajax Success Event and Receiving Response Message - javascript

I am calling jQuery Ajax function, everything works fine.. except, it is not receving any response and appending it in.
When form is submitted.. beforeSend event is called and loading image successfully runs, and also there is an alert box with message 'Deleted', but the request and response from page is not appended.... in network tab of chrome, i can see message of selected post deleted... but its not appending in page.
$(document).ready(function() {
$("#post").submit(function() {
var post = $('#post').val();
var token = $('#token').val();
var str = 'token='+ token + '&post='+ post;
$.ajax({
type: "POST",
cache: false,
url: "http://localhost/delete.php",
data: str,
beforeSend: function(){
$("#post").html('<img src="http://localhost/loader.gif" align="absmiddle"> Deleting...');
},
success: function(msg) {
alert('Deleted');
$("#post").ajaxComplete(function(event, request, settings) {
$("#post").html(msg);
});
}
});
return false;
});
});

You're attaching a new event listener to #post after the AJAX query succeeds. Basically what you're saying is, "after this query succeeds, wait for another query to succeed and then change the HTML." Since the query has already succeeded, you need to remove ajaxComplete and simply use:
success: function() {
alert('Deleted');
$("#post").html(msg);
}

Related

NO refresh the page when success ajax

I have a ajax section to submit data in laravel. I want if I submit success then don't reload the page and submit the error then reload the page. In the code below, when the error reloads the page correctly, I am having a problem in the success case, the page must not be reloaded, but the result is reloaded. I have added the line e.preventDefault () then true in the success case but wrong in the error case
$(document).ready(function() {
$('form').submit(function(e){
//e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:'{{ route('contracts.store') }}',
method: "POST",
data: form_data,
dataType: "json",
success: function(data) {
$("#mgsContract").text("Add successfully");
$("#hideForm").css("visibility", "visible");
$("#hideForm").css("height", "auto");
$("#result-contract-id").val(data.contract_obj);
},
error: function(data) {
$("#mgsContract").text("Something wrong");
}
})
});
});
Add back that e.preventDefault() to prevent the form submission, and in the error case, call location.reload(). (Or if you want to submit the form conventionally in the error case, use e.target.submit(); instead. Since that's calling submit on the DOM element [not a jQuery wrapper], it won't call your submit handler again. [This is one of the differences between programmatically calling submit on a DOM element vs. calling it on a jQuery object.])
when you use ajax, laravel automatically responds in JSON for validation errors. therefore to access the validation errors you can use this.responseJSON.errors in error section of your ajax. there is no need to reload the page to access validation errors.
however in any case if you need to reload or go to specific location you can use window.location
window.location.href = "an address"; // going to specific location
window.location.reload(); //reloading the page
an ajax example is the following, in which a loop for showing all errors inside the form is specified.
$("#form_id").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
method: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function (data) {
// code in the case of success
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
// code in the case of error
console.log(err.responseJSON);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="' + i + '"]');
el.removeClass('is-valid');
el.addClass('is-invalid');
var parent = el.parents('.form-group');
parent.append("<small class='error-message text-right text-danger d-block pr-5 ' role='alert'>" + error + "</small >");
});
}
},
});
});

Calling ajax request continually until a certain search request is found

I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"

Given a form submit, how to only submit if the server first responses back with a valid flag?

I have a form, with a text input and a submit button.
On submit, I want to hit the server first to see if the input is valid, then based on the response either show an error message or if valid, continue with the form submit.
Here is what I have:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
if (data.valid) {
return true
} else {
// Show error message
return false;
e.preventDefault();
}
}
});
});
Problem is the form is always submitting, given the use case, what's the right way to implement? Thanks
Try like this:
$('#new_user').submit(function(e) {
var $form = $(this);
// we send an AJAX request to verify something
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
// if the server said OK we trigger the form submission
// note that this will no longer call the .submit handler
// and cause infinite recursion
$form[0].submit();
} else {
// Show error message
alert('oops an error');
}
}
});
// we always cancel the submission of the form
return false;
});
Since you're already submitting via AJAX why not just submit the data then if it's valid rather than transmit the data twice?
That said, the function that makes the Ajax call needs to be the one that returns false. Then the successvfunction should end with:
$('#new_user').submit()
The fact that AJAX is asynchronous is what's throwing you off.
Please forgive any typos, I'm doing this on my cell phone.
Submitting the same post to the server twice seems quite unnecessary. I'm guessing you just want to stay on the same page if the form doesn't (or can't) be submitted successfully. If I understand your intention correctly, just do a redirect from your success handler:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
location.href = "success.htm";
},
// if not valid, return an error status code from the server
error: function () {
// display error/validation messaging
}
});
return false;
});
Another approach
EDIT: seems redundant submitting same data twice, not sure if this is what is intended. If server gets valid data on first attempt no point in resending
var isValid=false;
$('#new_user').submit(function(e) {
var $form = $(this);
/* only do ajax when isValid is false*/
if ( !isValid){
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
isValid=true;
/* submit again, will bypass ajax since flag is true*/
$form.submit();
} else {
// Show error message
alert('oops an error');
}
}
});
}
/* will return false until ajax changes this flag*/
return isValid;
});

Cant seem to set global vars correctly

I am trying to store a token into a global var. When the alert is run it says null, but if I put 2 alerts one after the other the 1st shows null but the second shows the token.
Its like the token is not being set because the 1st alert is run before the ajax request has finished.
Does anyone have any ideas on what I am doing wrong?
var csrf_token = null;
$(document).ready(function(){
get_csrf_token();
alert('token 1 '+csrf_token);
alert('token 2 '+csrf_token);
});
function get_csrf_token()
{
$.ajax({
type: "GET",
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
csrf_token = resp.csrf_token;
}
});
}
Thanks
UPDATED
Ok thanks for your help everyone but still dont see how this would work. I use get_csrf_token() like jqgrid to send the token with the request like below. So how do I pass the token to and have it working?
beforeRequest: function (){
get_csrf_token()
//alert(csrf_token);
$("#customer_grid").setPostDataItem('<?php echo $csrf_token_name; ?>', csrf_token);
}
The success callback function runs when the HTTP response arrives.
In your test, the response is arriving between the time that the first alert is displayed and the time you click the button to let the script continue.
Do whatever you need to do with the data in the callback, not as the statement after the one where you initiate the Ajax request.
Example as requested by comment:
$(document).ready(function(){
get_csrf_token();
});
function get_csrf_token()
{
$.ajax({
type: "GET",
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
alert('token 1 '+csrf_token);
alert('token 2 '+csrf_token);
}
});
}
The A in AJAX stands for 'asynchronous'. While you are busy clicking on the first alert, the AJAX request is going through and the value is filled. You will need to place all code that needs the variable csrf_token into your callback function. Alternatively, you can look into using jQuery 1.5 or above (if you aren't already). It has so-called Deferred Objects
This API allows you to work with return values that may not be immediately present (such as the return result from an asynchronous Ajax request).
You can also set the async value on your post request tofalse, like this:
$.ajax({
type: "GET",
async: false,
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
csrf_token = resp.csrf_token;
}
});
This will make the browser wait for the response before proceeding with the rest of your code. I wouldn't necessarily recommend it, but it should work.
The AJAX request is async. That means the script doesn't wait for it to finish. When the first alert fires the token is not set. But until you hit OK it has time to load and the token will be set.
Here's the order of the operations:
call get_csrf_token
make token request
show alert 1
finish request and set csrf_token
client hits OK on the first alert
show alert 2 (the token variable was set at 4.)

How do I reload the page after all ajax calls complete?

The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData function) and uses them to get more information from a thirdparty service (getInformation function). This getInformation function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
In your getInformation() call you can call location.reload() in your success callback, like this:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any further ajax calls complete, you can use the ajaxStop event, like this:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
.ajaxStop() works fine to me, page is reloaded after all ajax calls.
You can use as the following example :
$( document ).ajaxStop(function() {
window.location = window.location;
});
How it's works?
A: Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.
Hope help y'all, furthermore information, I'm sharing the link of the documentation following.
source: https://api.jquery.com/ajaxstop/
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
//document.location.reload(true);
window.location = window.location;
See more at: http://www.dotnetfunda.com/forums/show/17887/issue-in-ie-11-when-i-try-to-refresh-my-parent-page-from-the-popupwind#sthash.gZEB8QV0.dpuf

Categories

Resources