狐狸.fox 2019-03-02 04:28 采纳率: 0%
浏览 141

使用PHP获取AJAX POST

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

  • 写回答

6条回答 默认 最新

  • weixin_33721427 2019-03-02 04:49
    关注

    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

    评论

报告相同问题?