繁体   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