Russ Ted
Russ Ted

Reputation: 87

jQuery AJAX POST JSON error when sending ? or & to the server

I have looked all over the web for a solution to this problem. But couldn't find a fix.

Here's what I have for jQuery:

    function fetchMsg (type, msg, msgid) {
    $.ajax({
        type: "POST",
        url: "fetchmsg.php",
        data: "type=" + type + "&msg=" + msg + "&msgid=" + msgid,
        dataType: "json",
        cache: false,
        success: function(data){
            $.each(data.msgs, function(i,item){
                $('.messages ul').append("<div class='msgstyle id='"+item.usid+"'><li class='msgname'>"+item.fname+" "+item.lname+"</li>"+"<li class='msgid' id='"+item.msgid+"'>"+item.msg+"</li></div>");
            });
        }
    });
    return false;
}

The problem is when I type ? or & as a message, I get the an error such as: jQuery17104689251377712935_1330746677552

Any suggestions on fixing this? This is actually the message that is inserted in the database (instead of the actual ? or & character). I've tried JSON.stringify but it adds double quotes to the questions marks and it completely removes the & in the string, so it doesn't seem to be an ideal solution.

Thank you in advance.

Upvotes: 0

Views: 519

Answers (2)

J. Bruni
J. Bruni

Reputation: 20492

You need to URL encode the message:

data: "type=" + type + "&msg=" + encodeURIComponent(msg) + "&msgid=" + msgid,

Upvotes: 2

charlietfl
charlietfl

Reputation: 171669

If you use a data object shouldn't have any issues. Let jQuery encode it

 data: {type: 'type', msg: 'msg', msgid: 'msgid'}

Upvotes: 4

Related Questions