-1

I'm new to php so please bare with me. I have an ajax function that creates a post request to send data to server side php and echo it and my code should work fine. The problem is the php echo is proccessing before the create() function is ran so an error that the variables are not found is only displayed. Is there a way in php to make the echo proccess wait untill the ajax function is ran. Any help is appreciated. Thanks in advace.

function create() {
  $.ajax({
    url: "test.php",
    type: "post",
    dataType: 'json',
    data: {
      registration: "success",
      name: "xyz",
      email: "abc@gmail.com"
    },
    success: function(result) {
      console.log(result.abc);
    }
  });
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<button onclick="create()">click me</button>

<?php 
  $registration = $_POST['registration'];
  $name= $_POST['name'];
  $email= $_POST['email'];

  if ($registration == "success"){
    echo json_encode(array("abc"=>'successfuly registered'));
  }
?>
UPDATE: Checked if there is a POST request inorder to proccess the script but no echo.

function create() {
  $.ajax({
    url: "test.php", //the page containing php script
    type: "post", //request type,
    dataType: 'json',
    data: {
      registration: "success",
      name: "xyz",
      email: "abc@gmail.com"
    },
    success: function(result) {
      console.log(result.abc);
    }
  });
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<button onclick="create()"> Click me</button>

<? php 
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $registration = $_POST['registration'];
    $name= $_POST['name'];
    $email= $_POST['email'];
    
    if ($registration == "success"){
    // some action goes here under php
       echo json_encode(array("abc"=>'successfuly registered'));
    }  
  }
?>
seriously
  • 1,202
  • 5
  • 23
  • Does this answer your question? [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – CBroe Jul 28 '21 at 06:07
  • did you even read the question @CBroe – seriously Jul 28 '21 at 06:08
  • I know the differene bettwen server side and client side. What im trying to ask is if there is a way to wait until an ajax call is completed @CBroe – seriously Jul 28 '21 at 06:26
  • 1
    By asking how to “wait”, you are clearly showing that you have _not_ understood what it actually means yet. There _is_ nothing to “wait” for, your AJAX request is a _second_ request, completely independent from the first one, that loaded the page. So if you want to get a different _response_ now than the first time - then you have to implement logic in your script, that differentiates between the two cases, and handles them differently. For example checking if the request method was POST to begin with is an option, or checking for specific POST parameters to be set. – CBroe Jul 28 '21 at 06:35
  • ok i get what you are trying to say but for example if i said ``` if ($_SERVER['REQUEST_METHOD'] === 'POST') { //run script }``` won't that run on page render and never check for post request again? @CBroe – seriously Jul 28 '21 at 06:42
  • It checks once, every time the script runs. And by making your AJAX request, which is a _second_ request, completely independent of the first one, you are making it run a second time. – CBroe Jul 28 '21 at 06:44
  • I added an update code to my question with your suggested stratagy but no second ajax request when calling the function therefore no echo am i doing something wrong? @CBroe – seriously Jul 28 '21 at 07:04
  • You also need to make your script _not_ output the `script` and the `button` element - if you output those before your JSON data, then that will invalidate your JSON. – CBroe Jul 28 '21 at 07:07
  • im not sure i understand what you mean by that. If i don't output the button then how am i gonna call the ajax function @CBroe – seriously Jul 28 '21 at 07:18
  • You need to output them on the _first_ request, that is used to load & display the HTML page. You need to _not_ output them on the _second_ request, because the response to that is supposed to be JSON. (And that means JSON _only_, otherwise your client-side code will fail to decode it.) – CBroe Jul 28 '21 at 07:19
  • if i am not getting this wrong i am outputing them on the first request which is page load as you explained earlier i tought the second request was created when i ran the ajax function. @CBroe – seriously Jul 28 '21 at 07:22
  • Yes, it is. But currently, you PHP script does not properly differentiate between the two requests. You made the part that is supposed to provide the response for the AJAX request dependent on some condition now - but you need to do the same thing, only opposite, for the rest of it as well. The `script` and `button` elements must _not_ be output in case you are handling the AJAX request. – CBroe Jul 28 '21 at 07:27
  • what I don't get is how im making the script and button elements an ouput. i don't think i get what you mean by that @CBroe – seriously Jul 28 '21 at 07:39
  • I can’t really tell what your problem with understanding is here. If you can manage to output some JSON dependent on a condition - then where is your problem doing that with any other arbitrary text output then? Only that text output happens to be `` and `` now. – CBroe Jul 28 '21 at 07:49
  • (Of course you don’t have to `echo` large parts of static HTML - https://www.php.net/manual/en/language.basic-syntax.phpmode.php) – CBroe Jul 28 '21 at 07:49
  • If you are getting output in console that would be the success for your ajax request, I don't know what does that php code doing after `click me` button. And I don't think that `result.abc` will work there, as `json_encode` is to encode as string. – Mohammed Khurram Jul 28 '21 at 10:48

1 Answers1

0

Assuming your script and button tags live in the same file as the php script the way it's shown in your question: Your code runs out of order because, as you point out yourself, you run the PHP code before your create function runs. Just because you wrote the code in order doesn't mean it will run in order.

Here's what happens, in order:

  1. script and button tags are rendered
  2. Your php code runs
  3. The result of steps 1 and 2 is sent to the browser
  4. Then somebody clicks the button

What you need to do is move the php script to a separate route that you only request upon button blick. For example test.php, assuming the code you show in your q doesn't already live in that file—in that case, you'll need to put the php code in a different file.

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115