user955822
user955822

Reputation:

Get JSON responce from ajax call to PHP script

I have been successful in returning the json responce from the ajax call to my php script that sends messages. When submitting data to the PHP script, if successful it should return a json string like the following...

{"status":"valid","message":"Your message was send successfully."}

I would like to check if the "status" equals valid and then show a div showing that the message has been sent. How would i go about doing this and this is the code i have so far...

$("#send").click(function() {
        var complete = true;
        $('input#fullname, input#email, input#subject, textarea#message').each(function() {
            if ($(this).val()) {
                $(this).css("background","#121212").css("color","#5c5c5c");
            } else {
                $(this).css("background","#d02624").css("color","#121212");
                complete = false;
            }
        });
        if (complete == true){
            var name = $("input#fullname").val();
            var email = $("input#email").val();
            var subject = $("input#subject").val();
            var message = $("textarea#message").val();
            var data = 'name='+name+'&email='+email+'&subject='+subject+'&message='+message;
            $.ajax({
                type:"POST",  
                url:"resources/includes/contact.php",  
                data:data,
                success:function(data){
                    alert(data);
                }
            });
        }
    });

Thanks,
Nathaniel Blackburn

Upvotes: 2

Views: 259

Answers (3)

Arfeen
Arfeen

Reputation: 2623

you can do it like this

$.ajax({
                type:"POST",  
                url:"resources/includes/contact.php",  
                data:data,
                dataType: 'json',
                success:function(response){
                   if(response.status="valid"){
                        ......
                  }

                }
            });

Upvotes: 1

Martin.
Martin.

Reputation: 10529

In your success callback function, add

data = $.parseJSON(data);
if (data.status == "valid"){
     //do stuff
}

Upvotes: 0

Ayush
Ayush

Reputation: 42450

change your success function to look like this:

success:function(data)
{
    jsonObject = JSON.parse(data);
    alert(jsonObject.status);
}

Upvotes: 0

Related Questions