I,m try check(validate) form data by using AJAX.
First i create callback function with AJAX request(in my example it's field time)
When i found same record in database, my NodeJS server response with value false, it's means we have record and we don't need add second record with that time).
My problem is that the form is still sent, regardless of the server response.
here my code(front end)
function funABC(mdata,callback){
console.log(mdata);
$.ajax({
url:'/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data:mdata,
success: callback ,
// error:callback,
});
}
$('.addForm').on('submit', function (event) {
let form = $('.addForm');
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
// return false;
}
event.preventDefault();
checkdata = {
time_show : document.querySelector('.addForm').elements.time_show.value
}
functABC(checkdata,function(result) {
console.log(result);
if (result == 'true') {
alert(`For time: ${checkdata. time_show} there is already an event, choose a different time`);
return false;
}
})
form.addClass('was-validated');
some operations with form data, then send with ajax
$.ajax({
type: "POST",
url: "/dashboard/materials/add",
dataType: "json",
contentType: "application/json",
success: function (data) {
setTimeout(location.href = '/dashboard/materials', 10000);
},
data: JSON.stringify(formdata)
});
});
How and where did you call that post request ?
May be you would need to move post request into the callback
function funABC(mdata, callback) {
console.log(mdata);
$.ajax({
url: '/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data: mdata,
success: callback,
// error:callback,
});
}
$('.addForm').on('submit', function(event) {
let form = $('.addForm');
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
// return false;
}
event.preventDefault();
checkdata = {
time_show: document.querySelector('.addForm').elements.time_show.value
}
functABC(checkdata, function(result) {
console.log(result);
if (result == 'true') {
alert(`For time: ${checkdata. time_show} there is already an event, choose a different time`);
return false;
} else {
$.ajax({
type: "POST",
url: "/dashboard/materials/add",
dataType: "json",
contentType: "application/json",
success: function(data) {
setTimeout(location.href = '/dashboard/materials', 10000);
},
data: JSON.stringify(formdata)
});
}
})
form.addClass('was-validated');
});
Or you could async false for validation request
$.ajax({
url: '/dashboard/materials/checkshowrange',
method: 'GET',
dataType: "json",
contentType: "application/json",
data: mdata,
success: callback,
async: false,
// error:callback,
});
Related
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
}
});
}
This is my ajax GET request I want to display the given url in html.
The below is the whole snippet with my login logic.
$(document).ready(()=>{
$('#login').submit((e)=>{
$.ajax({
type: 'POST',
url:'http://localhost:3000/login/users',
data: {
email: $('#email').val(),
password: $('#password').val()
},
success: function(data, status, req){
// alert(req.getResponseHeader('x-auth'));
localStorage.setItem('t',req.getResponseHeader('x-auth'));
var token = localStorage.getItem('t');
regCall(token);
// window.location.href = '/';
},
error: function (req, status, error) {
// alert(req.getResponseHeader('x-auth'));
localStorage.setItem('t',req.getResponseHeader('x-auth'));
alert('Invalid email and password');
window.location.href = '/login';
}
});
e.preventDefault();
});
})
This is the whole code of snippet.
extract response data from SUCCESS function:
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
},
success: function(data){
//targetElement should be replaced by the ID of target element
$("#targetElement").html(data);
}
});
}
By using the success callback function you can display the response content on the HTML place
**First method:**
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
},
success: function(responseData){
$("#div or class Id").html(responseData);
}
});
}
**Second method:**
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
}
}).done(function(responseData){
$("#div or class Id").html(responseData);
});
}
**NOTE:**
Make sure you are having the jQuery script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm currently working the project using Polymer and I'd like to get the return value of API after POST using Iron-Ajax.
Here is my sample code,
var rs = $.ajax({
type: "POST",
url: apiUrl,
data: _data,
dataType: "json",
contentType: 'application/json'
});
rs.done(function (data) {
console.log(data);
alert(data);
}
});
Ajax is asynchronous by default,you need add async:false to make it synchronous
var rs = $.ajax({
type: "POST",
url: apiUrl,
data: _data,
async:false,
dataType: "json",
contentType: 'application/json'
});
var result = null;
rs.done(function (data) {
console.log(data);
alert(data);
result = data;
}
});
//return result;//you can return value like this
I have a javascript function with two promises:
uploadDocument = function (formData, order) {
$.ajax({
type: "POST",
url: "/API/Documents/addDocument",
data: formData,
contentType: false,
processData: false
}).then(function (documentID) {
order.referenceID = documentID;
return $.ajax({
type: "POST",
url: "/API/Documents/addOrder",
data: ko.toJSON(transaction),
contentType: "application/json"
});
}).then(function (result) {
return 'success';
});
}
That works perfectly, the API calls success.
the call to the function is:
uploadDocument(formData, order).then(function (data) {
console.log('success');
})
At this point I'm getting an error:
Uncaught TypeError: Cannot read property 'then' of undefined
What am I doing worng?
You need to return your $.ajax() and then use then on it. Without return the function returns undefined by default, so why you get an error. See return before $.ajax(...).then(...).
uploadDocument = function (formData, order) {
return $.ajax({
type: "POST",
url: "/API/Documents/addDocument",
data: formData,
contentType: false,
processData: false
}).then(function (documentID) {
order.referenceID = documentID;
return $.ajax({
type: "POST",
url: "/API/Documents/addOrder",
data: ko.toJSON(transaction),
contentType: "application/json"
});
}).then(function (result) {
return 'success';
});
}
So all I want to do is conditionally call the .fail method from within the .success method, how?
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { ajaxCall.fail(); return; }
alert("success");
})
.fail(function () {
alert("fail");
});
$.ajax return a promise so you can't do it directly. Your best shot is that :
var fail = function () {
alert("fail");
};
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail") { fail(); return; }
alert("success");
})
.fail(fail);
You can simply call as this.fail(); as shown below :-
var ajaxCall = $.ajax({
url: pUrl,
type: "POST",
data: pData,
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8"
})
.always(function () {
alert("always");
})
.success(function (data) {
if (data == "fail")
{
this.fail();
return;
}
alert("success");
})
.fail(function () {
alert("fail");
});
For more information :-
http://www.youlikeprogramming.com/2013/07/jqueryajax-conditionally-call-error-method-fro-success/
just use the "this" keyword to actually call any other method of the ajax call, I have made a sample for error method.
$.ajax({
url: 'url',
dataType: 'json',
contentType: 'application/json; charset=utf-8;',
type: 'GET',
success: function (dataReturn) {
this.error('error called explicitly');
},
error: function (errorMessage) {
if(errorMessage.ResponseText) // or directly compare as errorMessage !== "error called explicitly" if u send the same message elsewhere
//actual error code
else
alert(errorMessage);
}
});
hope this helps :)
I have the following Ajax request which I make. Currently if the json response is true then the success callback runs. But if the json response is false then the success callback isn't run, even if the Ajax request itself is successfully made.
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'check_username',
user: user_email
},
success: function(json) {
if (json.user_exists == true) {
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'auto_login',
user: user_email
},
success: function(json) {
$('#aux_lightbox_overlay').fadeOut();
}
});
}
if (json.user_exists == false) {
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'auto_register',
user: user_email
},
success: function(json) {
$('#aux_lightbox_overlay').fadeOut();
}
});
}
}
});
So my question is, how do I get the callback to run even if the response is false?
Thanks
Maybe you need to use complete instead success and error.
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'check_username',
user: user_email
},
complete: function(json) {
if (json.user_exists == true) {
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'auto_login',
user: user_email
},
success: function(json) {
$('#aux_lightbox_overlay').fadeOut();
}
});
}
if (json.user_exists == false) {
$.ajax({
url: "http://testdomain.com/wp-admin/admin-ajax.php",
type: "POST",
dataType: "json",
cache: false,
data: {
action: 'auto_register',
user: user_email
},
success: function(json) {
$('#aux_lightbox_overlay').fadeOut();
}
});
}
}
});
Are you sure that when the user does not exist, json.user_exists is indeed equal to false? If I understand you correctly, the if (json.user_exists == false){...} statement is not triggered, so there is something weird there.
For more robust code, you could change
if (json.user_exists == true) {
// ...
}
if (json.user_exists == false){
// ...
}
into
if (json.user_exists == true) {
// ...
}
else {
// ...
}