javascript - Why is the PHP code not running after ajax data transfer?

$(function () {
$(
    "#contactForm input,#contactForm textarea,#contactForm button"
).jqBootstrapValidation({
    preventSubmit: true,
    submitError: function ($form, event, errors) {
        // additional error messages or events
    },
    submitSuccess: function ($form, event) {
        event.preventDefault(); // prevent default submit behaviour
        // get values from FORM
        var name = $("input#name").val();
        var email = $("input#email").val();
        var phone = $("input#number").val();
        var city = $("input#city").val();
        var qualification = $("input#qualification").val();
        var about = $("textarea#about").val();
        var reason = $("textarea#reason").val();
        var firstName = name; // For Success/Failure Message
        // Check for white space in name for Success/Fail message
        if (firstName.indexOf(" ") >= 0) {
            firstName = name.split(" ").slice(0, -1).join(" ");
        }
        alert("Fuck " + $("input#name").val());

        $this = $("#sendMessageButton");
        $this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
        $.ajax({
            url: "/assets/mail/register.php",
            type: "POST",
            data: {
              name: name,
              phone: phone,
              email: email,
              city: city,
              qualification: qualification,
              about: about,
              reason: reason,
            },
            cache: false,
            success: function () {
                // Success message
                $("#success").html("<div class='alert alert-success'>");
                $("#success > .alert-success")
                    .html(
                        "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;"
                    )
                    .append("</button>");
                $("#success > .alert-success").append(
                    "<strong>Your message has been sent. </strong>"
                );
                $("#success > .alert-success").append("</div>");
                //clear all fields
                $("#contactForm").trigger("reset");
            },
            error: function () {

                // Fail message
                $("#success").html("<div class='alert alert-danger'>");
                $("#success > .alert-danger")
                    .html(
                        "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;"
                    )
                    .append("</button>");
                $("#success > .alert-danger").append(
                    $("<strong>").text(
                        "Sorry " +
                            firstName +
                            ", it seems that my mail server is not responding. Please try again later!"
                    )
                );
                $("#success > .alert-danger").append("</div>");
                //clear all fields
                $("#contactForm").trigger("reset");
            },
            complete: function () {
                setTimeout(function () {
                    $this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
                }, 1000);
            },
        });
    },
    filter: function () {
        return $(this).is(":visible");
    },
 });

  $('a[data-toggle="tab"]').click(function (e) {
    e.preventDefault();
    $(this).tab("show");
  });
});

$("#name").focus(function () {
  $("#success").html("");
});

PHP Code

<?php

  if(empty($_POST['name'])      ||
  empty($_POST['number'])     ||
  empty($_POST['qualification'])     ||
  empty($_POST['city'])   ||
  empty($_POST['about'])   ||
  empty($_POST['reason'])   ||
  !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
  {
    echo "<script>alert(No arguments Provided!);</script>";
    return false;
  }

  echo "<script>alert(Come On);</script>";

?>

From the HTML Input views, I'm successfully fetching the data. But the code in PHP file is not running for some reason.
The ajax code shows "message was sent" which is only displayed if the data transfer is successful but the PHP code isn't running i want to add the data inside the ajax code into MySQL database and for that i need to transfer the data into the PHP file

Answer

Solution:

Your PHP script gets triggered, or at least the XHR request gets processed by your web server and it returns status 200.

This is indicated by your own statement:

The ajax code shows "message was sent" which is only displayed if the data transfer is successful

While you are correct that the message will be displayed only if the data transfer is successful, I am not sure you understand which transfer.

With XHR you do a request from the browser to a web server. When that request has an HTTP Status Code 200 response - that's success => your message gets rendered.

Your alert(Come On); doesn't get rendered in your browser because you never work with the returned data. Your "success" event handler doesn't take into account returned data - only your logic defined in the JS gets processed.

I suggest you alter your logic a bit:

PHP script:

<?php

  if(empty($_POST['name'])      ||
  empty($_POST['number'])     ||
  empty($_POST['qualification'])     ||
  empty($_POST['city'])   ||
  empty($_POST['about'])   ||
  empty($_POST['reason'])   ||
  !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
  {
    $response = array (
        "status" => "fail",
        "message" => "No arguments provided"
    );
    return false; // This is pointless
  }

  else{
    $response = array (
      "status" => "success"
    );
  }

  echo json_encode ( $status );

?>

Then on the JS end, process the actual response from the PHP script and filter based on the response status message:

  success: function (response) {
    if ( response->status == "fail" ) {

                // Fail message
                $("#success").html("<div class='alert alert-danger'>");
                $("#success > .alert-danger")
                    .html(
                        "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;"
                    )
                    .append("</button>");
                $("#success > .alert-danger").append(
                    $("<strong>").text(
                        "Sorry " +
                            firstName +
                            ", it seems that my mail server is not responding. Please try again later!"
                    )
                );
                $("#success > .alert-danger").append("</div>");
                //clear all fields
                $("#contactForm").trigger("reset");

    }

    if ( response->status == "success" ) {

                // Success message
                $("#success").html("<div class='alert alert-success'>");
                $("#success > .alert-success")
                    .html(
                        "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;"
                    )
                    .append("</button>");
                $("#success > .alert-success").append(
                    "<strong>Your message has been sent. </strong>"
                );
                $("#success > .alert-success").append("</div>");
                //clear all fields
                $("#contactForm").trigger("reset");

    }

I hope you get the point :)

Answer

Solution:

The response from an AJAX request is not automatically executed. If you want it to be executed, you need to add it to the DOM in your success function.

            success: function (response) {
                $('body').append(response); // execute the returned script.
                // Success message
                $("#success").html("<div class='alert alert-success'>");
                $("#success > .alert-success")
                    .html(
                        "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;"
                    )
                    .append("</button>");
                $("#success > .alert-success").append(
                    "<strong>Your message has been sent. </strong>"
                );
                $("#success > .alert-success").append("</div>");
                //clear all fields
                $("#contactForm").trigger("reset");
            },

Source