Parameter passing with Ajax (using deferred and promise) help needed - javascript

This is most likely a repeat question since it's a common problem for learners, but I just cant find a to-the-point working solution for the issue (I've been trying to get on top this for ages!):
This works because there's no Ajax:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
function first(){
var bbb;
var test = prompt("enter a number");
if(test == 6){
bbb = true;
return bbb;
} else {
bbb = false;
}
}
function second(){
if(first()){
alert("returned true!!");
} else {
alert("returned false");
}
}
But I can't get this next piece of code to work, because the callback runs before the Ajax call is complete. I know deferred and promise are the modern way to sort callbacks like this, but after reading and watching TONS on the matter, I'm still missing some key logic or syntax and it just won't work for me.
Can someone help me get a working example of deferred in action with the following code? Then from there I'll be able to improve my learning about deferred, but currently I'm getting nowhere.
//-----------------------gets much more confusing with Ajax calls------------------
function firstAjax(){
var check = prompt("number between 1 and 10 to send (6 should return true from PHP...)");
$.post('remote.php',
{
check: check
},function(data) {
var returned = JSON.parse(data);
if(returned == true) {
alert(returned);
return true;
} else {
alert(returned);
return false;
}
});
}
function secondAjax(){
if(firstAjax()){
alert("successfull return");
} else {
alert("return failed"); //callback runs before the post returns...
}
}
Buttons to activate the functions:
<button type="button" onClick="second()">Run Local Javascript only </button>
<button type="button" onClick="secondAjax()">Run Ajax call with param passing</button>
And this is 'remote.php': simple if input = 6 return true.
<?php
$check = $_POST['check'];
if($check == 6){
echo json_encode(true);
} else {
echo json_encode(false);
}
?>

You are doing a asynchronous requests and firstAjax() will return undefined before the response have been received.
You need to define a callback function as a parameter in firstAjax(), and then call this function when the response have been received.
function firstAjax(callback) {
var check = prompt("number between 1 and 10 to send (6 should return true from PHP...)");
$.post('remote',
{check: check},
function (data) {
var returned = JSON.parse(data);
if (returned == true) {
alert(returned);
callback(true);
} else{
alert(returned);
callback(false);
}
});
}
function secondAjax() {
firstAjax(function(result){
if(result){
alert("successfull return");
}else{
alert("return failed");
}
});
}

Related

Is there a way to stop Form from executing action and wait for ajax to complete executing?

Before customers can proceed to paypal, I have a quick check on the database to see if the items still available,. The problem im having is that while Ajax is executing. function check_availability continue executing and returns true to the Form onsubmit before the completion of Ajax. To fix that problem I kept calling the same function within. But I dont think that is the best possible option.
Here is the code:
<form onsubmit="return check_availability(0,0,1)" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="pp1">
function ajax_paypal(orders){
var htpr = new XMLHttpRequest();
var url = "Hi there";
var val = "orders="+orders;
htpr.open("POST", url, true);
htpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
htpr.onreadystatechange = function(){
if(htpr.readyState == 4 && htpr.status == 200){
var sold_out_ids = htpr.responseText;
check_availability("continue", sold_out_ids, 0);
}
};
htpr.send(val);
}
function check_availability(str, sold_out_ids, n) {
if (str === "continue") {
if (sold_out_ids > 0) {
alert("One of your items has sold out! Sorry for any inconvenience");
location.reload();
return false;
} else {
return true;
}
}else if(n === 1){
var orders = [];
var x = document.cookie.split(';'); // your array of cookies
var i = 0;
x.forEach(item => {
//to make sure that item contains "order"
if (item.indexOf('order') > -1) {
var val = item.split("=");
orders[i] = val[1]+"o";
i++;
}
});
ajax_paypal(orders);
}
check_availability(0, 0, 0);//I keep calling this until Ajax is completed
}
You can use following code snippet to solve. This will be called on submit but before actual submit happen if you return true from here form will get submit to paypal. If you return false form won't get submit.
$('#pp1').submit(function() {
var submitOrNot=await callcheck_availability();
return true; // return false to cancel form submit
});
async function callcheck_availability(){
//your function goes here
}
for more on async await read this page on MDN

How to use two ajax field validation on button redirection stop?

