SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Learning...
    Join Date
    Jan 2003
    Posts
    778
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to handle JSON and HTML together?

    Via AJAX i am requesting certain informaiton. The script either returns the content as html or in case of an error returns JSON (error number and description).


    How can i fix the success message to cater for both?
    Code:
    $.ajax({
                cache: false,
                type: "POST", //POST
                url: processPageURL,
                data: dataValues, //form seralize
                dataType: "html",
                error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.responseText);
                },
                success: function (data) {
                    alert(data);
                }
            });
    Thanks
    The beauty of life is not dependent on how happy you are,
    but on how happy others can be because of you...

  2. #2
    SitePoint Zealot
    Join Date
    Apr 2010
    Posts
    154
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This may be a little late...

    When you remove the "dataType" jQuery will try to figure out what type of data is being returned by reading the header information.

    So what you can do is the following

    Code JavaScript:
    $.ajax({
        cache: false,
        type: "POST", //POST
        url: processPageURL,
        data: dataValues, //form seralize
        success: function (data) {
            if (typeof data == 'object') { JSON
                alert('We got some JSON!');
            }
            else { //html
                alert('We got some HTML!');
            }
        }
    });
    Follow me @YaderHernandez

  3. #3
    Learning...
    Join Date
    Jan 2003
    Posts
    778
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks.
    The beauty of life is not dependent on how happy you are,
    but on how happy others can be because of you...


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •