Variable from ajax function doesnt work outside function [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have simple registration form. Ajax and form works fine but can't connect them by variable, I mean when ajax check that email is in database register should stop by variable error but it isnt.
Code:
$('.login').submit(function(e) {
e.preventDefault();
var error = 0;
var self = $(this);
var $name = self.find('[type=name]');
var $email = self.find('[type=email]');
var $pass = self.find('[type=password]');
//MY AJAX
var email = $email.val();
$.ajax({
url: 'http://localhost/FPD/nowe/inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
//THAT ERROR VARIABLE DOESNT WORK OUTSIDE AJAX FUNCTION
error++;
}
},
error: function(xhr, textStatus, error) // THOSE ROWS
{
alert(error);
}
});
if (error!=0)return;
//THAT STILL WORKS EVEN AJAX ERROR
self.find('[type=submit]').attr('disabled', 'disabled');
self.children().fadeOut(300,function(){ $(this).remove() })
$('<p class="login__title">sign in <br><span class="login-edition">welcome to A.Movie</span></p><p class="success">You have successfully<br> signed in!</p>').appendTo(self)
.hide().delay(300).fadeIn();
// var formInput = self.serialize();
// $.post(self.attr('action'),formInput, function(data){}); // end post
}); // end submit

The reason is ajax is called Asynchronously. You have to make async: false in your ajax call. So your code will become :
$.ajax({
url: 'http://localhost/FPD/nowe/inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
async : false, //<----
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
//THAT ERROR VARIABLE DOESNT WORK OUTSIDE AJAX FUNCTION
error++;
}
},
error: function(xhr, textStatus, error) // THOSE ROWS
{
alert(error);
}
});
This will ensure that nothing will executed after ajax call unless you get your response.

Related

Codeigniter & Ajax - Condition statement in javascript

Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.

How to get error response in Ajax?

I am trying to add data to a cart(using) Ajax jQuery, now I have added a primary key constraint and I want when the constraint is violated in get the error message in jQuery:
function add()
{
$(document).ready(function()
{
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {pid:pid ,user:user},
success:
function()
{
alert("Item has been added to cart");
},
error:
function()
{
alert("Item already present in the cart");
}
});
return false;
});
});
}
The error function never runs, the functionality in the DB is running fine but I don't see the error message in Ajax.
Here is Java code:
public int addintocart(String user,int pid)
{
try
{
conn = obj.connect();
String sql="insert into cart(userid,product_id,quantity) values(?,?,?)";
ps1 = conn.prepareStatement(sql);
ps1.setString(1,user);
ps1.setInt(2,pid);
ps1.setInt(3,1);
ps1.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(Exception k)
{
k.printStackTrace();
}
return x;
}
What is going wrong?
You have to send the error back as a servlet response from Java. Here is an example: How to return Java Exception info to jQuery.ajax REST call?
Also, you are missing some parameters in the ajax error function. It might be another problem. Check out http://api.jquery.com/jquery.ajax/ You should evaluate the error and present the appropriate message.
That error code wwill never work. the onerror event of AJAX only runs when connection cannot be established or URL does not exist. You have to return something from your the server indicating success or faliure.
I would do it this way.
PHP(convert this code to JAVA):
if(success){
die(1);
} else {
if(notyetincart){
die(0);
} else {
die(2);
}
}
Then Jquery coded:
function add()
{
$(document).ready(function()
{
$('#addtocart').submit(function() {
//$('#add-button').prop('disabled',true);
var user = $('#user').val();
var pid = $('#pid').val();
$.ajax({
type: "post",
url: "/devilmaycry/register?action=addtocart",
data: {pid:pid ,user:user},
success:
function(response)
{
if(reponse==="1")
alert("Item has been added to cart");
else if(reponse==="0")
alert("Item could not be added to cart");
else alert("Item already present in the cart");
},
error:
function()
{
alert("Item could not be added to cart due to poor network connection");
}
});
return false;
});
});
}
Hope this helps

jquery ajax always results in 'error' even when it works

I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}

