I have a problem with my $.post query. Here is my code :
function verif_subscribe_sale() {
var URL_ROOT = "http://my_website.com/";
var email_sale = document.getElementById('email-sale');
var name_sale = document.getElementById('name-sale');
var url_sale = document.getElementById('url-sale');
var password_sale = document.getElementById('password-sale');
var token = document.getElementsByName('_token');
test = 0;
$.post(URL_ROOT + 'check-url', { url: url_sale.value, token: token.value } ).done(function( data ) {
if(data == "notok" || data.length < 4){
document.getElementById('error_url').style.display="block";
test = 1;
}
});
if(name_sale.value.length < 4){
document.getElementById('error_name_length').style.display="block";
test = 1;
}
if(check_email(email_sale) != true) {
document.getElementById('error_mail').style.display="block";
test = 1;
}
if(test == 0){
return true;
}else{
return false;
}}
This code is called from an HTML form:
<form action="{{{ URL::to('create_my_sale') }}}" method="post" onsubmit="return verif_subscribe_sale();">
The problem is, as post is asynchronous, the form can be submited even if the post return doesn't satisfy the condition. Is it possible to wait the end of the post loop before to submit the form? I tried some stackoverflow solution (like a callback), but it doesn't work...
Edit part:
I tried this way in the JS :
function verif_subscribe_sale(callback) {
var URL_ROOT = "http://www.mysite.com/";
var url_sale = document.getElementById('url-sale');
var token = document.getElementsByName('_token');
test = 0;
$.post(URL_ROOT + 'check-url', { url: url_sale.value, token: token.value } ).done(function( data ) {
if(data == "notok" || data.length < 4){
document.getElementById('error_url').style.display="block";
test = 1;
}
});
callback(test);
}
function test_callback(test){
var name_sale = document.getElementById('name-sale');
var email_sale = document.getElementById('email-sale');
var password_sale = document.getElementById('password-sale');
if(name_sale.value.length < 4){
document.getElementById('error_name_length').style.display="block";
test = 1;
}
if(check_email(email_sale) != true) {
document.getElementById('error_mail').style.display="block";
test = 1;
}
if(test == 0){
return true;
}else{
return false;
}
}
and i called it like that :
<form action="{{{ URL::to('create_my_sale') }}}" id="form-sale" method="post" onsubmit="return verif_subscribe_sale(test_callback);">
But it doesn't work too...