简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM