Home > Enterprise >  Ajax send post request to the current page php
Ajax send post request to the current page php

Time:09-03

I want to send a post request to the current page and receive it through php. I searched the web then I found this code :

 <?php
    if (isset($_POST['firstName'])) {
        echo($_POST['firstName']);
    }
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button onclick="xy()">Search</button>
<script>
    function xy() {
     $.ajax({
     type: "POST",
     url: window.location.href,
     data: {
         firstName: 'Name',
         lastName: 'Surname',
         email: 'Mail',
         message: 'Msg'
      },
      cache: false,
      success: function(data) {alert('success')},
      error: function(xhr, status, error) {alert(xhr)}
 });}
 </script>

It is not working properly when I running it, it is only alerting success and php is not echoing the firstName that comes from the post request. what I'm doing wrong? Thank You

CodePudding user response:

<?php
    if (isset($_POST['firstName'])) {
        echo($_POST['firstName']);
        return;                             //add return;
    }
?>

then you can get $_POST['name'] value in success:

success(data) {
    alert(data);
}
  • Related