CN1002
CN1002

Reputation: 1115

Displaying PHP success and fail messages with Ajax

What went wrong in this code? I ready many post here on this issue but can't fix my error. I have the following.

HTML Code

    <div id="successMessage" style="display:none;"> It worked </div>
    <div id="failMessage" style="display:none;"> It failed </div>

    <div container>
          <div class="modal">
            <form>
             ....
            </form>
          </div>
    </div>

PHP Code

if(!$stmnt->execute()){
            echo "Failed!"; 

        }else{
            echo "Inserted";
        }

AJAX Code

   success: function(data){
    viewData();
    if (data=="Failed!") { 
        console.log(data);
        $("#failMessage").show();

        } else if(data=="Inserted"){
            console.log(data); 
            $("#successMessage").show();
        }
    }

Problem: I would like to display the error in the page not in console. I want to inform the user. Why is it not working with $("#successMessage").show();?

PS: I am using Bootstrap. Also how can I show my messages using one(1) div="msg" tag?

Upvotes: 0

Views: 451

Answers (1)

Ayush
Ayush

Reputation: 759

Found a mistake in your code

PHP Code

   if(!$stmnt->execute()){
        echo "Failed!"; // Check the exclamation mark

    }else{
        echo "Inserted";
    }

AJAX Code

success: function(data){
        viewData();
        $('#addData').modal('hide');//close the modal.
        if (data=="Failed!") { // Add an exclamation mark to correct code
            $("#failMessage").show();
            //console.log(data); is showing message from PHP
        } else if (data=="Inserted") { // Change this else to else if
            $("#successMessage").show();
            //console.log(data); is showing message from PHP
       }

Change "Failed" in ajax to "Failed!". Also, change the else to correct format of else if

Upvotes: 1

Related Questions