Home >Backend Development >PHP Tutorial >How to use AJAX in PHP to return login success information!
That is to say, when I click the button to submit the form, I use ajax to send a request, and then how do I return the login success or login failure information to the front-end page for display? The whole process is non-refreshed!! Can anyone give me some ideas? ! ! !
That is to say, when I click the button to submit the form, I use ajax to send a request, and then how do I return the login success or login failure information to the front-end page for display? The whole process is non-refreshed!! Can anyone give me some ideas? ! ! !
The following is the complete reference code. index.php is the login page, and ajax.php is the page that handles ajax non-refresh requests.
index.php
<code><!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>登录</title> <script type="text/javascript" src="http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script> </head> <body> 帐号:<input type="text" id="account" /> <br><br> 密码:<input type="password" id="password" /> <br /> <input type="button" value="登录" id="btnlogin" /> <script type="text/javascript"> $(function(){ $("#btnlogin").click(function(){ $.ajax({ type:"post", url:"ajax.php", data:{account:$("#account").val(),password:$("#password").val()}, dataType:"json", success:function(data){ if(data.type==1){ alert("登录成功"); }else{ alert("登录失败"); } }, error:function(){ alert("请求异常"); } }); }); }); </script> </body> </html></code>
ajax.php
<code><?php header("Content-Type:text/html; charset=utf-8"); $account = $_POST['account']; $password = $_POST['password']; $result = array(); if ($account != '' && $password != '') { //$row = $db->query("SELECT * FROM account where user = '".$account."' and password = '".$password."'"); $row = true;//这里去查数据库,假设这里返回true if($row){ $result['type'] = 1; $result['msg'] = '登录成功'; }else{ $result['type'] = 0; $result['msg'] = '用户名或密码不正确'; } } else { $result['type'] = 0; $result['msg'] = '参数传输不正确'; } echo json_encode($result); ?></code>
Just write directly into the response. After ajax receives the data, modify the page in the callback function. How to write must be in the same format as the front end, usually writing json data into the response
Generally speaking, when you submit information to the backend php through ajax, after the php judgment processing is completed, a json will be returned, and then the success callback function of the front end can accept the judgment. Now it is difficult to provide code on mobile phones
<code>header('content-type:application/json; charset=utf-8'); exit(json_encode($yourdata));</code>