Trying to use AJAX to display a spinner during php code execution, then show error, or redirect on success

I have a simple PHP script that collects an e-mail via an HTML form, then sends a message to it. But there is a delay when pressing submit as the script executes. So, I’m trying to use AJAX and JS to display a spinner during code execution, and dim the screen as well, so the user knows that it is processing. Then once done, the screen returns to normal, and either redirects to “thanks.php” upon success, or displays an error on failure. All of this works, but the AJAX/JS doesn’t! I use a DB to check if a submitted e-mail has already been used. If yes, it creates an error message and this is supposed to be displayed to the user. If it’s a new e-mail, it processes the PHP, sends a message to that e-mail, then redirects to “thanks.php”. Again, this all works. But the AJAX, if the e-mail exists, only shows the spinner for a second, and that’s all. And if the e-mail is new, the spinner displays while the script processes, but the screen doesn’t fade, and when completed, it does not redirect or show the error message. The new e-mail is saved in the DB and everything else works. Hmm…

I’ll be honest, I was using AI for the AJAX/JS and after 5 to 6 iterations, and testing, it just doesn’t work.

Any help would be great! I’m completely a noob with AJAX/JS, but it would be awesome to get this working! Here is the full code, minus the e-mail sending code and API stuff (obviously):

https://pastebin.com/M5tfyEtU

Thanks!!

Is the single pastebin the buy.php code?

When ajax submits to the same page that it is on, your code must exit/die after it outputs the json response. By allowing the code on the page to continue after that point, the html document is still being output, breaking the json syntax, and should be producing errors that you can see in the browser’s developer tools.

You also need specific post method form processing code, so that it only gets executed upon a post method form submission. Put all the post method form processing code inside a conditional statement -

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
    // put all the form processing code here...

    // after outputting the json response, exit/die to stop code execution
   die;
}

// the html document starts here...
?>
1 Like

Yes, it’s all one file (now called buy_ajax.php to keep it apart from the original). Okay, getting closer. I added the code you suggested, including a “die;” after both JSON responses (one for the error display, and the other at the very end after the success code executes). And I’m getting this in the console in Firefox:

AJAX error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

And in Chrome (my main browser):

AJAX error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON (buy_ajax.php)

I played around with it, but couldn’t get it to work (the spinner shows up, but the screen doesn’t dim and no error or success message/redirection occurs) as before…

That you are receiving the <!DOCTYPE tag in the ajax response says that you are not making the ajax request to the proper code.

I think the call is to the proper code. However, as phdr said previously, you aren’t exiting the processing. So it continues to render the html following the script.

1 Like

I do see what you are saying about the code not stopping and throwing that error. How do I fix this? I added the “die;” code after each JSON echo. Is this not correct? Am I missing a step? This is my first time using AJAX and JSON in my own code. But I do see, and follow what is basically happening in it. Here are the updated snippets:

if($stmt->rowCount() > 0){      
        $error = "<br><span class='error_msg'>This e-mail has already been used! Contact me if you need assistance.</span><br>";
        // Prepare the response
        $response = array('error' => $error);

        // Set the content type to JSON
        header('Content-Type: application/json');

        // Encode the response as JSON and echo it back to the client
        echo json_encode($response);
        die;
    } else {   
    
    // Process the email sending and other tasks

        // Prepare the success response
        $response = array('success' => 'Thank you for your submission!');

        // Set the content type to JSON
        header('Content-Type: application/json');

        // Encode the response as JSON and echo it back to the client        
        echo json_encode($response);        
        die;     
      }
          ...

The actual AJAX/JS:


    $(document).ready(function(){
        $("#register_form").submit(function(event){
            event.preventDefault();
            $("#loading").show();
            $("body").css("background-color", "rgba(0, 0, 0, 0.5)"); // Dim the background
            $.ajax({
                type: "POST",
                url: "buy_ajax.php",
                data: $(this).serialize(),
                dataType: "json", // Set the expected data type to JSON
                success: function(response){
                    if (response.error) {
                        $("#error_msg").html(response.error);
                        $("#loading").hide();
                        $("body").css("background-color", ""); // Restore the background color
                    } else {
                        // Redirect to thanks.php or display a success message
                        window.location.href = "thanks.php";
                    }
                },
                error: function(xhr, status, error){
                    // Handle AJAX error
                    console.log("AJAX error: " + error);
                    $("#loading").hide();
                    $("body").css("background-color", ""); // Restore the background color
                }
            });
        });
    });

After looking at it line by line, it seems related to displaying the error message, or if success, redirect. The code works otherwise, so if the e-mail was used, I do see the spinner. It just doesn’t show the error message, and if the e-mail is new, I see the spinner for the 4 or 5 seconds while the code executes, and it adds the e-mail to the DB, and sends a message as intended (but no screen dimming). But again, it won’t redirect.

I’m also not sure why part of the code is:

 // Prepare the success response
    $response = array('success' => 'Thank you for your submission!');

But then later it is:

success: function(response){

                    if (response.error) {

                        $("#error_msg").html(response.error);

                        $("#loading").hide();

                        $("body").css("background-color", ""); // Restore the background color

                    } else {

                        // Redirect to thanks.php or display a success message

                        window.location.href = "thanks.php";

                    }

                },

                error: function(xhr, status, error){

                    // Handle AJAX error

                    console.log("AJAX error: " + error);

                    $("#loading").hide();

                    $("body").css("background-color", ""); // Restore the background color

                }

The response string seems odd. One last thing: What’s up with this:

  $("#error_msg").html(response.error);

“error_msg” is a class. So why is it $("#error_msg").html… Is it saying error_msg is an html file?

In your server-side code, you are validating the email address (more than once), but you are not sending anything to the client if the email is not valid.

The following errors can occur in the php code - 1) email format not valid, 2) email already in use, and 3) mail sending error. After the end of the processing, if there is any error, send it in the json response, ‘else’ send the success json response.

So that the ajax response code could specifically test if response.success is true, and simply output that message on the current web page.

The javascript, as written or wherever you copied it from, expects a specific, single, element with id=‘error_msg’ to put the response.error into, as the html content of that element (see the .html( htmlString ) documentation at this link - .html() | jQuery API Documentation )

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service