简体   繁体   English

对php对象的ajax请求

[英]ajax request to php object

EDIT: I SOLVED IT! 编辑:我解决了! (QUESTION 3) (问题3)
now i only get the json object nad not the HTML anymore 现在我只得到json对象而不再得到HTML
I'll post my solution in a separate answer below, so its easier to understand what i did. 我将在下面的单独答案中发布我的解决方案,因此更容易理解我的工作。

1.) Basic question: 1.)基本问题:
I'd like to know if it is possible to get the return value of a method in a php object via jquery ajax request. 我想知道是否有可能通过jquery ajax请求获取php对象中方法的返回值。

In other words: I try to get the return value of something like this: 换句话说:我尝试获取类似以下内容的返回值:

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

2.) Here is what i'm doing in my project: 2.)这是我在项目中正在做的事情:
Its very simple - i just wanna check if an E-Mail already exists in my database and i do this with this saveUser() method of my $dbfunctions object: 非常简单-我只想检查数据库中是否已存在电子邮件,并使用$ dbfunctions对象的saveUser()方法执行此操作:

$dbfunctions: $ 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'] . "');"
              // (...)
      );      
    }
  }
}

$controller $控制器

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

    }
    }    
  }

Thanks a lot. 非常感谢。

If the Basic question "1.)" is "no", you can ignore "2.)" 如果基本问题“ 1.)”为“否”,则可以忽略“ 2.)”

EDIT: +++ CHANGED CODE, GETTING STRANGE RESPONSE +++ 编辑:+++更改代码,获得奇怪的响应+++

Hello again, thanks for your help - i changed code as you suggested using json_encode(see changes above near the "+++") 再次您好,感谢您的帮助-我按照您建议的方式使用json_encode更改了代码(请参见上面“ +++”附近的更改)

And added following JS-Code: 并添加了以下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);
        }
      }
    });

I left the alerts inside to check the response. 我将警报留在内部以检查响应。 The response.message is undefined. response.message未定义。

But i didn't trust them so i checked the "response" only. 但是我不信任他们,所以我只检查了“响应”。 And it was good and bad too: 它也有好有坏:

I got the deserved message at the beginning of the response, but after it, i get lots of HTML-Code: 在响应的开头我得到了应有的消息,但是在此之后,我得到了许多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">

(.....) (.....)

and lots more. 还有更多。 I get the entire page HTML of my index page. 我得到索引页面的整个页面HTML。

Maybe it has something to do with the small templatesystem i'm working with? 也许与我正在使用的小型模板系统有关? It is controlled by "page" parameter and a renderer object. 它由“页面”参数和渲染器对象控制。

ike this in the constructor of the controller: $this->renderer->setTemplate($this->pageVal); 在控制器的构造函数中可以这样: $this->renderer->setTemplate($this->pageVal);

I think this is why im getting the entire html-code: is this possible? 我认为这就是为什么我要获取整个html代码的原因:这可能吗?

3.) 3.)
So another question is: Can i change the ajax request so i get only the result of 因此,另一个问题是:我可以更改ajax请求,以便仅获得以下结果:

$dbfunctions->saveUser($entryDatas)

from the controller? 从控制器?

In your controller; 在您的控制器中;

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

echo json_encode($res);

And in js, 在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);
        }
    }
});

I'm posting my solution in i seperate answer - i hope this will help others with the same problem! 我在单独的答案中发布了我的解决方案-希望这对其他遇到相同问题的人有所帮助!

The Solution is to check if it is an ajax request or a "normal" request. 解决方案是检查它是ajax请求还是“正常”请求。 And if it's an ajax request, deaktivate the page rendering call in the constructor. 如果这是一个ajax请求,请在构造函数中取消页面渲染调用。

Thank you for your help again! 再次感谢您的帮助! Have a nice day! 祝你今天愉快!

If you leave comments to this first solution i'll read it and update the answer of course if needed. 如果您对第一个解决方案有任何评论,我会阅读并在需要时更新答案。

Here's the code: 这是代码:


HTML REGISTER FORM HTML注册表格

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



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



controller 控制者

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



THE RESPONSE should look like this 响应应如下所示

//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