Go Back   CodingForums.com > :: Client side development > JavaScript programming > Ajax and Design

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 08-02-2011, 12:16 PM   PM User | #1
dev07
New Coder

 
Join Date: Aug 2011
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
dev07 is an unknown quantity at this point
Unhappy Need help on return function result

Hello everyone,

I am trying to get return value from a function while submitting "a form". But, i am failing to get the correct result.

Please help me on this. I am posting code below.

My aim:

1) To check availability of an item while submitting the form.

2) If item is available, then confirm a contract using javascript confirm function.

3) If the user agrees the return true. Else return false.

4) If the item is not available the alert a message and return false.


My code:

<form method="post" name="abc" onsubmit="return contract(2)">

</form>



function contract(count_number)
{
var item1=document.getElementById('ItemId1'+count_number).value;
var response=" ";

if(window.XMLHttpRequest)
{
contract_xml=new XMLHttpRequest();
}
else
{
contract_xml=new ActiveXObject("Microsoft.XMLHTTP");
}
contract_xml.onreadystatechange=function()
{

if(contract_xml.readyState==4)
{
//alert("4");
response=contract_xml.responseText;

}
else if( (contract_xml.readyState==3) || (contract_xml.readyState==2) || (contract_xml.readyState==1) )
{
response="";
}

};

contract_xml.open("GET","check_available_offer.php?item_id="+item1,true);
contract_xml.send();

if(response==1)
{
if(confirm('Please confirm the that this is a binding contract. '))
{
return true;
}
else
{
return false;
}

}
else
{
alert("Sorry, you are a little late. Better luck next time.");
return false;
}

}


Its always displaying the alert message and returning false.

Please help me on this. Thanks in advance.
dev07 is offline   Reply With Quote
Old 08-02-2011, 12:29 PM   PM User | #2
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
You stumbled upon the most common pitfall in using Ajax

The first "A" in Ajax stands for "asynchronous". That means: The javascript code following the Ajax request .send() continues to execute while(!) the request is still running. A process in the background will call the onreadystatechange callback as soon as the readyState of the request changes. As soon as the readyState reaches 4 the request is finished.

That results in two facts:
1. If you want to alert the result of the request outside of the callback it will not work
2. Everything you want to do with the result of the request has to be done in (or started from) the onreadystatechange callback

So if you move the code from below the .send() into the onreadystatechange callback, it will start to work all of a sudden
devnull69 is offline   Reply With Quote
Old 08-02-2011, 12:40 PM   PM User | #3
dev07
New Coder

 
Join Date: Aug 2011
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
dev07 is an unknown quantity at this point
Quote:
Originally Posted by devnull69 View Post
You stumbled upon the most common pitfall in using Ajax

The first "A" in Ajax stands for "asynchronous". That means: The javascript code following the Ajax request .send() continues to execute while(!) the request is still running. A process in the background will call the onreadystatechange callback as soon as the readyState of the request changes. As soon as the readyState reaches 4 the request is finished.

That results in two facts:
1. If you want to alert the result of the request outside of the callback it will not work
2. Everything you want to do with the result of the request has to be done in (or started from) the onreadystatechange callback

So if you move the code from below the .send() into the onreadystatechange callback, it will start to work all of a sudden

I followed what you have advised earlier. But failed to get result it was returning true each time. Then i used this code. Anyways, again i tried what you have advised and find to get correct result. Posting modified code below.



function contract(count_number)
{
var item1=document.getElementById('ItemId1'+count_number).value;

var response=" ";

if(window.XMLHttpRequest)
{
contract_xml=new XMLHttpRequest();
}
else
{
contract_xml=new ActiveXObject("Microsoft.XMLHTTP");
}

contract_xml.onreadystatechange=function()
{

if(contract_xml.readyState==4)
{
//alert("4");
response=contract_xml.responseText;

if(response==1)
{
if(confirm('Please confirm that this is a binding contract '))
{
return true;
}
else
{
return false;
}

}
else
{
alert("Sorry, you are a little late. ");
return false;
}



}
// else if( (contract_xml.readyState==3) || (contract_xml.readyState==2) || (contract_xml.readyState==1) )
// {
// response="";
// }

};

contract_xml.open("GET","<?php echo $site_url; ?>check_available_offer.php?item_id="+item1,true);
contract_xml.send();
}




But is there any other solution? Can you just modify this?

Last edited by dev07; 08-02-2011 at 12:48 PM..
dev07 is offline   Reply With Quote
Old 08-02-2011, 01:56 PM   PM User | #4
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
Not quite

