简体   繁体   中英

show ajax call result in div on same page

I have tried some code to get the results on same page.But it is not working. It displays me the result on result.php file. Stuck with ot. I am totally new with AJAX. Any suggestions please.

AJAX

  $("document").ready(function(){
  $(".but").submit(function(){
  event.preventDefault();
  var $form = $( this ),
  var myData=$form.find( 'input[name="query"]' ).val(),
  $.ajax({
   url: 'result.php',
   data: myData,
   type: 'post',
    dataType: "html",
   success: function(result){
   $('.coupons').text(result)
    } }); }); });

result.php

$keyword = mysqli_real_escape_string($con,$_GET['query']); // always escape
 $keys = explode(" ", $keyword);
 $sql="SELECT  c.* , sc.* , sm.* ,ca.* from store_category sc INNER JOIN store_manufacture sm ON sm.sm_id=sc.store_id INNER JOIN categories ca ON ca.cat_id=sc.cat_id INNER JOIN coupons c on c.c_sc_id=sc.sc_id WHERE c.c_name LIKE '%$keyword%' OR sm.sm_brand_name LIKE '%$keyword%' OR ca.cat_name LIKE '%$keyword%' OR c.c_description LIKE '%$keyword%'";

foreach ($keys as $k) {

    $sql.="OR c.c_name LIKE '%$k%' OR sm.sm_brand_name LIKE '%$k%' OR ca.cat_name LIKE '%$k%' OR c.c_description LIKE '%$k%'";
}

$result = mysqli_query($con, $sql);
$count=mysqli_num_rows($result);
if($count!=0) {
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        echo $row['c_name'];

        echo $row ['c_description'];
        echo $row['sm_brand_name'];
        echo "<br>";
    }
}
else
{
    echo "no result";
}

Variable event in submit(function(){ is not defined.

Provide it as function's argument:

$("document").ready(function(){
    $(".but").submit(function(event){  // here
        event.preventDefault();
        var $form = $( this ),
        var myData=$form.find( 'input[name="query"]' ).val(),
        $.ajax({
            url: 'result.php',
            data: myData,
            type: 'post',
            dataType: "html",
            success: function(result){
                $('.coupons').text(result)
            } 
        });
    }); 
});

Besides the missing function event attribute, you should be using key value pairs for your myData var.

var myData = {
  query: $form.find( 'input[name="query"]' ).val()
}

Then in result php to get the value:

echo $_REQUEST['query'];

PS : You should learn to use PDO as well as mysqli.

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