![](/img/trans.png)
[英]Processing a PHP request from an ajax-driven Fancybox element on the same page
[英]Ajax/JSON request to php processing page
我正在為我的大學學位使用html5,ajax,JSON和php創建一個手機應用程序。 此應用程序必須與mysql數據庫通信,因此ajax Json用於與php文件通信,然后php文件將查詢處理到數據庫。 然后使用phonegap雲服務打包。
登錄頁面使用表單來獲取用戶名和密碼,然后jQuery和JSON通過登錄頁面上的腳本將其傳遞給login.php。 我可以在一定程度上獲得jQueryworking,但是一旦我在php文件上執行SQL查詢,登錄似乎就會掛起。 我已經通過手動將輸入變量放在php中並在瀏覽器中運行頁面來測試php進程很多次。 您可以在移動應用登錄時看到登錄信息 。
我目前正在使用$ .getJSON從輸入表單發送變量,但更喜歡使用一個帖子,但不能完全解決這個問題。 也不像使用表單動作帖子,然后我可以使用回聲輸出,以確保PHP正在做它的工作我不能找到如何允許我使用類似的方式來檢查我的PHP進程因為使用jquery / JSON,任何指導將不勝感激。
以下是我的腳本,我一直試圖讓這個工作3天現在,即使我已經嘗試了很多不同的腳本在許多論壇上發現,但似乎無法讓它工作,任何幫助將不勝感激
jquery / JSON腳本************************
$(document).ready(function() {
$("#submit").click(function() {
if($("#childs_name").val()=="" || $("#password").val()=="") {
$("#add_err").html("Please enter childsname and password");
return false;
}else{
$("#add_err").html('<img src="images/ajax-loader.gif" width="16" height="16" alt=""/>');
var childsname=$("#childs_name").val();
var password=$("#password").val();
$.getJSON("includes/login.php",{username:childsname,password:password},function(json) {
//Parse JSON data if json.response.error = 1 then login successfull
if(json.response.error == "1")
{
$("#add_err").html( "Welcome "+childsname+"");
//login successfull, write code to Show next page here
window.location= "menu.html";
}else
if(json.response.error == "2")
{
$("#add_err").html( "Details do not exsist in Database. Please contact the School");
}
});//get json
}
});//submit click
});//doc ready
PHP ********************************
//include_once 'db_connect.php';
if(!isset($_GET['submit'])) {
//check if childsname is empty
if(empty($_GET['childsname'])) {
echo '{"responce":{"error": "1"}}';
}else{
$childs_name = $_GET['childsname'];
echo '{"responce":{"error": "0"}}';
}//end of chidsname
//check if password is empty
if(empty($_GET['password'])) {
echo '{"responce":{"error": "1"}}';
}else{
$password = $_GET['password'];
echo '{"responce":{"error": "0"}}';
}//end of password
//query database
$query = "SELECT * FROM app Where child_name = '$childs_name'";
$results = mysqli_query($mysqli, $query);
// Loop through results
// if($result->num_rows >= 1){
// $row = $result->fetch_array(MYSQLI_ASSOC);
// if ($row['childs_name'] = '$childs_name'){
//
while ($row = mysqli_fetch_array($results, MYSQLI_BOTH)){
if($_GET['childsname'] == $row['child_name']) {
echo '{"responce":{"error": "1"}}';
// header("Location: ../menu.html");
}else{
echo '{"responce":{"error": "2"}}';
}
}
//**************************************************************submit
echo '{"response":{"error": "1"}}';
}
else
{
echo '{"response":{"error": "0"}}';
}
我的表格HTML *******************************
<body class="body">
<div id="logo"></div>
<div class="loginForm">
<form id="login" name="login" method="post" action="includes/login.php">
<input name="childs_name" type="text" id="childs_name" form="login" placeholder="Childs Name">
<input name="password" type="password" id="password" form="login" placeholder="Password">
<input name="submit" class="submit" type="button" id="submit" formaction=""value="Submit">
<input name="reset" type="reset" id="reset" form="login" value="Reset">
<div id ="add_err" class="add_err"></div>
</form>
</div>
<div class="l-a"></div>
<div class="tagLine">Little minds with big ideas</div>
</body><!--body-->
</html>
jQuery和JSON對我來說是新的,所以我希望我的代碼是可疑的,我錯過了一些簡單的東西,我也希望我已經提供了足夠的信息來提供幫助,以防萬一有些人認為我已經把它放了那么多代碼我只想提供我認為需要的信息
首先更新你的php文件:1。取消注釋
//include_once 'db_connect.php';
在此行之后添加以下內容:
header('Content-Type: application/json'); //this one will tell the server to send a json object back to client (by default it sends text/html)
不要使用echo'thing'; 而是將結果輸入$ result變量,如下所示:
$result = array ( 'response' => array('status'=>'error', 'message' => 'password is missing')); //this is just an example for the missing password line
在腳本結束時使用此:
echo json_encode($result);
exit();
PS用'響應'替換你的php腳本中的'responce'。
這就是你的PHP文件的外觀:
<?php
include_once 'db_connect.php';
//Start the session if is not started it
//You need it to store here the user's name when he successfully logs in
if (!isset(session_id())) {
session_start();
}
header("Content-Type: application/json"); //this will tell the browser to send a json object back to client not text/html (as default)
// This function will convert your variable (array) into a JSON object
function result($var){
echo json_encode($var);
exit();
}
if(!isset($_GET['submit'])) {
//check if childsname is empty
if(empty($_GET['childsname'])) {
$response = array('result'=>'fail', 'message' => 'missing childsname');
result($response);
}else{
//Always escape your variables before using them in a database
//I assumed $mysqli is your database connector
$childs_name = mysqli_real_escape_string($mysqli, $_GET['childsname']);
}
//check if password is empty
if(empty($_GET['password'])) {
$response = array('result'=>'fail', 'message' => 'missing password');
result($response);
}else{
//Always escape your variables before using them in a database
$password = mysqli_real_escape_string($mysqli, $_GET['password']);
}
// Query database
$query = "SELECT * FROM app WHERE `child_name` = '$childs_name'"; // You also need to add: AND `password_column_name` = '$password' LIMIT 1
$results = mysqli_query($mysqli, $query);
// Check if SQL query had erors
if (!$results){
$response = array('result'=>'fail', 'message' => 'sql error: ' . mysqli_error($mysqli));
result($response);
}
// If query was successfull and there are rows do this:
if (mysqli_num_rows($results)>0){
$_SESSION['username'] = $childs_name;
//You may use this variable to check if the user is logged in like this:
/*
if (isset($_SESSION['username'])) {
// user is logged in
// do something here
}
*/
$response = array('result'=>'success', 'message' => 'user is authenticated'));
result($response);
} else {
$response = array('result'=>'fail', 'message' => 'user authentication failed');
result($response);
}
?>
在JavaScript代碼中將getJSON部分替換為此部分
$.getJSON("includes/login.php",{username:childsname,password:password},function(json) {
if(json.result === "success") {
$("#add_err").html( "Welcome "+childsname+"!");
//you should redirect to a php page, not a html one AND on that page you should have a session started ( session_start(); )
// and there you should check if :
/*
if (isset($_SESSION['username'])) {
// user is logged in
// do something here
} else {
//redirect the user back on this page(login_page)
}
*/
//wait two seconds before redirect, otherwise you say 'Welcome kiddo' for nothing because no one will ever see it :)
setTimeout(function(){
window.location= "menu.html";
},2000);
}else{
$("#add_err").html(json.message);
}
});
稍后更新解釋php中的$ response數組:
//$response here is an PHP array with the following structure
$response = array('result'=>'fail',
'message' => 'missing password');
你打電話的時候
結果($響應);
此數組在JSON對象中轉換,具有以下結構:
{
"response":"fail",
"message": "missing password"
}
因為result()函數中的最后一條指令是exit(); 腳本執行結束,結果在getJSON函數中傳遞回客戶端。
不確定它是否可以作為答案,但我想給你一些提示,評論可能太長。
1)使用post而不是get。 它非常類似,在文檔中有很好的例子: https : //api.jquery.com/jquery.post/
示例:發布到test.php頁面並獲取以json格式返回的內容(“John”,“time”=>“2pm”)); ?>)。
$.post( "test.php", { func: "getNameAndTime" }, function( data ) {
console.log( data.name ); // John
console.log( data.time ); // 2pm
}, "json");
2)如何調試? 如果你無法直接檢查服務器響應,你可以在php端放一些文件記錄來獲取那里發生的事情。
3)在你的PHP代碼,你回聲“responçE”而不是“響應”
這可能不是您問題的直接解決方案,但我希望它會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.