As I told you: The javascript code keeps running while the request is being processed. That includes the end/return of the function. I.e. the function has already returned "long before" the request finishes. So it's pointless to return something from within the callback. Every action has to be performed inside the callback. So you will have to move everything you want to do with the result into the callback (or into a function and call this function from the callback)
devnull69 is offline   Reply With Quote
Old 08-03-2011, 06:30 AM   PM User | #5
dev07
New Coder

 
Join Date: Aug 2011
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
dev07 is an unknown quantity at this point
Quote:
Originally Posted by devnull69 View Post
Not quite

As I told you: The javascript code keeps running while the request is being processed. That includes the end/return of the function. I.e. the function has already returned "long before" the request finishes. So it's pointless to return something from within the callback. Every action has to be performed inside the callback. So you will have to move everything you want to do with the result into the callback (or into a function and call this function from the callback)
Well, i will try to do this. But. at the same time can you guide me how can i return the result into the callback? Will it be better to write two separate function (One for validation and one for ajax response) for this? Then where should i call the ajax function as the whole operation depends on the response of this ajax function.
dev07 is offline   Reply With Quote
Old 08-03-2011, 10:28 AM   PM User | #6
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
I think it would be the easiest to do something like that:
Code:
function contract(count_number) {
   var item1=document.getElementById('ItemId1'+count_number).value;

   if(window.XMLHttpRequest) {
      contract_xml=new XMLHttpRequest();
   } else {
      contract_xml=new ActiveXObject("Microsoft.XMLHTTP");
   }

   contract_xml.onreadystatechange=function() {
      if(contract_xml.readyState==4) {
         response=contract_xml.responseText;

         if(parseInt(response, 10)==1) {
            if(confirm('Please confirm that this is a binding contract ')) {
               startAction(true);
            } else {
               startAction(false);
            }
         } else {
            alert("Sorry, you are a little late. ");
            startAction(false);
         }
      }
   };

   contract_xml.open("GET","<?php echo $site_url;?>check_available_offer.php?item_id="+item1,true);
   contract_xml.send();
}

function startAction(requestResult) {
   if(requestResult) {
      // here will be the code to execute if the request result was TRUE
      ...
   }
}

Last edited by devnull69; 08-03-2011 at 10:34 AM..
devnull69 is offline   Reply With Quote
Old 08-03-2011, 10:51 AM   PM User | #7
dev07
New Coder

 
Join Date: Aug 2011
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
dev07 is an unknown quantity at this point
Quote:
Originally Posted by devnull69 View Post
I think it would be the easiest to do something like that:
Code:
function contract(count_number) {
   var item1=document.getElementById('ItemId1'+count_number).value;

   if(window.XMLHttpRequest) {
      contract_xml=new XMLHttpRequest();
   } else {
      contract_xml=new ActiveXObject("Microsoft.XMLHTTP");
   }

   contract_xml.onreadystatechange=function() {
      if(contract_xml.readyState==4) {
         response=contract_xml.responseText;

         if(parseInt(response, 10)==1) {
            if(confirm('Please confirm that this is a binding contract ')) {
               startAction(true);
            } else {
               startAction(false);
            }
         } else {
            alert("Sorry, you are a little late. ");
            startAction(false);
         }
      }
   };

   contract_xml.open("GET","<?php echo $site_url;?>check_available_offer.php?item_id="+item1,true);
   contract_xml.send();
}

function startAction(requestResult) {
   if(requestResult) {
      // here will be the code to execute if the request result was TRUE
      ...
   }
}


Well, thanks a lot for your guideline. But how can i return the result (i.e TRUE / FALSE) to the form using the function startAction? I was passing the value of count_number while submission of the form.

code:

<form action="#" method="post" name="form" onsubmit="return contract(2)">

.
.
.
<input type="submit" name="submit" value="submit"/>
</form>
dev07 is offline   Reply With Quote
Old 08-03-2011, 11:11 AM   PM User | #8
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
You just can't do that

So you should replace the form element with
Code:
<form action="#" method="post" name="form" onsubmit="contract(2); return false;">
and submit() the form programmatically from within the callback
Code:
function contract(count_number) {
   var item1=document.getElementById('ItemId1'+count_number).value;

   if(window.XMLHttpRequest) {
      contract_xml=new XMLHttpRequest();
   } else {
      contract_xml=new ActiveXObject("Microsoft.XMLHTTP");
   }

   contract_xml.onreadystatechange=function() {
      if(contract_xml.readyState==4) {
         response=contract_xml.responseText;

         if(parseInt(response, 10)==1) {
            if(confirm('Please confirm that this is a binding contract ')) {
               document.forms["form"].submit();
            }
         } else {
            alert("Sorry, you are a little late. ");
         }
      }
   };

   contract_xml.open("GET","<?php echo $site_url;?>check_available_offer.php?item_id="+item1,true);
   contract_xml.send();
}
devnull69 is offline   Reply With Quote
Old 08-03-2011, 11:56 AM   PM User | #9
dev07
New Coder

 
Join Date: Aug 2011
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
dev07 is an unknown quantity at this point
Thanks a lot for quick reply. I was trying with your code. But failed to get the result. In Crome, Opera the form is not submitting using the following code after confirming. It was inserting inside the loop. But after that , it was doing nothing.

