2014-03-29 135 views
0

編輯:我解決了它! (問題3)
現在我只得到JSON對象NAD不是HTML了
我會後我的下面一個單獨的答案的解決方案,所以它更容易理解我的所作所爲。ajax請求到php對象

1)基本問題:
我想知道是否有可能獲得通過jQuery Ajax請求PHP對象的方法的返回值。

換句話說: 我試圖得到的是這樣的返回值:

$dbfunctions = new dbfunctions(); 
$dbfunctions->saveUser(); //<--- the return value of saveUser() is what i need, but in a result of an ajax request 

2)這是我在我的項目正在做:
它非常簡單 - 我如果電子郵件已經存在於我的數據庫只是想檢查,我想到我$ dbfunctions這saveUser()方法對象:

$ dbfunctions:

class dbfunctions {  
//(...)  
    public function saveUser(array $datas) { 

    //(...) preparing some variables for mysql query 

    $sqlMail = $this->mysqli->query("SELECT `email` from `myTable` WHERE `email` = '" . $this->mysqli->escape_string($datas['email']) . "';"); 

    if ($sqlMail->num_rows) { //<--- check if mail exists in DB 


     return false; //<-- this is what i need in the ajax result 


    } else { 
     $this->mysqli->query("INSERT INTO `TABLE` (`name`, `street`, `email`) 
      VALUES('" . 
       $this->mysqli->escape_string($datas['name']) . "','" . 
       $this->mysqli->escape_string($datas['street']) . "','" . 
       $this->mysqli->escape_string($datas['email'] . "');" 
       // (...) 
    );  
    } 
    } 
} 

$控制器

class controller { 

    //constructor and preparing some variables (...) 

    public function dbStuff() { 
    if (isset($_GET['action']) && $_GET['action'] != "") { 

     require_once 'dbfunctions.php'; 
     $dbfunctions = new dbfunctions(); 

     //Save new User 
     if ($_GET['action'] == 'newUser') { 
     $entryDatas = array(
      'first_name' => trim($_POST['name']),    
      'street' => trim($_POST['street']),    
      'email' => trim($_POST['email']), 
      //(...)    
    ); 


     //THIS IS WHAT I DID WITHOUT AJAX 
     /*if ($dbfunctions->saveUser($entryDatas) === false) { 
     header("Location: index.php?page=registerform&mail=exists"); 
     //in the registerform page a message is displayed via echo 
     // "your mail already exists" 
     } else { 
     //everything is cool 
     header("Location: index.php?page=confirmation?var=xyz); 
     }*/ 

     /*+++ AND I CHANGED IT TO +++*/ 

     if ($dbfunctions->saveUser($entryDatas) === false) {   
     $res = array(
      "result" => false, 
      "message" => "Email already exists" 
    ); 
     echo json_encode($res); 

     } else { 
     $code = $dbfunctions->getOptinHash(); 
     $res = array(
      "result" => true, 
      "message" => "Success" 
    ); 
     echo json_encode($res);   

    } 
    }  
    } 

非常感謝。

如果基本的問題: 「1)」 是 「沒有」,你可以忽略 「2)」

編輯: +++改變的代碼,遇到奇怪的反應+++

你好再次, 感謝您的幫助 - 我改變了代碼,如你所說使用json_encode(見附近的「+++」上述變化)

並補充以下JS-代碼:

$.ajax({ 
     url: "index.php?action=newUser", 
     type: "POST", 
     data: $(registerform).serialize(), 
     success: function(response) { 
     if (response.result === true) { 
      alert("success: " + response.message); 
      // window.location = "..../index.php?page=confirmation?var=your_email" 
     } else { 
      alert("fail: " + response.message); 
     } 
     } 
    }); 

我在裏面留下警報來檢查迴應。 response.message是未定義的。

但我不信任他們,所以我只檢查了「回覆」。 它是好的和壞的太:

我得到了應有的消息在響應的開始,但之後,我得到很多的HTML代碼:

{"result":false,"message":"Email already exists"} 
<!DOCTYPE html> 
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" /> 
    <title>some title</title>  
    <meta name="language" content="de"> 

(..... )

以及更多。 我得到了我的索引頁面的整個頁面HTML。

也許它與我正在使用的小模板系統有關? 它由「頁面」參數和渲染器對象控制。

IKE在此控制器的構造函數:$this->renderer->setTemplate($this->pageVal);

我想這就是爲什麼即時得到完整的HTML代碼:這可能嗎?

3)
那麼另一個問題是:
我可以改變Ajax請求,所以我得到的

$dbfunctions->saveUser($entryDatas) 

從控制器只有結果?

+0

是使用JSON編碼 – Anni

+0

你可以在你的PHP文件中使用json_encode得到確切的對象。然後解析它並像使用正常的jquery/javascript對象一樣使用它! –

+0

這裏的東西是如何通過ajax請求調用控制器的方法。如果你已經考慮過了,那麼你可以執行'$ dbfunctions = new dbfunctions(); $ savedUser = $ dbfunctions-> saveUser();返回json_encode($ savedUser);' – ponciste

回答

0

在您的控制器中;

if ($dbfunctions->saveUser($entryDatas) === false) { 
    $res = array(
     "result" => false, 
     "message" => "Email already exists" 
    ); 
} else { 
    $res = array(
     "result" => true, 
     "message" => "Success" 
    ); 
} 

echo json_encode($res); 

而且在JS,

$.ajax({ 
    url: "your_url", 
    type: "POST", 
    data: "action=newUser&name=your_name&street=your_street&email=your_email", 
    success: function(response) { 
     if(response.result == true) { 
      window.location = "..../index.php?page=confirmation?var=your_email" 
     } else { 
      alert(response.message); 
     } 
    } 
}); 
+0

謝謝Hüseyin爲您詳細解答 - 我會測試它。週末愉快。 –

+0

嘿,當我添加dataType:'json'時,在你的ajax請求的選項中它工作正常 - 謝謝! –

0

我張貼我的解決方案在我單獨回答 - 我希望這將幫助其他有同樣的問題!

解決方案是檢查它是否是ajax請求或「正常」請求。 如果它是ajax請求,則在構造函數中取消激活頁面呈現調用。

再次感謝您的幫助! 祝您有美好的一天!

如果您對第一個解決方案留下意見,我會閱讀並在需要時更新答案。

下面的代碼:


HTML登記表

//action is index.php?action=newUser 
<form name="registerform" id="registerform" method="post" action="index.php?action=newUser" accept-charset="UTF-8"> 
//(...) 



JavaScript的:

$(document).ready(function() { 
//(...) 
$('#registerform').on('submit', function(e) { 
    e.preventDefault(); 
    var formAction = $(this).attr('action'); 
    //console.log('Sending request to ' + formAction + ' with data: '+$(this).serialize()); 
    validateRegisterForm(); 
    }); 
} 

function validateRegisterForm() { 
//doing some form validation(...) 


//CHECK IF E-MAIL EXISTS 
    $.ajax({ 
    url: $(registerform).attr('action') + "&request=ajax", //<--this is the "check if request is an ajax request" 
    type: "POST", 
    data: $(registerform).serialize(), 
    dataType: 'json', //<-- don't forget this or u will get undefined 
    success: function(response) { 
     if (response.result === true) { 
     console.log("response result: " + response.result); 
     // window.location = "..../index.php?page=confirmation?var=your_email" 
     } else { 
     console.log("response result: " + response.result);  
     } 
    } 
    }); 
} 



控制器

class controller { 
    //(...) some variables 
    public function __construct() { 
    //(...) initializing the rendering stuff here 

    //check if it's an ajax request 
    if($this->ajaxRequest == false){ 
     $this->render->renderTemplate($page); 
    } 
    } 

//(...) 


    if ($dbfunctions->saveUser($entryDatas) === false) { 
     $res = array(
      "result" => false, 
      "mail" => "Email already exists" 
    ); 
     echo json_encode($res);   
    } else { 
     $res = array(
      "result" => true, 
      "message" => "Success" 
    ); 
     echo json_encode($res);   
    }  
} 



的響應應該是這樣的

//E-Mail is available 
{"result":true,"message":"Success"} 

//E-Mail already exists 
{"result":false,"mail":"Email already exists"}