简体   繁体   中英

Showing ajax content in same page without page load

My ajax_form.php page is:

<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script>
function showUser(form, e) {
 e.preventDefault();
 var xmlhttp;
 var submit = form.getElementsByClassName('submit')[0];
 var sent = document.getElementsByName('sent')[0].value || '';
 var id = document.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">
Enter the sentence: <input type="text" name="sent"><br>
<input type="submit" class="submit" name="insert" value="submit" onsubmit="showUser(this, event)">
</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>
 </body>
</html>

and ajax_test.php is:

<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head> <body > 
<?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['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['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);
}
?></html > </body >

In form1 I have put function call on button click event, which works fine. But on button click it load the page and redirects to ajax_test.php. can we say it proper use of ajax?

In second form I have kept function call in form itself and coded as required in script. But on button click on action takes place. Is it wrong function call or any other mistake?

How can I show result without page load(refresh) in both cases?

The problem is with your sent parameter - it's looking for an input named "sent", which doesn't exist. And then, if it's not set, it's exiting the showUser function.

Here's the offending snippet (which I removed below):

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

In addition to that problem, you also had no close </head> or open <body> tags, which in themselves are not the problem, but a pretty major formatting issue. Also, always put a type on your <script> element. Finally, you should close <meta /> , <input /> and <br /> elements inline. Formatting your code consistently (sibling elements on their own lines, 4-space tabs for each heirarchical level) helps you find little formatting issues like the missing open body, etc.

That said, this works for me:

<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();
        var xmlhttp;
        var submit = form.getElementsByClassName('submit')[0];
        var sent = document.getElementsByName('sent')[0].value || '';
        var id = document.getElementsByName('id')[0].value || '';

        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>
</head>
<body>
    <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
        <label>Enter the sentence: <input type="text" name="sent"></label><br />
        <input type="submit" class="submit" name="insert" value="submit" onsubmit="showUser(this, event)" />
    </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:</label>
            <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>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM