1

I have a drpcategory dropdown in a form. I will just paste the dropdown code below;

<div class="form-group">
     <label>Category</label>
     <select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
     <?php
          $category = ''.$dir.'/template/post/category.txt';
          $category = file($category, FILE_IGNORE_NEW_LINES);

          foreach($category as $category)
          {
              echo "<option value='".$category."'>$category</option>";
          }
     ?>
     </select>
</div>

Then I AJAX post every time I make a selection in the above drpcategory dropdown as below;

<script>
$(function(){

$('#drpcategory').on('change',function()
{

$.ajax({
method: 'post',
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});

});    

});
</script>

This seems to be currently working as I'm getting outputs like below in Chrome Browser > Inspect > Network tab every time I make a selection in drpcategory. Here is the screenshot;

Google Chrome Developer Tools Capture

The question is how can I capture this AJAX post data using PHP within the same page and echo it within the same page? So far I have tried;

<?php 
  if(isset($_POST['drpcategory']))
  {
    echo 'POST Received';
  }
?>

I'm looking for a solution using only PHP, JQuery and AJAX combined.

This question was later updated and answered here: AJAX POST & PHP POST In Same Page

haZh
  • 127
  • 2
  • 12
  • You're using `$(this).attr('post')`, I guess this should probably be `$(this).attr('method')` since it's like `
    ` and not `
    `. Your data should be in `$_POST` if you actually `POST` it (verify this using the network tab aswell!)
    – ccKep Mar 02 '19 at 04:42
  • @ccKep: The form is already `
    ` and I have changed the AJAX part to `$(this).attr('method')` and now it's just `http://example.com/?page=post` in the network tab. Still PHP didn't echo anything.
    – haZh Mar 02 '19 at 04:50
  • Could you please monitor network tab on ajax call. – Parvej Alam Mar 02 '19 at 05:05
  • @Parvej Alam: Already did. All network tab outputs in different situations are posted in my question and answers, comments below. – haZh Mar 02 '19 at 05:08
  • This question has been updated. Please refer if you can. – haZh Mar 02 '19 at 14:20

6 Answers6

1

First of all, this line -> type: $(this).attr('post') should be type: $(this).attr('method'),. So this will give the value ** type:post** and

As far as i understand, you are asking to send ajax whenever you select options from drpcategory. Why are you submitting the entire form for this. If i where you, i should have done this problem by following way

$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
   type: 'post',
   data: drpcategory,
   success: function(result) {
        console.log(result);
   }
});
});

On you php side, you can get your data like,

echo $_POST['drpcategory'];
Ijhar Ansari
  • 310
  • 1
  • 2
  • 9
  • Why there is a `e.preventDefault();` for the `$("#drpcategory").change(function();` function? But I have tried this code in my `$('#form').submit(function(e)` and PHP didn't echo anything. – haZh Mar 02 '19 at 05:06
  • 1
    i just use this to prevent default functionality. You can omit if you want. Try like this, it will work. – Ijhar Ansari Mar 02 '19 at 05:16
  • Already omitted and tried as I have mentioned. No luck on this one. – haZh Mar 02 '19 at 05:26
  • 1
    It should work and it is working fine for me. Please try to change id name from drpcategory to something different like drp. It sometime ajax keep cache of all the name and similar string might point to same pointer in chrome. Try this once – Ijhar Ansari Mar 02 '19 at 05:38
  • Tried with different `id`s and again no echo. Does PHP require a page reload to capture the POST and show the echo? Because as I have mentioned in the question, currently it will only echo if the page gets reloaded using the standard submit method with page reload. If that's the case, then I suppose this AJAX approach isn't gonna work for me. – haZh Mar 02 '19 at 05:50
  • AJAX is specifically for allowing information to be sent back to the server without requiring a page refresh. But your page does get called and you have to know what to do with the post request. See my answer below... when I finish. – Tim Morton Mar 02 '19 at 06:12
  • Oh, then you can send your ajax request to different page instead and your problem will be sent. How could i possibly didn't recognise this.. tell me after you have finished. – Ijhar Ansari Mar 02 '19 at 11:42
  • This question has been updated. Please refer if you can. – haZh Mar 02 '19 at 14:21
0

I recommend you read the documentation for the ajax function, I tried to replicate it and I had to fix this:

$.ajax({
    // If you don't set the url
    // the request will be a GET to the same page
    url: 'YOU_URL',
    method: 'POST', // I replaced type by method
    data: $(this).serialize(),
    success: function(result) {
        console.log(result);
    }
});

http://api.jquery.com/jquery.ajax/

OUTPUT: enter image description here

roag92
  • 146
  • 1
  • 6
  • I don't have a `url` as I'm posting to the same page. And I have tried `$(this).attr('method')` already. And in the network tab it just gave `http://example.com/?page=post` output. Still PHP didn't echo anything. – haZh Mar 02 '19 at 04:54
  • If you are posting to the same page, that means you’re posting to that page’s url. When you do a regular html post, your browser is filling that in for you if you don’t specify a url – Tim Morton Mar 02 '19 at 05:00
  • That's right if you don't put an URL the request will be the same page, I recommend you that you declare the url to test it and you can see how it works. – roag92 Mar 02 '19 at 05:08
  • @roag92 My webpage structure starts from `http://example.com/index.php`. Now I'm currently in `http://example.com/index.php?page=post` where users can post new things. I'm kinda confused what `url` I need to write in there so I removed `url` field for the browser to pick it up. – haZh Mar 02 '19 at 05:13
  • if is for the same file you can set the url as `http://example.com/index.php` or only `index.php`. For more information about relative urls, check this https://stackoverflow.com/questions/4765740/relative-urls-in-ajax-requests – roag92 Mar 02 '19 at 05:26
  • @roag92 Tried with `url` as `url: 'http://mywebsite.com/index.php'` but now the output in the network tab is just `http://mywebsite.com/index.php` every time I make a change on `drpcategory`. PHP didn't gave any output either. – haZh Mar 02 '19 at 05:34
  • As you can see now you are doing a POST request but the problem is identify the right URL. – roag92 Mar 02 '19 at 05:55
  • @roag92 I doubt that's the case since I have tried both `http://mywebsite.com/index.php` and `http://mywebsite.com/index.php?page=post` as the `url`. Besides, the browser is picking up the current page to post automatically if I don't specify a `url`. I strongly think that the problem lies elsewhere preventing PHP from displaying the echo. Can PHP even show a dynamic change like this without a page reload? – haZh Mar 02 '19 at 06:08
  • This question has been updated. Please refer if you can. – haZh Mar 02 '19 at 14:20
0

Please try this code:

$.post('URL', $("#FORM_ID").serialize(), function (data)
{
  alert('df);
}
Nimesh Patel
  • 796
  • 1
  • 7
  • 23
PHP Geek
  • 3,949
  • 1
  • 16
  • 32
  • What is `df`? I just edited this like `$.post('', $('#form').serialize(), function (data){alert(data);});` and it just give me an alert window with source code of the whole page that I'm currently in. – haZh Mar 02 '19 at 05:24
  • This question has been updated. Please refer if you can. – haZh Mar 02 '19 at 14:20
0
First change to $value

<div class="form-group">
 <label>Category</label>
 <select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
 <?php
      $category = ''.$dir.'/template/post/category.txt';
      $category2 = file($category, FILE_IGNORE_NEW_LINES);

      foreach($category2 as $value)
      {
          echo "<option value='".$value."'>".$value."</option>";
      }
 ?>
 </select>

then add url

<script>
 $(function()
 {
   $('#form').submit(function(e)
   { 
      e.preventDefault();
      $.ajax({
          url:'folder/filename.php',
          type: 'post',
          data: '{ID:" . $Row[0] . "}',
          success: function(result) {
              console.log(result);
          }
      });
   });
   $('#drpcategory').on('change',function()
   {
      $("#form").submit();
   });
 });

try request

if(isset($_REQUEST['ID']))

The result will/should send back to the same page

  • It's okay. I know it's not ideal to use the same variable names. But the real problem here is that PHP not getting the AJAX POST right? – haZh Mar 02 '19 at 05:29
  • Tried your edited solution. Please note that I'm posting to the same page using AJAX, so there's no `url`. But I have tried this with a `url` to the same page and still no echo from PHP. – haZh Mar 02 '19 at 06:10
  • This question has been updated. Please refer if you can. – haZh Mar 02 '19 at 14:21
0

It sounds like you're trying to troubleshoot several things at once. Before I can get to the immediate question, we need to set up some ground work so that you understand what needs to happen.

First, the confusion about the URL:

You are routing everything through index.php. Therefore, index.php needs to follow a structure something like this:

<?php 
// cleanse any incoming post and get variables

// if all your POST requests are being routed to this page, you will need to have a hidden variable 
// that identifies which page is submitting the post. 

// For this example, assume a variable called calling_page.  
// As per your naming, I'll assume it to be 'post'.

// Always check for submitted post variables and deal with them before doing anything else.
if($_POST['calling_page'] == 'post') {
  // set header type as json if you want to use json as transport (recommended) otherwise, just print_r($_POST);
  header('Content-Type: application/json');

  print json_encode(array('message' => 'Your submission was received'));
  
  // if this is from an ajax call, simply die.  
  // If from a regular form submission, do a redirect to /index.php?page=some_page
  die; 
}

// if you got here, there was no POST submission.  show the view, however you're routing it from the GET variable.
?>
<html>
  (snip)
  <body>
    <form id="form1" method="post">
      <input type="hidden" name="calling_page" value="page" />
      ... rest of form ...
      <button id="submit-button">Submit</button>
    </form>

}

Now, confusion about JQuery and AJAX:

According to https://api.jquery.com/jquery.post/ you must provide an URL.

All properties except for url are optional

Your JQuery AJAX will send a post request to your index.php page. When your page executes as shown above, it will simply print {message: "Your submission was received"} and then die. The JQuery will be waiting for that response and then do whatever you tell it to do with it (in this example, print it to the console).


Update after discussion

<div class="form-group">
     <label>Category</label>
     <select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
     <?php
          $category = ''.$dir.'/template/post/category.txt';
          $category = file($category, FILE_IGNORE_NEW_LINES);

          foreach($category as $category)
          {
              echo "<option value='".$category."'>$category</option>";
          }
     ?>
     </select>
</div>

<!-- HTML to receive AJAX values -->
<div>
  <label>Item</label>
  <select class="" id="drpitem" name="drpitem"></select>
</div>





<script>
  $(function(){

    $('#drpcategory').on('change',function() {
      $.ajax({
        url: '/receive.php',
        method: 'post',
        data: $(this).serialize(),
        success: function(result) {
          workWithResponse(result);
        }
      });

    });    

  });


  function workWithResponse(result) {

    // jquery automatically converts the json into an object.
    // iterate through results and append to the target element

    $("#drpitem option").remove();
    $.each(result, function(key, value) {   
         $('#drpitem')
             .append($("<option></option>")
                        .attr("value",key)
                        .text(value)); 
    });        
          }

</script>

receive.php:

<?php 
// there can be no output before this tag.

if(isset($_POST['drpcategory']))
{
  // get your items from drpcategory.  I will assume: 
  $items = array('val1' => 'option1','val2' => 'option2','val3' => 'option3');

  // send this as json.  you could send it as html, but this is more flexible.
  header('Content-Type: application/json');

  // convert array to json
  $out = json_encode($items);

  // simply print the output and die.
  die($out);


}

Once you have everything working, you can take the code from receive.php, stick it in the top of index.php, and repoint the ajax call to index.php. Be sure that there is no output possible before this code snippet.

Community
  • 1
  • 1
Tim Morton
  • 2,614
  • 1
  • 15
  • 23
  • Okay, so if AJAX is specifically for allowing information to be sent back to the server without requiring a page refresh, and in my question if PHP only successfully echo using the standard submit function with page reload, why PHP can't echo when that same standard submit function is overridden with AJAX? Is it because the page is not being reloaded for the PHP to show the changes? – haZh Mar 02 '19 at 06:40
  • In both html submission and AJAX submission, the same POST information is sent. The only difference is that AJAX does it behind the scenes and doesn't rewrite the page. In order to troubleshoot it, you need to have developer tools open and watch the network tab. On submission, you'll see the file request. click on it, and you can see what was submitted and what the reply was. – Tim Morton Mar 02 '19 at 06:47
  • If, however, the page reloads, then you know you didn't actually submit with ajax. Then it's a matter of going back to the docs to see what you missed. – Tim Morton Mar 02 '19 at 06:48
  • I just used the default submit to check if PHP does echo here. I have actually overridden the default submit as mentioned in the question and it's still like that now. And it's getting submitted using AJAX and there's no page reload. I'm getting file requests in Network tab as `http://example.com/?page=post` every time I make a change in `drpcategory`. So I can be sure that submit is being sent using AJAX, I just can't figure out why PHP is not `echo` here while the default submit did show the PHP `echo` in the page. – haZh Mar 02 '19 at 06:58
  • Where and how are you expecting it to echo? As written, it won’t show on the page, only in the console. To troubleshoot, need to know what the server is responding, found by clicking on the file request. – Tim Morton Mar 02 '19 at 13:39
  • There is no specific place I'm requesting it to echo. It can be anywhere in the page, I just echo it to see if PHP picks it up after AJAX `post`. That PHP echo should be in the same page and it should be visible with the new value without a page reload. I have updated the question with what's going on now after trying suggested solutions. Please refer if you can. – haZh Mar 02 '19 at 14:00
  • Ok I see that a post is initiated, now what is the response? I’m expecting that you’re seeing a repeat of the entire page output. – Tim Morton Mar 02 '19 at 14:36
  • Yes, in the Response tab, I can see the source code of this entire page. – haZh Mar 02 '19 at 14:39
  • Just a thought, to get rid of confounding variables, I would suggest posting to a temporary page whose only output is to echo the post variables it receives. That way you can troubleshoot one thing at a time. – Tim Morton Mar 02 '19 at 14:40
  • Created a `receive.php` file in the domain directory and added the `url` in the AJAX function. The `receive.php` file had `` coded in it. And in Network tab, this file is getting called successfully and it's outputting as; `Array ( [drpcategory] => Vehicles )` as expected. What I need is to echo just the value `Vehicles` in the same page without calling an external file like this. – haZh Mar 02 '19 at 14:49
  • Excellent. For the time being work with the external file while you figure out how the whole process works. What were you wanting to do with drpcategory on the server side? What are you wanting to send to the browser to display? – Tim Morton Mar 02 '19 at 15:03
  • I'm trying to get the value of `drpcategory` and use it to populate the 2nd dropdown called `drpitem` which isn't mentioned here, the html element code of `drpitem` is same as `drpcategory` with a PHP loop to read a file, except it's file path is getting changed according to the value sent by `drpcategory`. – haZh Mar 02 '19 at 15:09
  • Gotcha. Just wanted to be sure Ajax was really what you need. What you’re needing now is to know how to take the Ajax data and add it to the existing page. Still using the temp php page, I would suggest printing out what you want to insert/replace. Also in your question add the part of the html that will receive the changes. Once you get this all working, you can move php response back to index, but leave it separate for now for clarity. – Tim Morton Mar 02 '19 at 15:53
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/189319/discussion-between-tim-morton-and-hazh). – Tim Morton Mar 02 '19 at 16:58
  • Solved after several updates were made to the question: https://stackoverflow.com/questions/54968749/ajax-post-php-post-in-same-page – haZh Mar 06 '19 at 08:39
