Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My first post here. I am new to Java/AJAX, but I have some experience in PHP. I am trying to pass html form data to a php file for processing. The goal is to have the php script process the form data and return a true/false flag. I am trying AJAX as I dont want a screen refresh. Based on the response from the php script a popup will overlay the existing screen with information to the user.

My HTML form code is:-

<form name="screen3" method="post" action="" id="scr3" />
<input type="image" src="images/proceed.jpg" alt="Proceed" id="proceed1" name="submit" value="Send" />
</form>            

I have redirected the submit button from the form using javascript:-

<script type="text/javascript">
$(document).ready(function() {
$('#proceed1').click(function(e) {
    e.preventDefault();
    x=validateScreen3();
    if (x) {getFormData();}
        })
    });
</script>

So far so good, validateScreen3() is called and validates the users entry (wont bore you with the script). getFormData is called but that is where the problem lies:-

function getFormData() {
var xmlhttp;
var emailAddress = document.getElementById("emailaddress").value;
var entryCode = document.getElementById("entrycode").value;
var acceptance = document.getElementById("acceptance").value;
var Sel = document.getElementById("sel").value;


xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","test1.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("emailaddress="+emailAddress);
}

I've confirmed that the variable data is getting passed to the function ok, but the test1.php script referenced above doest seem to be being called/executed. Here is the test1.php file:-

<?php
$here = $_POST['emailaddress'];
echo '</div></div>';
if (!empty($here)) {
echo '<div style="position:absolute; top:100px; left:300px; width:400px; height:200px; background-color:#CCC; color:#000; z-index:50;">';
echo 'got the variable '.$here;
echo '</div>';
}
else {
echo '<div style="position:absolute; top:100px; left:300px; width:400px; height:200px; background-color:#CCC; color:#000; z-index:50;">';
echo 'DIDNT GET the variable '.$here;
echo '</div>';
}

?>

Neither of these div's are showing up and from every test I can think of, the file is simply not being called. Any ideas or suggestions would be greatly appreciated.

share|improve this question
    
Java !== JavaScript, not even close (==), they're completely different languages –  Elias Van Ootegem Jun 7 '13 at 9:05
add comment

2 Answers

up vote 1 down vote accepted

You need to add an event handler for the XMLHttpRequest's onreadystatechange event. When PHP sends its response, this event will be fired:

xmlhttp.onreadystatechange = function(response)
{
    if (this.readyState===4 && this.status===200)
    {//readyState 4 means request is finished
        document.body.innerHTML += response;//since it's an HTML response...
    }
};

But since you're using jQ, you needn't worry about all those headers... just check $.ajax.

At some point, you might want to ditch jQ, because you have to support older browsers (IE<9, or even IE<8). In that case this might prove helpful

To clarify:
Vanilla JS:

var xhr =new XMLHttpRequest();
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function()
{
    if (this.readyState === 4 && this.status === 200)
    {//response is xhr property in vanilla JS
         document.body.innerHTML += this.responseText;
    }
    if (this.readyState === 4 && this.status !== 200)
    {//error in request
        console.log(this);//<-- check your console
        document.body.innerHTML += '<h1>Http error: ' + this.status;
    }
};
xhr.open("POST","test1.php", true);
xht.send("emailaddress="+emailAddress);

That should work just fine. If, for some reason, it doesn't, try it with jQuery like so:

$.ajax({ url: 'test1.php',
         type: 'POST',
         data: {emailaddress: $('#emailaddress').val()},
         success: function(response)
         {
              document.body.innerHTML += response;
         }
});

If this doesn't work for you, then perhaps your url is wrong, or the server running your PHP script is on another domain, or you'll have to post a follow-up question.
Hope this helps, though

share|improve this answer
    
Thanks. still no luck in getting the php div's to show, but I think it is more the logic flow than the coding syntax. Will try the ajax script you recommended and see how that goes. –  Dave Teasdale Jun 8 '13 at 7:23
    
@DaveTeasdale: Added some full examples for you, and some other things you might want to take into consideration. The main reason why my first answer didn't work probably was because I forgot that, in Vanilla JS, the response isn't passed to the readystatechange handler, but is assigned as a property to the XHttpRequest object instance itself. My "new" snippets fix this issue, though. Happy Coding –  Elias Van Ootegem Jun 9 '13 at 11:13
add comment

You've written JavaScript to make an HTTP request, but you haven't written any to use the data in the response.

You need to wait until the response comes back, and then do something with xmlhttp.responseText.

See Using XMLHttpRequest.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.