document.forms["form"].submit();

In firefox, the form was getting submit. But, it was not performing the post task of form submission.

Please help me on this. Thanks for your help.
dev07 is offline   Reply With Quote
Old 08-03-2011, 12:44 PM   PM User | #10
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
Is your form action really "#" ? What do you want to achieve with this action?
devnull69 is offline   Reply With Quote
Old 08-03-2011, 01:37 PM   PM User | #11
dev07
New Coder

 
Join Date: Aug 2011
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
dev07 is an unknown quantity at this point
Using "#" , i want to redirect on the same page itself as i have written the post submission query on this.

Few points i should mention here.

1) There are 10 similar forms in the page. Their name is different. Did it unique dynamically by passing count_number value.

2) passed the value of count_number while submission of the form using the code:

document.forms["form"+count_number].submit();


The structure of the form :


<form name="form<?php echo $j?>" action="#" method="post" onsubmit="contract(<?php echo $j?>);return false;">


<input type="hidden" name="InterestedUserId<?php echo $j?>" id="InterestedUserId<?php echo $j?>" value="<?php echo $user_id?>"></input>

<input type="hidden" name="ItemId<?php echo $j?>" id="ItemId1<?php echo $j ?>" value="<?php echo $product_id?>"></input>

<input type="submit" name="btn_submit" style="background: url(offer.jpg) no-repeat scroll center center transparent; cursor: pointer; border: 0pt none; width: 88px; height: 23px;" value="">


</form>


php code:

if(isset($_POST['btn_submit']))

{
.
.
.
}


Javascript:



function contract(count_number) {

var item1=document.getElementById('ItemId'+count_number).value;
InterestedUserId=document.getElementById('InterestedUserId'+count_number).value;

var response="";


if(window.XMLHttpRequest) {
contract_xml=new XMLHttpRequest();
} else {
contract_xml=new ActiveXObject("Microsoft.XMLHTTP");
}

contract_xml.onreadystatechange=function() {
if(contract_xml.readyState==4) {
response=contract_xml.responseText;

if(parseInt(response, 10)==1)
{
if(confirm('Please confirm that this is a binding contract'))
{
document.forms["accept_offer"+count_number].submit();
}

}
else {
alert("Sorry, you are a little late. ");
}
}
};

contract_xml.open("GET","<?php echo $site_url; ?>check_available_offer.php?item_ids="+item1+"&InterestedUserId="+InterestedUserId,true);
contract_xml.send();
}
dev07 is offline   Reply With Quote
Old 08-03-2011, 07:48 PM   PM User | #12
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
You might have to change action="#" to action="<?php echo $_SERVER['PHP_SELF']?>" to make sure you really submit to the current page
devnull69 is offline   Reply With Quote
Old 08-04-2011, 06:21 AM   PM User | #13
dev07
New Coder

 
Join Date: Aug 2011
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
dev07 is an unknown quantity at this point
I used <?php echo $_SERVER['PHP_SELF']?> in form action, but did not work. Still not submitting the form. Whenever i am trying to submit the form using javascript form submission code

document.forms["accept_offer"+count_number].submit();

the form is not doing any post submission task. But, if i submit it on normal way [i.e returning true from onsubmit action ], the post submission task executes successfully.

Last edited by dev07; 08-04-2011 at 06:28 AM..
dev07 is offline   Reply With Quote
Old 08-04-2011, 07:07 AM   PM User | #14
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
What is the document type of your HTML? If you use XHTML you will not be able to address a form via its name. You should then add an id attribute to it and use document.getElementById(...).submit()
devnull69 is offline   Reply With Quote
Old 08-04-2011, 07:20 AM   PM User | #15
dev07
New Coder

 
Join Date: Aug 2011
Posts: 14
Thanks: 0
Thanked 0 Times in 0 Posts
dev07 is an unknown quantity at this point
I am using the following document type.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

Please suggest me what to do.
dev07 is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 09:11 AM.


Advertisement
Log in to turn off these ads.