How does Ajax work with PHP?

Deadly 提交于 2019-12-02 00:38:01

You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.

Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.

Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:

echo (check($_POST) ? 'true' : 'false');

You can now check the content in JavaScript.

Basically ajax is a hand-shaking routine with your server.

Ajax:

$.post('yoursite.com/pagewithfunction.php',
    {postkey1:postvalue1, postkey2:postvalue2...},
    function (response) {
       // response is the data echo'd by your server
    }, 'json'
);

pagewithfunction:

yourFunction(){
   $var1 = $_POST['postkey1'];....
   $result = dosomething($var1..);
   echo json_encode($result); // this is passed into your function(response) of ajax call
}

So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.

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