6

I can't seem to figure out how to use ajax to post. I made a silly form to try it out and even after having cut it all the way down to just two values, still can't get anything to work. My html is this:

<html>
<head>
<script type="text/javascript" src="j.js"></script>
<title>Test this<
<body>/title>
</head>
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="submit" value="Submit Form" />
</form>
<div id="status"></div>
</body>
</html>

Then, my external javascript is just a single function so far:

function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}

While my php just echoes the stuff back:

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>

I can't find anything wrong in firebug or in chrome's toolsy thingies.. Can anybody who me what I'm doing wrong?

  • You send "application/x-www-form-urlencoded" as content-type but you're not encoding your values. There are ways how this can be automated but if you just pass your HTTP payload string to .send() you need to URL encode your values. – StanE Dec 20 '14 at 03:26

6 Answers6

6

The whole problem is caused by the fact that you are both submitting the form and performing an AJAX call! status is for sure updated, but in the same moment the page is refreshed (notice that the <input>-values disappear)

Simply avoid the form submit by altering the markup,

<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />

and your code works. Or dont use a form at all. It is to no use when you are AJAXing anyway.


update

I reproduced the whole scenario before answering :

xhr.html

<html>
<head>
<title>Test this</title>
</head>
<body>
<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />
</form>
<div id="status"></div>

<script>
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "xhr.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
    console.log(hr);

    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</body>
</html>

xhr.php

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • What if I'm going to be validating the form using a different function before actually submitting it to php? would I need to to basically just include this function within it if the form passes validation? – include 'breakDance' Sep 20 '13 at 00:33
  • Perform the validation as the first thing in `postStuff`, or call your validation routine from there. If it not validates, abort. That is just one solution. – davidkonrad Sep 20 '13 at 00:36
  • Or make a function `submit()`, which first calls `validate()`, and if that successes then calls `postStuff()`. – davidkonrad Sep 20 '13 at 00:45
  • Well, I appreciate everybody's response so far. I'm very grateful. But, despite having tried everybody's suggestions short of using jquery (nothing against it, I just want to be really proficient with javascript before I start using libraries). I've still not gotten the status div to show the variables as I've specified in the code. Now, it sends the variables to the url. – include 'breakDance' Sep 20 '13 at 00:47
  • 1
    And I like you are not falling in the jQuery-trap. Using jQuery myself, but that is really not the answer to your question. – davidkonrad Sep 20 '13 at 00:53
  • Yeah, this appears to be what I had changed to make it work.. I don't know why I didn't see the update. Thanks! – include 'breakDance' Sep 20 '13 at 00:56
3

Here's how I do it:

In your html file put <SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></SCRIPT>

Then you can call this function that will call (in my case) queryDB.php script.

function queryDB(db,query,doAfter){
$.ajax({
    type: 'POST',
    data: { host: "localhost",
            port: "5432",
            db: db,
            usr: "guest",
            pass: "guest",
            statemnt: query
        },
    url: 'scripts/php/queryDB.php',
    dataType: 'json',
    async: false,

    success: function(result){
        // call the function that handles the response/results
        doAfterQuery_maps(result,doAfter);
    },

    error: function(){
        window.alert("Wrong query 'queryDB.php': " + query);
    }
  });
};
TDrabas
  • 858
  • 6
  • 13
3

Make the:

<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /> <br />
Last Name: <input type="text" name="lname" id="lname" /> <br />
<input type="submit" value="Submit Form" />
</form>

into a button tag:

<form name="testForm">
First Name: <input type="text" name="fname" id="fname" /> <br />
Last Name: <input type="text" name="lname" id="lname" /> <br />
<button type="button" onclick="postStuff();">Submit Form!</button>
</form>

The page refreshes from the form submit as far as I can see. You don't need to use a form if you're using ajax.

Also read: Why is using onClick() in HTML a bad practice? since you're enclosing the post in a function anyway.

EDIT: I just noticed your title and head tags are broken in the source you've put up.

Community
  • 1
  • 1
Arjun Kumar
  • 124
  • 4
  • 1
    Not exactly. It is not "interrupts the ajax request", submit is just the last in the chain of execution. Both are executed very well. You can see that by yourself by reproducing the setup and insert console.log's / alerts. – davidkonrad Sep 20 '13 at 00:32
  • I think David got the answer before me :) Glad to see it worked out for you! As David mentioned, good to see you learning JS properly before jumping onto jQuery. – Arjun Kumar Sep 20 '13 at 01:03
1

Send post to test.php in the same hierarchy and accept the result in html variable

$.ajax(
{
type: "POST",
url: "test.php",
data: {'test': test, 'name': 0, 'asdf': 'asdf'},

success: function(html)
{
alert(html);
}
});

In PHP of the recipient, specify it as follows

<?php 
echo "come here";
echo $_POST['test'];
?>

Directory structure

$ tree
.
├── a.php
└── test.php

reference https://off.tokyo/blog/ajax%E3%81%A7post%E3%82%92%E5%8F%97%E3%81%91%E5%8F%96%E3%82%8B%E6%96%B9%E6%B3%95/

Ryosuke Hujisawa
  • 2,682
  • 1
  • 17
  • 18
0

u need to return false at the end of the function.

function postStuff(){
  // Create our XMLHttpRequest object
  var hr = new XMLHttpRequest();
  // Create some variables we need to send to our PHP file
  var url = "processForm.php";
  var fn = document.getElementById("fname").value;
  var ln = document.getElementById("lname").value;
  var vars = "firstname="+fn+"&lastname="+ln;
  hr.open("POST", url, true);
  hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  // Access the onreadystatechange event for the XMLHttpRequest object
  hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("status").innerHTML = return_data;
    }
  }
  // Send the data to PHP now... and wait for response to update the status div
  hr.send(vars); // Actually execute the request
  document.getElementById("status").innerHTML = "processing...";
  return false;
}
ias
  • 76
  • 3
0

Perhaps it's best for you to use a library like jquery and then you can do something like : $('form').submit(function(){$.post('detinatnion', $('form').serialize());}); but to answer your question since you have a reason for using pure js then:

<form method="post" action="pathToFileForJsFallback.">
First name: <input type="text" id="fname" name="fname" /> <br />
last name: <input type="text" id="lname" name="lname" /> <br />
<input type="submit" value="Submit Form" />
<div id="status"></div>
</form>

JS:

function postStuff(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    mypostrequest = new ActiveXObject(activexmodes[i]);
   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  mypostrequest = new XMLHttpRequest();
 else
  return false;


mypostrequest.onreadystatechange=function(){
 if (mypostrequest.readyState==4){
  if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
   document.getElementById("result").innerHTML=mypostrequest.responseText;
  }
  else{
   alert("An error has occured making the request");
  }
 }
}
var fname=encodeURIComponent(document.getElementById("fname").value);
var lname=encodeURIComponent(document.getElementById("lname").value);
var parameters="fname="+fname+"&lname="+lname;
mypostrequest.open("POST", "destination.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);

}

Again my recommendation to you is to learn js with a library like jquery, because by the time you learn how to do these stuff, these libraries, hardware and everything will be so fast that javascript code like this will become useless for practical every day use.

Neo
  • 11,078
  • 2
  • 68
  • 79