0

my problem is: I have to pass a variable from a.php to b.php with an ajax call that take the variable 'numitems' from a.php and pass it to b.php...

My code is below but when I try to retrieve 'numitems' in b.php I receive this message:

Notice: Undefined index: numitems in b.php on line 19

    stringaPost();        
    xmlHttp.open('POST', "b.php", true);    
    xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4) { 
            if (xmlHttp.status == 200) { 
            data: {numitems : <?php $numitems;?> }
            document.getElementById("primaryContent").innerHTML=xmlHttp.responseText;
            }
        }
    }; 

Instead in b.php I have:

$numitems = $_POST['numitems'];

The problem is probably in the line with data: {numitems : <?php $numitems;?> but I'm not sure and I can't figure out the root of the problem.

3
  • This should actually be: <?php echo $numitems;?> or <?=$numitems;?>, but you're probably executing the script way before $numitems is being set. Commented Jul 16, 2013 at 18:19
  • Why b.php don't call a.php directly to get those variables ? Commented Jul 16, 2013 at 18:20
  • Read this I think Its Use Full for You. [stackoverflow.com/questions/15637101/… [1]: stackoverflow.com/questions/15637101/… Commented Jul 16, 2013 at 18:21

1 Answer 1

4

You need to set the data in the request rather than the success callback. As several other people have pointed out you are also missing an echo statement in your php.

stringaPost();     
xmlHttp.open('POST', "b.php", true);    
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4) { 
        if (xmlHttp.status == 200) { 
            document.getElementById("primaryContent").innerHTML=xmlHttp.responseText;
        }
    }
}; 
xmlHttp.send("numitems=<?php echo $numitems;?>");
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, the last line was what I missed.
I would ask you another thing. We're in b.php and $numitems which is $_POST['numitems'] should be increased by 1. So we do $numitems++ and after I would return it to a.php, How can I do this? Thanks again
In b.php you need to print out the new numitems to the page where it will be obtained through xmlHttp.responseText in your onreadystatechange function. If you need to send back both the new number and something else you'll need to send both back by printing them to the page and then parse the returned page with javascript in the onreadystatechange function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.