4

I'm trying to send HTML that is in a form to a server-side script so I can save it in the database. What I'm sending is a query string, and every time the HTML contains a character like a comma or ampersand, the rest of the HTML gets truncated at that point.

Thanks in advance!

2 Answers 2

7

When sending a request you should properly URL encode parameteres:

$.ajax({
    url: 'foo.php',
    data: { html: '<html>You can use whatever characters you want here</html>' },
    type: 'GET',
    success: function(result) {

    }
});

or:

$.ajax({
    url: 'foo.php',
    data: { html: $('#someTextFieldWhichMightContainHtml').val() },
    type: 'GET',
    success: function(result) {

    }
});

Now you can safely read the html variable in your PHP script: $.GET["html"].

I suppose that right now your code looks something like this:

$.ajax({
    url: 'foo.php?html=' + $('#someTextField').val(),
    type: 'GET',
    success: function(result) {

    }
});

I would recommend you to never use string concatenations and always use the data hash.

Sign up to request clarification or add additional context in comments.

5 Comments

is data html is preserved keyword , if you mention as html will it take care of these type issues...
@gov, no html is not a reserved word. You could use any name you like. The important part is to use the data hash.
i always pass as query string thats why i am asking, where did we use hash in the above code, i am just asking for learning purposes, don't mind
@gov, the data parameter of the $.ajax method is a hash (key/value pairs).
@DarinDimitrov what if i don't want to use php i want to use asp.net the how to do it.
0

As Darin Dimitrov said, it needs to be urlencoded. I use these function to encode and decode in javascript.

function urlencode(str) {
    return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function urldecode(str) {
    return unescape(str.replace(/\+/g, ' '));
}

Originally from a post on phpbuilder I believe.

3 Comments

Why on earth would you use such functions when there's encodeURIComponent and decodeURIComponent. Rolling your own encoding functions is rarely a good thing.
Woah, clearly I need to update my code. Thanks for the notice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.