Updating database with jQuery AJAX works only one

2019-07-15 11:54发布

问题:

I'm trying to update a database by using jQuery. The function works just fine, but only once. I have to refresh the page and clear the cache if I want to update the database again. I'm using MODX Revolution, I'm not sure if that has anything to do with this problem. Here is the code:

<html>
  <head>
    <script language="javascript" type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
  </head>
  <body>

<script>
$(document).ready(function(){
 $('#paina').submit( function updateTitle() {
        var mail = $("#output").val();
        $.ajax({  
            type: "POST",  
            url: "gettable.php",  
            data: "mail="+ mail,  
            cache: false,
            success: function(data){
                alert(mail);  
            }  
        });
        return false;
    });
});

  </script>

<form id="paina" name="test" action="javascript:updateTitle()" method="post">
<input type="text" id="output">
<input type="Submit" value="Update">
</form>   
  </body>
</html>

PHP:

<?php
$mail=$_POST["mail"];

$mysqli = mysqli_connect("url", "user", "password", "database_name");

mysqli_query($mysqli, "UPDATE modx_site_content SET pagetitle='$mail' WHERE longtitle='jee'");

echo "Updated!";

$mysqli->close();

回答1:

From the jQuery docs:

Note: Setting cache to false will only work correctly with HEAD and GET requests

Ugly fix: append a random parameter to the query string:

$.ajax({  
            type: "POST",  
            url: "gettable.php",  
            data: "mail="+ mail + "&timestamp=" + new Date(),  // Will append the current date in milliseconds since January 1, 1970 (correct me if I'm wrong).
            cache: false,
            success: function(data){
                alert(mail);  
            }  
        });


回答2:

Try changing the ajax to be to help debug, I have also added an object to data and set a sync to false to ensure the ajax finishes execution before the return

$(document).ready(function(){
  $('#paina').submit( function() {
     $.ajax({  
        type: "POST",  
        url: "gettable.php",  
        data: {mail: mail},  
        cache: false,
        async: false,
        success: function(data){
            alert(mail);  
        },
        error function(){
           alert("Failed");

        } 
     });
  });
});

You don't need the action on your form either as jQuery is handling it

<form id="paina" name="test" action="" method="post">


回答3:

Thanks for the tips. I found the solution, MODX Revolution uses xPDO Database Connections so I had to change PHP code to this:

$mail=$_POST["mail"];

$dsn = 'mysql:host=localhost;dbname=databasename;port=3306;charset=utf-8';
$xpdo = new xPDO($dsn,'user','password');
$results = $xpdo->query("UPDATE modx_site_content SET pagetitle='$mail' WHERE longtitle='jee'");