2014-03-29 136 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"}