Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle jQuery .ajax responses from server

Tags:

jquery

ajax

forms

I am trying to figure out how to process a response from a server (server returning either true or false (json encoded)) with ajax / query:

function submitFormWithAjax(form) {
    form = $(form);

    $.ajax({
        url: form.attr('action'),
        data: form.serialize(),
        type: (form.attr('method')),
        dataType: 'json'
    });

    var serverResponse = eval(result.responseText);
    console.log(serverResponse);
    return serverResponse;
}

now when I console log the result, there property responseText is showing as true/false correctly, however the function always seems to return true. I am not a javascript / jquery programmer, so if what I am doing above looks 'stupid' forgive me, I am trying to piece things together.

-- Correction, the function always returns false (not true as I stated above)

like image 319
Aaron Murray Avatar asked Oct 22 '25 05:10

Aaron Murray


1 Answers

This is probably closer to the right way of doing this....

$("#SomeButtonThatOpensDialog").click(function()
{
    $("#ElementWithForm").dialog({
        // dialog options here
        buttons: {
            Submit: function() {
                $.ajax({
                    // ajax options
                    success: function(data, status, xhttp)
                    {     
                        if ( data )
                        {
                          // if true
                          $("#ElementWithForm").dialog("destroy");
                        }
                        else 
                    { // if false, show some sort of message with errors
                            alert("OH NO!");
                        }                      
                    }
                });
            }
        }
    })
});
like image 166
Darthg8r Avatar answered Oct 23 '25 19:10

Darthg8r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!