Using AJAX to submit form to two locations [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I need some help. I'm using AJAX to submit my form to one location and then to another location. once its posted to that second location it sends an email with php to whoever I want, but i cant seem to get it to work. Can some one please help.
Here is my code below:
$(document).ready(function(){
$('input#submit').submit(function(event){
var dataString = $('form :input').serialize();
$.ajax({
type: 'GET',
url: 'http://www.domain.com/sendmail.php',
data: dataString,
success: function(result){
$('p#message').text('SUCCESS!!!');
},
error: function(result){
$('p#hint').text('there was an error');
}
});
event.preventDefault();
});
});
Unless you have some algorithms already in place, you will have problems on the server side handling the data. You may want to prepare the data and than stringify it to JSON. I would also keep the ajax functionality in its own function an use the promise feature. That way you can also use it for other calls within your script.
ajax function with deferred
function ajaxsend(data, url) {
var deferred = $.ajax({
type: 'POST',
url: url,
data: data,
dataType: "json",
});
return deferred.promise();
}
form data handling and preparation
$("form").submit(function (event) {
event.preventDefault();
var formdata = $('form').serializeArray();
var formobject = {};
// transform data to prepare for JSON
$(formdata).each(function (e) {
formobject[formdata[e].name] = formdata[e].value;
});
var data = {
json: JSON.stringify(formobject)
};
var url = 'http://www.domain.com/sendmail.php';
var url2 = 'some_other.php';
ajaxsend(data, url).done(function (response) {
// handle returned results
console.log(response);
}
ajaxsend(data, url2).done(function (response) {
// handle returned results
console.log(response);
}
}
At the server side you receive the value with:
$data = json_decode($_POST['json']);
Then you can access your data with the fieldnames of your form. For instance ..
$data -> firstname;
You can send a response from the php file:
if(success == true) {
$result = array("success" => true , "message" => "form submitted");
echo json_encode($result);
}
if(success == false) {
$result = array("success" => false , "message" => "an error occured");
echo json_encode($result);
}
At the javascript side you can catch the response values
console.log(response.success);
console.log(response.message);
Check the difference:
$('form').submit(function(event){ // 'input#submit' is a button and cannot be "submited", just clicked
var dataString = $(this).serialize(); // suffisant
$.ajax({
type: 'GET',
url: 'http://www.domain.com/sendmail.php',
data: dataString,
success: function(result){
$('p#message').text('SUCCESS!!!');
return true; // trigger the form default action
},
error: function(result){
$('p#hint').text('there was an error');
}
});
event.preventDefault();
});

my javascript function dont display alert message when get data from database through ajax in mvc3 [duplicate]

This question already has an answer here:
javascript alert messages is not show in mvc3
(1 answer)
Closed 9 years ago.
I am working on a form in mvc3 and use form validations in javascript and ajax.
in my form i add code and description in database and before form submission want to check that code already exist in database or not.i get the code in javascript through ajax function call andd eturn data in json form. when i get the data i display error message in alert to user that code already exist. but my alert is not display.what can i do for it.
below is my javascript save button click function
$('#sve').click(function () {
//e.preventDefault();
var iscodeexis = CodeExistChk();
if (iscodeexis) {//
//***********************CODE TO SAVE DATA IN DATABASE***********************************
var person = { AcCode: $('#AcCode').val(), Descrip: $('#Descrip').val(), AddOn: dd };
$.ajax({
url: '/Home/Save?action=Sve',
type: "POST",
data: JSON.stringify(person),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
// $('#message').html('Record saved successfully' + result).fadeIn();
alert("Record saved successfully");
},
error: function () {
// $('#message').html('Error Occurred').fadeIn();
alert("Record not saved successfully");
}
});
}//end of is valid function chk
else
return false;//if isvalid function return false then save button also return false
}); //end button clcik function
function CodeExistChk() {
subA = $('#AcCode').val().trim();
// ===========================check whether code exist already or not
if (subA.length === 10) {
str1 = "select AcCode from Account where AcCode='";
str2 = str1 + subA + "'";
GetCodeData(str2); //check whether code exist or not
strRes = strRes.substring(1, strRes.length - 1);
if (strRes.length > 0 && strRes != "") //if code exist then return false and not allow to enter code
{
alert('Code already exist cannot insert record');
return false;
}
}
//===============================
}
below is getcodedata function which use in above code to get code from database
//===============FUNCTION TO GET CODE FROM DATABASE TO USE IN JS FILE==========
function GetCodeData(Str) {
var p = {
StrSql: Str
};
$.ajax({
url: '/Home/GetGenVal',
type: 'POST',
// contentType: 'application/x-www-form-urlencoded',
dataType: "JSON",
contentType: "application/json; charset=utf-8",
processData: false,
crossDomain: false,
traditional: true,
data: JSON.stringify(p),
cache: false,
// success: callback
success: function (data) {
//$("#Descrip").val(data);
// ResSubCode = data;
strRes = null;
strRes = data;
return strRes;
}
});
}
waiting for early solution.
Whoa, I see a some mistakes in this code.
At first, never construct your sql queries on client side to execute them. What if I modify the query to be a "delete from"? Bye bye database!
I would simply edit your logic and use a [RemoteAttribute] MVC3/4 feature to call a controller action and return simply a true or false.
Check it here: Remoteattribute test usage
You cannot be wrong!
Vincenzo.

Categories