Javascript/AJAX to PHP Page with either POST or GET

坚强是说给别人听的谎言 提交于 2019-12-12 02:33:43

问题


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,


回答1:


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>



回答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/



来源:https://stackoverflow.com/questions/17799795/javascript-ajax-to-php-page-with-either-post-or-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!