简体   繁体   English

提交表单而不刷新(ajax,php)

[英]Submit form without refresh (ajax , php)

I am trying to submit a form without refreshing the page and I want an alert message to appear when the button id=fav in clicked. 我正在尝试提交表单而不刷新页面,并且当单击i​​d = fav按钮时,我希望显示一条警告消息。 this is the code but I don't know what i did wrong. 这是代码,但我不知道我做错了什么。 Should it be on button click or on form submit? 是单击按钮还是提交表单?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script>
$(document).ready(function(){
$("#f1").submit(function(){




// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "bookpage.php",
data: {'fav':'fav'} ,
cache: false,
success: function(response){
if(response.message){
alert(response.message);
}
}
});
}
return false;
});
});
    </script>
<form action="#read" method="post" id="f1">
  <div class="r1">
    <button class="down" name="download" title="Add to favorites">Download</button>
    <li><a class="full" href="full.php?id=<?php echo $id; ?>">Full page</a>
    </li>

    <button class="d-later" name="dlater">Download later</button>
    <button class="fav-button" type="submit" id="fav"></button>

  </div>
</form>

PHP 的PHP

   if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== true){

      $query = "DELETE FROM favorites WHERE bid='$ii' AND email='$u'";
       $result = mysql_query($query);
        if(! $result ) {

             die('Could not delete data: ' . mysql_error());

    } $response['message'] = 'My message';
echo json_encode($response);

    }else if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== false){


          $query = "INSERT INTO favorites (email,book, bid) VALUES('$u','$bname','$ii')";
       $result = mysql_query($query);
        if(! $result ) {

             die('Could not enter data: ' . mysql_error());
    }
   $response['message'] = 'My message';
echo json_encode($response);
}

  function fav_exists($u , $ii){


    $query = "SELECT id FROM favorites WHERE email='$u' AND bid='$ii'";
    $result = mysql_query($query);
    $count = mysql_num_rows($result); 


    if($count >= 1) {
        return true;
    } else {
        return false;
    }

}

I think you are passing empty data, see example below how to pass some data; 我认为您正在传递空数据,请参见下面的示例如何传递一些数据。 If you want to run ajax+php you need to pass some data 如果要运行ajax + php,则需要传递一些数据

<?php if(isset($_POST['action'] && $_POST['action'] == 'my_action') {
// do stuff;
// to send json response use json_encode;
$response['message'] = 'My message';
echo json_encode($response);
}


$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : 'my_action' },
success: function(response){
if(response.message){
alert(response.message);
}
}
});

Also i highly recommend using PHP PDO to make SQL queries - http://php.net/manual/en/book.pdo.php 我也强烈建议使用PHP PDO进行SQL查询-http: //php.net/manual/zh/book.pdo.php

upd: 更新:

$('#fav').click(function(){
    do_ajax_request('you can pass different type of acitons as param');
});
function do_ajax_request(action) {
$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : action },
success: function(response){
  if(response.message){
   alert(response.message);
  }
 }
});
}

And at your php file you can switch or if/else different functions depending on your action ; 并且在您的php文件中,您可以根据自己的action进行switch或不同if/else不同的功能;

<?php if(isset($_POST['action'])) {
  $action = $_POST['action'];
  switch($action) {
    case 'favorites':
    $msg = 'favorites action called';
    breake;
    case 'not fav':
    $msg = 'not fav called';
    breake;
    default: 
    $msg = 'Nothing passed';
    breake;
  }
  $Response['msg'] = $msg;
  echo json_encode($Response);
}

This is what i use for the same task. 这就是我用于同一任务的内容。

HTML 的HTML

<form action="" method="post">
name:<input type="text" name="user" /> <br/>
<p><input type="submit" /></p>
</form>

JS JS

$(function() {
    $('form').submit(function(e) {
        e.preventDefault(); // Stop normal submission
        data = $('form').serializeArray();
        alert(JSON.stringify(data));
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: 'inc/update.php',
            data: {
                json: JSON.stringify(data)
            },
            dataType: 'json'
            }
        });  
    });
    return false;
});

PHP 的PHP

$str_json = file_get_contents('php://input');
$str_json = urldecode($str_json);
$str_json = str_replace('json=[', '', $str_json);
$str_json = str_replace(']', '', $str_json);
$arr_json = json_decode($str_json, true);
$name = $arr_json['name'];

$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password);
$update = $pdo->prepare("UPDATE user SET name='".$name."' WHERE id='3';");
$update->execute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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