0

I think you have an eroror syntax mistake in ajax jQuery resquest because ajax post 'http://example.com/?page=post&drpcategory=Vehicles' does not return this type url in browser Network Tab.

<?php var_dump($_POST); exit; ?> please do this statment in your php function if anything posted to php page it will dump.

Here ajax request example

$("#drpcategory").change(function(){

e.preventDefault();

var drpcategory=$(this).val();

$.ajax({

type: 'post',

data: drpcategory,

success: function(result) {

    console.log(result);

}

});

});

`

  • Minor updates have been made to the question as suggested by answers here. And still no luck. In the browser Network tab, I'm getting `http://example.com/?page=post` requests and your PHP has dumped `array(0) { }` as the output. – haZh Mar 02 '19 at 07:19
  • sometimes jquery showes this type crazy thinks... do one think open new script tag create js function ,use onchnage="" method in html then write ajax in js function – Anandhukrishna VR Mar 02 '19 at 07:23
  • I would like to use keep using jQuery because standard JS is hard for me to understand. Even if I tried I would probably end up with this problem again. I doubt jQuery is the problem here, I'm missing something. – haZh Mar 02 '19 at 07:29
  • ya JQuery is the problem! use std.JS.nothing is hard html : – Anandhukrishna VR Mar 02 '19 at 07:35
  • Used your code and getting same activity in the Network tab as before, and still no PHP dump shown. Basically it's still the same. – haZh Mar 02 '19 at 07:49
  • check console tab to make sure no syntax error,then code function first line alert("ok"); to check if your code flow is in right way – Anandhukrishna VR Mar 02 '19 at 07:53
  • In console tab it's all white, not a single red error shown. Also I can confirm there's no syntax errors because I write code very carefully. And yes, code flows through AJAX and alert "ok" is shown in the browser when placed inside AJAX success. – haZh Mar 02 '19 at 07:57
  • ajx success is alerting??? ok fine ,so your request goes through same page please give url : path in ajax then, make sure php has if($_POST) and else part.It because ajax request success return whole page result . Please look through Network -> hearders -> Form Data ,it will shows your posting form data – Anandhukrishna VR Mar 02 '19 at 08:40
  • Browser is already detecting the `url` for the same page. Also tried giving a AJAX `url` before but no luck. Tried `if($_POST)` condition in PHP for an echo, but nothing echoed in the page. Here is the screenshot of Network > Headers during AJAX call: https://i.imgur.com/7rdu1oj.jpg – haZh Mar 02 '19 at 09:14
  • This question has been updated. Please refer if you can. – haZh Mar 02 '19 at 14:21
  • No, I couldn't make it. – haZh Mar 06 '19 at 04:46
  • whats was the '/?page=post' in your url ? please var_dump($_POST,$_GET); – Anandhukrishna VR Mar 06 '19 at 04:52
  • This is the new question with the problem I have, expecting a direct answer; https://stackoverflow.com/questions/54968749/ajax-post-php-post-in-same-page – haZh Mar 06 '19 at 04:53