Please help me, How to use two ajax field validation on button (if data already exist don't click on button or redirect same page) redirection stop?
This is my ajax code:
function validate()
{
return (chkunm() && chkemail());
}
function chkunm()
{
// alert ("hello");
var unm, http;
unm = document.getElementById("pupilname").value;
http= new XMLHttpRequest();
http.onreadystatechange=function(){
if (http.readyState==4 && http.status==200){
document.getElementById("s1").innerHTML=http.responseText;
}
if(http.responseText==true)
{
// alert ("Welcome");
return true;
}
else
{
// alert ("username already exists");
return false;
}
}
http.open("GET","getunm.php?unm="+unm,true);
http.send();
}
function chkemail()
{
// alert("hello");
// die();
var email, http;
email = document.getElementById("pupilpass").value;
http= new XMLHttpRequest();
http.onreadystatechange=function(){
if (http.readyState==4 && http.status==200){
document.getElementById("s2").innerHTML=http.responseText;
if(http.responseText==true)
{
// alert ("welcome");
return true;
}
else
{
//alert ("email already exists");
return false;
}
}
}
http.open("GET","getemail.php?email="+email,true);
http.send();
}
I want, if data is already exist...!! SO don't click on button .. How can possible.. Help me
Thanks
This answer might help you:
Basically you will have multiple ajax calls that bring back their check results. You will use when to wait for both before checking if you want to redirect or not.
Code:
$(document).ready(function(){
var check1, check2;
$("yourElement(s)").click(function(){
$.when(ajax1(), ajax2()) {
if(check1 || check2) {
// window.location - whatever your soul desires
}
}
}
function ajax1() {
return $.ajax({
url: "someUrl",
dataType: "json",
data: yourJsonData,
// whatever else you need,
success: function(result){
check1 = result;
}
});
}
// idem ajax 2 to get check2 value.
}
As you might have guessed, this code is not quite tested.
I hope this helps.

Form click function to check variable before submitting

I am using a $.get function to check the connection to the server before submitting the ASP login form. If the get function is successful and returns a true then the form should submit, otherwise if it fails and returns false, it should not.
I have tried many different configurations, but everything I've tried has either rendered the button inoperable, or only showing a true, and never a false!
Any advice is appreciated. Thanks.
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Enter" ValidationGroup="LoginUserValidationGroup" class="submitButton" />
UPDATE - The code below executes the get function correctly, but I have a feeling the problem lies within $('form').submit();
When true is returned the page refreshes like it sent the data, but the system does not log the user in. Why is this!?
submitButton.click(function () { // capitalize username on login
var url = 'https://examplesite.com/';
$.get(url).done(function () {
if (usernameBox.val() === '') {
usernameBox.attr('placeholder', 'Username Required');
passwordBox.attr('placeholder', '');
usernameBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val() === '') {
passwordBox.attr('placeholder', 'Password Required');
usernameBox.attr('placeholder', '');
passwordBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val().length < 6) {
passwordBox.focus();
return false;
}
else {
alert('Successful - Now logging in');
$('form').submit();
}
}).fail(function () {
alert('Failed - No Connection');
});
return false;
});
};
$.get is an async function, so online is never set to what you think it is since the rest of the code is being processed before the call is complete. Move your logic into the .done part of it!
$.get(url).done(function () {
online = true;
if (online == true) {
alert('Success');
$('form').submit();
}
else if (online == false) {
alert('Cannot Connect');
return false;
}
else {
return false;
}
}).fail(function () {
online = false;
});

How to find value (true or false) from AJAX response?

I have written a script register user. And in the last step I need value true or false from a function to find that email is already existed or not.
function do_register(user_email){
if (!isemailexist(user_email)) {
document.getElementById("error").innerHTML="email is already exist, please change!!";
document.regForm.user_email.focus()
return false;
}
if (user_email=="") {
document.getElementById("error").innerHTML="email is emphy!!";
document.regForm.user_email.focus()
return false;
}
if(document.regForm.user_name.value!=""){ process_register();} }
function isemailexist ()
xmlHttp.onreadystatechange=function () {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var str=xmlHttp.responseText;
var res=JSON.parse(str);
if (res[0]=="no"){
return false;
}
}
haha=xmlHttp.onreadystatechange.test(res[0]); ///I used test(); methode in order to find value true or false
}
I have tried alot but none of them could give me true or fals !
I have updated my script above, I hope it´s better. Some more code:
PHP CODE
if(mysql_num_rows($result)>0){ // email is already exist
$phpArray = array("no","Erroremail is aleady exist");
echo json_encode($phpArray);
}
You're doing things bit too complicated. There's no need of making an array when the response is simply false, as you're already telling the user that the email already exists.
Instead of doing
if(mysql_num_rows($result)>0){ // email is already exist
$phpArray = array("no","Erroremail is aleady exist");
echo json_encode($phpArray);
}
Just do this in your server side.
if(mysql_num_rows($result)>0){ // email is already exist
return false;
}
As you're no longer using an array, your response changes, and you need to adjust your code a little bit. Remove [0] from res[0].
Then your server response will be false, so change
if (res[0]=="no"){
return false;
}
to
if (res==false){
return false;
}
else{
//continue...
}

Check if a user Is fan of a Facebook page

After logged in I am trying to return if the user is either not a fan of a Facebook page, but the result is always "undefined". But if I replace "return" to "alert" works perfectly.
function pageFan()
{
FB.api({ method: 'pages.isFan', page_id: '175625039138809' }, function(response) {
showAlert(response);
});
}
function showAlert(response)
{
if (response == true) {
return 'like the Application.';
} else {
return "doesn't like the Application.";
}
}
var like = pageFan();
document.getElementById('debug').innerHTML = like; //return undefined
This question has already been answered.
Relevant Javascript:
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
That's because the return in showAlert is not returning "into" the pageFan function. The showAlert function is passed as a callback, meaning it will be called later, outside of pageFan's execution. I think you need to read more about callback functions and asynchronous programming.
function showAlert(response)
{
if (response == true) {
document.getElementById('debug').innerHTML = 'like the Application.';
} else {
document.getElementById('debug').innerHTML = "doesn't like the Application.";
}
}

Categories

Resources