简体   繁体   中英

jquery ajax function returning null rather than json

I am developing a contact form that is submitted via the ajax command, the data is sent to a php file where it is processed and a json object is returned but i am having some trouble getting the json object back to into the ajax command as it keeps returning null, the code i am using is as follows...

$("#send").click(function () {
    var complete = true;
    $('input#name, input#email, input#subject, textarea#message').each(function () {
        if ($(this).val()) {
            $(this).css("background", "#ffffff").css("color", "#111111");
        } else {
            $(this).css("background", "#d02624").css("color", "#ffffff");
            complete = false;
        }
    });
    if (complete == true) {
        var name = $("input#name").val();
        var email = $("input#email").val();
        var subject = $("input#subject").val();
        var message = $("textarea#message").val();
        var data = '{"name":"' + name + '","sender":"' + email + '","subject":"' + subject + '","message":"' + message + '"}';
        $.ajax({
            type: "POST",
            url: "contact.php",
            data: "token=" + $.base64.encode(data),
            dataType: "json",
            success:function(response) {
        if (response) {
            var data = $.parseJSON(response);
            alert(data.response);
                if (data && data.status == "success") {
                $.fancybox.close();
            }
        }}
        });
    }
});

You can also see the problem live at: http://idify.co.uk , thanks for the help, i am not too good with javascript, im still learning...

Change

        if (response) {
            var data = $.parseJSON(response);
            alert(data.response);
                if (data && data.status == "success") {
                $.fancybox.close();
            }
        }}

to

        if (response) {
            var data = response;
            alert(data.response);
                if (data && data.status == "success") {
                $.fancybox.close();
            }
        }}

or just use use response directly.

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