Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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

An example is:

functionupdateDB(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'") ordie(mysql_error());

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

<script>functionlinkme(_this) {
        window.event.preventDefault();
        //do all the code with ajaxwindow.location = _this.href;
    }
</script><ahref="http://google.com"onclick="linkme(this)">Clicky</a>

Solution 2:

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/

Post a Comment for "Javascript/ajax To Php Page With Either Post Or Get"