簡體   English   中英

對php對象的ajax請求

[英]ajax request to php object

編輯:我解決了! (問題3)
現在我只得到json對象而不再得到HTML
我將在下面的單獨答案中發布我的解決方案,因此更容易理解我的工作。

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。

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

在控制器的構造函數中可以這樣: $this->renderer->setTemplate($this->pageVal);

我認為這就是為什么我要獲取整個html代碼的原因:這可能嗎?

3.)
因此,另一個問題是:我可以更改ajax請求,以便僅獲得以下結果:

$dbfunctions->saveUser($entryDatas)

從控制器?

在您的控制器中;

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);
        }
    }
});

我在單獨的答案中發布了我的解決方案-希望這對其他遇到相同問題的人有所幫助!

解決方案是檢查它是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"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM