3

I changed the GET methods into POST in php and ajax files but the logical error here is that every time I add a student into the database it doesn't work. I can't really figure out the problem because I'm new to AJAX.

Here's my code:

php file for adding

<?php
//I changed to POST
$q1=$_POST["q1"];
$q2=$_POST["q2"];
$q3=$_POST["q3"];

$con = mysql_connect('localhost', 'root', '');
if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }

mysql_select_db("stud", $con);

$sql="INSERT INTO stud_info(IDno, LName, FName) VALUES ('$q1', '$q2', '$q3')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }


mysql_close($con);
?>

getting the stud id

<?php

$q=$_POST["q"]; //I changed to POST

$con = mysql_connect('localhost', 'root', '');
if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }

mysql_select_db("stud", $con);

$sql="SELECT * FROM stud_info WHERE IDno like '".$q."%'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>IDno</th>
<th>LName</th>
<th>FName</th>
</tr>";

while($row = mysql_fetch_array($result))
 {
 echo "<tr>";
 echo "<td>" . $row['IDno'] . "</td>";
 echo "<td>" . $row['LName'] . "</td>";
 echo "<td>" . $row['FName'] . "</td>"; 
 echo "</tr>";
 }
echo "</table>";

mysql_close($con);
?>

JavaScript for ajax It doesn't work very well

// JavaScript Document
var xmlHttp;

function showStud(id)
{ 
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request");
        return;
    }
    var url="getStud.php";
    url=url+"?q="+id;   
    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("POST",url,true);
    xmlHttp.send(null);
}

function addStud(id, ln, fn)
{ 
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request");
        return;
    }
    var url="addStud.php";
    url=url+"?q1="+id+"&q2="+ln+"&q3="+fn;  
    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("POST",url,true);
    xmlHttp.send(null);
}

function editStud(id, ln, fn)
{ 
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request");
        return;
    }
    var url="editStud.php";
    url=url+"?q1="+id+"&q2="+ln+"&q3="+fn;
    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("POST",url,true);
    xmlHttp.send(null);
}

function deleteStud(id)
{ 
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request");
        return;
    }
    var url="deleteStud.php";
    url=url+"?q="+id;   
    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("POST",url,true);
    xmlHttp.send(null);
}

function stateChanged() 
{ 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    { 
        document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
    } 
}

function GetXmlHttpObject()
{
    var xmlHttp=null;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        //Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

4 Answers4

2

There are few things I would like to point out. First you are executing the function stateChanged here:

xmlHttp.onreadystatechange=stateChanged;

and assigning the RESULT of that function (which in this case is undefined) to xmlHttp.onreadystatechange.

Now, when the readystate changes, XMLHttpRequest attempts to call onreadystatechange which is now undefined, so nothing will happen.

Try this:

function stateChanged(){
    return function(){
        if(xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
            }

        }
    }
}

Now, you are still assigning the result of the function to http.onreadystatechange, but this time it is a callable function instead of undefined.

And second, to POST data like an HTML form, add an HTTP header with setRequestHeader(), and specify the data you want to send in the send() method, like this:

// Example of deleteStud(id) function
var url="deleteStud.php";
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange=stateChanged();
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("q="+id);

Edited:

For example, your showStud function would be like this,

function GetXmlHttpObject(){
    // your code
}

function stateChanged(){
    return function(){
        if(xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
            }

        }
    }
}

function showStud(id)
{ 
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null){
        alert ("Browser does not support HTTP Request");
        return;
    }
    var url="getStud.php";
    xmlHttp.open("POST",url,true);
    xmlHttp.onreadystatechange=stateChanged();
    xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlHttp.send("q="+id);
}

So change your other functions accordingly.

Re-edited:

There are few additional key things you need to know.

1) The correct order of calls is:

  • new XMLHttpRequest
  • xmlHttp.open()
  • xmlHttp.onreadystatechange = ...
  • xmlHttp.send()

In some browsers, calling .open clears any event handlers on it. This allows for clean re-use of the same xmlHttp object, which is supposedly more memory-efficient (but that really doesn't matter if you code properly to let the GC do its job). So, simply put the .open call before the onreadystatechange assignment and you should be good to go.

2) onreadystatechange isn't just fired once. It's fired multiple times, you need to be able to handle that. These are the codes you need to handle:

  • 0 UNSENT - open()has not been called yet

  • 1 OPENED - send()has not been called yet

  • 2 HEADERS_RECEIVED - send() has been called, and headers and status are available

  • 3 LOADING Downloading - responseText holds partial data

  • 4 RESPONSE is ready - The operation is complete

Hence your error check should be inside the xmlHttp.readyState==4 check, like this:

