Catty
Catty

Reputation: 466

Sending data from form to php file using post method

I am trying to send sent and id values from form.php to test.php. Without ajax use it works fine. I am learning ajax and here is my code:

<html>
<head>
<script>
function showUser(str)
{
    if (str=="")
    {
        document.getElementById("txtHint").innerHTML="";
        return;
    }

    if (window.XMLHttpRequest)
    {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }

    xmlhttp.open("POST","ajax_test.php?q="+str,true);
    xmlhttp.send(sent&id);
}
</script>
</head>
<body>
<form>
    Enter the sentence: <input type="text" name="sent"/><br/>
    <input type="submit" name="insert" onclick="showUser(this.value)"/>
</form>
</br>
UPDATE </br>
<form action="ajax_test.php" method="post"/>
    <pre>
        Enter the ID : <input type="text" name="id"/><br/>
        Enter the sentence: <input type="text" name="sent"/><br/>
    </pre>
    <input type="submit" name="update"/>
</form>
</br>
<form>
    <input type="submit" onclick="showUser(this.value)"/>
</form>
<br>
<div id="txtHint">
    <b>Person info will be listed here.</b>
</div>
</body>
</html>

ajax_test.php is here:

<html> <body > 
<?php
$q = $_GET["q"];
if (!empty($_POST['insert']))
{
    echo "Operation: Insert";
    echo "<br/>";

    $s    = $_POST['sent'];
    $flag = 0;

    echo "Entered sentence : $s";

    if (preg_match_all('/[^=]*=([^;@]*)/', 
        shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
        $matches)) //Values stored in ma.
    {
        $x = (int) $matches[1][0]; //optionally cast to int
        $y = (int) $matches[1][1];
    }

    echo "<br/>";
    echo "Positive count :$x";
    echo "<br/>";
    echo "Negative count :$y";
    echo "<br/>";

    //---------------DB stuff --------------------
    $con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $sql1 = "INSERT INTO table2 
             (id,sent,pcount,ncount,flag)
             VALUES
             ('','$_POST[sent]','" . $x . "','" . $y . "','" . $flag . "')";
    if (!mysqli_query($con, $sql1)) {
        die('Error: ' . mysqli_error($con));
    }

    echo "1 record added";
    mysqli_close($con);
}

// -------------------------------UPDATE --------------------------
if (!empty($_POST['update']))
{
    echo "Operation: update";
    echo "<br/>";

    $s    = $_POST['sent'];
    $flag = 1;

    echo "Entered sentence : $s";

    if (preg_match_all('/[^=]*=([^;@]*)/', 
        shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
        $matches)) //Values stored in ma.
    {
        $x = (int) $matches[1][0]; //optionally cast to int
        $y = (int) $matches[1][1];
    }

    echo "<br/>";
    echo "Positive count :$x";
    echo "<br/>";
    echo "Negative count :$y";
    echo "<br/>";

    //---------------DB stuff --------------------
    $con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $sql1 = "INSERT INTO table2 
             (id,sent,pcount,ncount,flag)
             VALUES
             ('$_POST[id]','$_POST[sent]','" . $x . "','" . $y . "','" . $flag . "')";
    if (!mysqli_query($con, $sql1)) {
        die('Error: ' . mysqli_error($con));
    }

    echo "1 record added";
    mysqli_close($con);
}
?>
</html > </body >

When I click the button it shows nothing. How can I sent id and sent values so that I can use it on ajax_test.php the I am using?

Upvotes: 2

Views: 3294

Answers (2)

user123
user123

Reputation: 5407

Here is the code: Context-type was missing and some other changes!

