0

If I have some php logic that results in either :

$staus = "pass";

or:

$status = "fail";

Then in my jQuery/Ajax I have:

$(function() {
$( "#send" ).click(function(e){
e.preventDefault();
$( "#send" ).prop( "disabled", true );
$( ".loader" ).show();
$( "#send" ).html( "Sending <img src='img/ajax-loader.gif'>" );
var form_data = $( "#contact-form" ).serialize();
 $.ajax({
  type: 'POST',
  url: 'send.php',
  data: form_data
}).done(function(response) {
 if(response.status == "pass")
// console log something here

But I am getting "undefined" in the Google Chrome Console when I try to console.log the data.

if($_POST) {


$message = "";

if(empty($_POST['first_name'])) {

    $message .= "First name required<br/>";
}

if(empty($_POST['last_name'])) {

    $message .= "Last name required";
}

if($message) {

    echo "<div class='alert alert-danger'>" . $message . "</div>";
    $pass = "error";

} else {

    echo "<div class='alert alert-success'>Form submitted successfully</div>";
    $pass = "succeed";
}
}
Iggy's Pop
  • 589
  • 1
  • 6
  • 24

3 Answers3

1

Try this:

$(function() {
$( "#send" ).click(function(e){
e.preventDefault();
$( "#send" ).prop( "disabled", true );
$( ".loader" ).show();
$( "#send" ).html( "Sending <img src='img/ajax-loader.gif'>" );
var form_data = $( "#contact-form" ).serialize();
 $.ajax({
  type: 'POST',
  url: 'send.php',
  dataType: 'json',
  data: form_data,
  success: function(json){
 if(json['error'])
{
$('#your_notification_div').html("<div class='alert alert-danger'>" +json['message']+ "</div>")
}
else
{
$('#your_notification_div').html("<div class='alert alert-success'>"+json['message']+"</div>")

}
}
});
});
});

Edit the validation PHP file:

    if($_POST) {
    $json = array();
    $message = '';
    if(empty($_POST['first_name'])) {
        $json['error'] = 'true';
        $message .=  "First name required<br/>";
    }
    if(empty($_POST['last_name'])) {
        $json['error'] = 'true';
        $message .=  "Last name required";
    }
    if(!isset($json['error'])) {
        $json['success'] = 'true';
        $message = 'Form submitted successfully';
    }
    $json['message'] = $message;
    echo json_encode($json);
}
Zaman
  • 551
  • 4
  • 8
0

I guess something like:

<?php
  $staus = "pass";
  ?>
  <script>
    const staus = <?php echo $staus?>
    console.log(staus);
  </script>
  <?php
  // PHP Code...
?>

I do something like that in EJS(Node)

Felix Fong
  • 969
  • 1
  • 8
  • 21
0

in ajax response you will get all echo value from PHP. if you want your ajax to give you result in variable then you can use JSON data type to retrieve data in array. refer this link for more details

Community
  • 1
  • 1
Bhupat Bheda
  • 1,968
  • 1
  • 8
  • 13