if(xmlHttp.readyState==4){
    if (xmlHttp.status==200){
        // your code
    }

}
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • https://www.dropbox.com/s/zmsft2rtwkl53rc/admin_ajax_problem.zip?dl=0 please take a look at the source code – Jude Howell Sarabia Nov 23 '15 at 13:43
  • @user3762884 You didn't incorporate anything I said. Here's your [updated selectStud.js file](http://pastebin.com/CChnaunn). – Rajdeep Paul Nov 23 '15 at 13:56
  • I've updated that also. Please re-run your code with this updated javascript file. – Rajdeep Paul Nov 23 '15 at 14:00
  • Evertime I click the add button nothing happens – Jude Howell Sarabia Nov 23 '15 at 14:17
  • @user3762884 I've corrected your code wherever necessary. I've also corrected my answer(*because stateChange function was not called properly*) and added few additional key points. Please read the my answer carefully. [Here's your working code](https://www.dropbox.com/sh/mqgkb8yp70evw1y/AAAC3L90Il-DzsnPDXuitOqja?dl=0). Let me know if it works for you. – Rajdeep Paul Nov 23 '15 at 17:03
1

You changed your requests to post - but it seems that you didn't change the placement of your paramters. You still attach them to your url:

xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);

You send "null" in the request body.

You will need to send the paramters in the body to make it work as expected by you. Refer to this: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp for further information.

Edit: Small (non-tested) Example:

xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("q=test?data=asd?moredata=das");

Update: Since you attached the dropbox folder / content I tried it.

You are still missing the essential function seRequestHeader as listed above. After adding this i am able to read the POST data.

Example for your code:

xmlHttp.open("POST","getStud.php",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("q="+id);

IMPORTANT: The seRequestHeader function needs to be called AFTER the open function and BEFORE the send function.

Endpoint dumps the POST variable and displays content as proof that it works

Endpoint dumps the POST variable and displays content as proof that it works

Frnak
  • 6,601
  • 5
  • 34
  • 67
  • I got an error in getting the stud_id `$q=$_POST["q"];`. Undefined index: q – Jude Howell Sarabia Nov 23 '15 at 12:06
  • That just means that you actually do not receive the data. In general you would wrap your php code in something like if(isset($_POST['p')) { $p=$_POST['p']; } However that won't fix the error it self. please post the code you use in the send function – Frnak Nov 23 '15 at 13:28
  • https://www.dropbox.com/s/zmsft2rtwkl53rc/admin_ajax_problem.zip?dl=0 here's my full source code I'm stuck because of the AJAX stuff – Jude Howell Sarabia Nov 23 '15 at 13:41
  • Not sure if you are still looking for the answer - I updated my response using an example out of your code. Please add the setRequestHeader function. – Frnak Nov 24 '15 at 08:10
1

POST method via JS XMLHttpRequest compared to GET is a bit different.

Just a quick untested example:

GET

url=url+"?q1="+id+"&q2="+ln+"&q3="+fn;  
xmlHttp.open("GET",url,true);
xmlHttp.send();

POST

url=url;  // stays the same
xmlHttp.open("POST",url,true);
xmlHttp.send(q1="+id+"&q2="+ln+"&q3="+fn); // params go into .send()

You can find working examples at w3schools.com

Based on your source

  • addStud function is missing xmlHttp.setRequestHeader
  • and xmlHttp.send string is missing & connecting parameters

like so:

xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("q1="+id+"&q2="+ln+"&q3="+fn);
  • I got an error in getting the stud_id $q=$_POST["q"]; in the php file – Jude Howell Sarabia Nov 23 '15 at 12:55
  • @user3762884 you are going to have to be a bit more specific. What kind of error ? – Ivan Veštić Nov 23 '15 at 13:01
  • Undefined index: q in the $q=$_POST["q"]; in the php file – Jude Howell Sarabia Nov 23 '15 at 13:03
  • @user3762884, The error is because you are not adding an HTTP header with `setRequestHeader()`. To POST data like an HTML form, you need to add an HTTP header with `setRequestHeader()`. And even if this works, you won't be able to display anything using `stateChanged` function. I've explained the reason in my answer. – Rajdeep Paul Nov 23 '15 at 13:25
  • https://www.dropbox.com/s/zmsft2rtwkl53rc/admin_ajax_problem.zip?dl=0 please take a look at the source code – Jude Howell Sarabia Nov 23 '15 at 13:43
  • user3762884 check my updated answer _(Based on your source)_ segment above. But also @rajdeep-paul was also pointing you in the right direction all along. – Ivan Veštić Nov 23 '15 at 14:05
1

Undefined index: q in the $q=$_POST["q"]; in the php file

Maybe because you are using q1 in your php file while on the javascript file you are using q only or vice versa. Make it the same and it should work fine.

And don't forget to add this before xmlHttp.send :

xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");