Get JSON value and set AJAX behavior

3

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

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

Another example of use is to delete information and "remove" the div with some fade-out effect, the ID being generated automatically, eg <div id="item-52"> , if everything is right {"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;
            });
        });
    
asked by anonymous 20.10.2016 / 08:36

2 answers

2

Create a div with id errorMessage:

<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();
        }
     }
 });

Whenever he makes a request he will check the data.error, if the value comes true it will populate the new error div with the message that came and will display it to the user with slow effect. If it works, it hides the error message div.

    
20.10.2016 / 12:57
1

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

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.

    
20.10.2016 / 10:43