简体   繁体   中英

Javascript/AJAX to PHP Page with either POST or GET

I have a javascript function with 2 values. I want to post those values to a PHP page where I can update a mySQL database with it. Here is what I have so far, which doesn't work.

function updateDB(page1,page2)
{
alert("TEST");

$.ajax({
type: 'POST',
url: update.php,
page1: page1,
page2: page2
});
}

Update.php code

 <?php include "connect.php"; 
 $page1 = $_POST['page1'];
 $page2 = $_POST['page2'];

 mysql_query("UPDATE `pages` SET `page1` = '$page1'");

 ?>

When I run the function, I get a POP up but the database does not update.

Any suggestions? I don't mind using GET or POST.

Thanks in advance,

The correct way to send data via POST with jQuery is with the data property.

An example is:

function updateDB(page1,page2)
{
    $.ajax({
        type: 'POST',
        url: 'update.php',
        data: {
            page1: page1,
            page2: page2
        },
        success: function() {
            window.location = "http://google.com";
        },
        cache: false
    });
}

I have also added alert on success, as well as disabling cache. Even though this is post, IE will cache post requests to pages that have been requested with get.

I would highly recommend using MySQLi, or at the very least escaping the query:

include "connect.php"; 
$page1 = mysql_real_escape_string($_POST['page1']);
$page2 = mysql_real_escape_string($_POST['page2']);

mysql_query("UPDATE `pages` SET `page1` = '$page1'") or die(mysql_error());

If you want to change the page afterwards from the href simply do this:

<script>
    function linkme(_this) {
        window.event.preventDefault();
        //do all the code with ajax
        window.location = _this.href;
    }
</script>


<a href="http://google.com" onclick="linkme(this)">Clicky</a>

You have forgot '' at your strings(update.php and page1/2), which your browser console should wine about: "Uncaught ReferenceError: update is not defined". See more about debugging here: https://developers.google.com/chrome-developer-tools/docs/javascript-debugging

Also you need to put your data in an data object.

$.ajax({
type: 'POST',
url: 'update.php',
data: {
  page1: page1,
  page2: page2
}
}).done(function(data){
  alert('got:' + data);
});

Se more at jquery documentation: http://api.jquery.com/jQuery.ajax/

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