<html>
<head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
    <meta content="utf-8" http-equiv="encoding" />
    <script type="text/javascript">
    function showUser(form, e) {
        e.preventDefault();
        e.returnValue=false;
        var xmlhttp;
        var submit = form.getElementsByClassName('submit')[0];
        var sent = form.elements['sent'].value;
    var id = form.elements['id'].value;

        if (window.XMLHttpRequest) {
            xmlhttp=new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function(e) {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open(form.method, form.action, true);
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
        xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value);
    }
    </script>
</head>
<body>
    <h4>INSERT</h4>
    <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
        <pre>
             <label>Enter the sentence: <input type="text" name="sent"></label><br/>
        </pre>
                <input type="submit" class="submit" name="insert" value="submit"/>
        <input type="" name="id" style="display: none"/>
    </form>

    <h4>UPDATE</h4>
    <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
        <pre>
            <label>Enter the ID:        </label><input type="text" name="id"><br>
            <label>Enter the sentence:  <input type="text" name="sent"></label><br />
        </pre>
        <input type="submit" class="submit" value="submit" name="update"/>
    </form>

    <br />
    <div id="txtHint">
        <b>Person info will be listed here.</b>
    </div>
</body>
</html>

Upvotes: 1

Jay Harris
Jay Harris

Reputation: 4271

with the ajax method being post this is invalid

xmlhttp.open("POST","ajax_test.php?q="+str,true);

instead it should be

xmlhttp.open("POST","ajax_test.php",true);
xmlhttp.send('q='+str);

you should not put the request string in the url unless you are using the GET method

to prevent the form from sending and going to the action page on click, you need to use preventDefault() function like so in your javascript and you should also initialize the var xmlhttp at the top of the function.

function showUser(str, e){
  e.preventDefault();
  var xmlhttp;

and in the html onclick="showUser(this.value, event)"

below is a short term fix to this solution but i strongly recommend you read more on javascript, html and php syntax as long as best practices

<script>
function showUser(form, e) {
 e.preventDefault();
 var xmlhttp;
 var submit = form.getElementsByClassName('submit')[0];
 var sent = form.getElementsByName('sent')[0].value || '';
 var id = form.getElementsByName('id')[0].value || '';


if (sent==""){
    document.getElementById("txtHint").innerHTML="";
    return;
}

if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
} else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function(e) {
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent='+sent+'&id='+id+'&'+submit.name+'='+submit.value);
}
</script>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
Enter the sentence: <input type="text" name="sent"><br>
<input type="submit" class="submit" name="insert" value="submit" >
</form>
<br>UPDATE <br>
 <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
    Enter the ID : <input type="text" name="id"><br>
    Enter the sentence: <input type="text" name="sent"><br>
</pre>
 <input type="submit" class="submit" value="submit" name="update">
</form> <br>
<div id="txtHint">
 <b>Person info will be listed here.</b>
 </div>

you don't need to add a closing slash to <br> br or <input> input tags unless you are using a strict markup like xhtml.

in your ajax_test.php document remove the <html> and <body> tags so it can be processed properly by ajax. don't worry its not going to affect how your page will render if the page was called without an ajax call, the browser automatically puts those tags in when page is reached unless its already present.

change ajax_test.php

<?php
// $q = $_POST["q"];
// you never process the $q var so i commented it
if (isset($_POST['insert']) && $_POST['insert'] !== '') {
echo "Operation: Insert","<br>";

$s = $_POST['sent'];
$flag = 0;

echo "Entered sentence : $s";

if (preg_match_all('/[^=]*=([^;@]*)/', 
    shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
    $matches)){ //Values stored in ma. 
    $x = (int) $matches[1][0]; //optionally cast to int
    $y = (int) $matches[1][1];
}

echo "<br>",
     "Positive count :$x",
     "<br>",
     "Negative count :$y",
     "<br>";

//---------------DB stuff --------------------
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql1 = "INSERT INTO table2 
         (id,sent,pcount,ncount,flag)
         VALUES
         ('".$_POST['id']."','".$_POST['sent']."',' $x ','$y','$flag')";
if (mysqli_query($con, $sql1)) {
   echo "1 record added";
} else {
   die('Error: ' . mysqli_error($con));
}


mysqli_close($con);
}

// -------------------------------UPDATE --------------------------
 if (isset($_POST['update']) && $_POST['update'] !== '') {
echo "Operation: update", "<br>";
 // you say update but you are actually inserting below

$s    = $_POST['sent'];
$flag = 1;

echo "Entered sentence : $s";

if (preg_match_all('/[^=]*=([^;@]*)/', 
    shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
    $matches)) //Values stored in ma.
{
    $x = (int) $matches[1][0]; //optionally cast to int
    $y = (int) $matches[1][1];
}

echo "<br>",
     "Positive count :$x",
     "<br>",
     "Negative count :$y",
     "<br>";

//---------------DB stuff --------------------
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql1 = "INSERT INTO table2 
         (id,sent,pcount,ncount,flag)
         VALUES
         ('".$_POST['id']."','".$_POST['sent']."',' $x ','$y','$flag')"; // error here again $_POST[id] should be $_POST['id'] with quotes
if (mysqli_query($con, $sql1)) {
  echo "1 record added";
} else { 
  die('Error: ' . mysqli_error($con));
}

 mysqli_close($con);
}
?>

there are a lot of errors here man, i tried to correcting them all but i can't test it and like i said you should read up on best practices because your code and syntax is pretty bad no to be harsh.

EDIT

further explanation on preventDefault:

we use this function to prevent the default form submission actions, which is sending the form by relocating the browser to the action page action="ajax_test.php" and setting parameters in the background or for GET methods in the url.

then after that you'll still want to send the form in and thats where ajax comes in; we use ajax to send forms asynchronously and without browser relocation. we can just load the page inside of the ajax call and process the response from the paged called inside of javascript xmlhttp.responseText.

Upvotes: 3

Related Questions