Take JSON value and set AJAX behavior

Asked

Viewed 580 times

3

How to take the JSON value with ajax and define the behavior, which div and which message to display, for example:

If the JSON returns {"error":"true","message":"Algo deu errado"} would display any div, "error" for example, with the message that JSON returned, being that JSON can return multiple messages...

Another example of usage is to delete information and "remove" the div with some fade out effect, the ID being generated automatically, e.g.: <div id="item-52">, if all goes well {"error":"false","message":"Removido com sucesso"} the DIV would be hidden. How can I do this?

jQuery(document).ready(function(){

            jQuery('#ajax_form').submit(function(){
                var dados = jQuery( this ).serialize();

                jQuery.ajax({
                    type: "POST",
                    url: "teste.php",
                    data: dados,
                    success: function( data )
                    {
                        alert( data );
                    }
                });

                return false;
            });
        });

2 answers

2

Create a div with errorMessage id:

<div id="errorMessage" style="display: none"></div>

Then change your ajax to:

$.ajax({
    type: "POST",
    url: "teste.php",
    data: dados,
    success: function( data )
    {
        if (data.error) {
            $('#errorMessage').html(data.message).show('slow'); 
        }
        else {
            $('#errorMessage').hide();
        }
     }
 });

Every time he makes a request he will check the data.error, if the value comes true he will fill the new error div with the message that came and will display it to the user with slow effect. If successful it hides the error messages div.

1

You have to define behavior through conditions within the success function.

jQuery(document).ready(function(){

        jQuery('#ajax_form').submit(function(){
            var dados = jQuery( this ).serialize();

            jQuery.ajax({
                type: "POST",
                url: "teste.php",
                data: dados,
                success: function( data )
                {
                    if (data.error == "true") alert (data.message);
                    else $('#'+id).remove();
                }
            });

            return false;
        });
    });

Anyway, it’s easier to answer a question than to write the whole code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.