简体   繁体   中英

ajax request to php object

EDIT: I SOLVED IT! (QUESTION 3)
now i only get the json object nad not the HTML anymore
I'll post my solution in a separate answer below, so its easier to understand what i did.

1.) Basic question:
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.

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

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.)"

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 "+++")

And added following JS-Code:

 $.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.

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:

{"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.

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

I think this is why im getting the entire html-code: is this possible?

3.)
So another question is: Can i change the ajax request so i get only the result of

$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,

$.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. And if it's an ajax request, deaktivate the page rendering call in the constructor.

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

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



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"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM