user1724268
user1724268

Reputation: 31

JQuery.Ajax call with <> in string

I have a simple jquery ajax call to update data from an input box. The moment I have any markup in the input, Eg a <div> it does not make it to the controller. Any help please on how I call ajax and save to database texxt that has html code markups in it

$.ajax({
  type:post,
  url: "/dom/updatelement",
  data: "name="+name+&id="+id
});

Where name may contain markup.

Upvotes: 0

Views: 117

Answers (2)

VisioN
VisioN

Reputation: 145428

First of all, you should make the correct Ajax call:

$.ajax({
    type: "POST",
    url: "/dom/updatelement",
    data: {
        name: name,
        id: id
    }
});

Next, you may transform characters like < or > in the controller part using special functions (e.g. htmlspecialchars() in PHP).

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039110

Here's the correct way to send data in a POST request:

$.ajax({
  type: 'post',
  url: '/dom/updatelement',
  data: { name: name, id: id }
});

jQuery will ensure to properly url encode the data when using this syntax.

You could of course could have done this by hand using the encodeURIComponent method:

$.ajax({
  type: 'post',
  url: '/dom/updatelement',
  data: 'name=' + encodeURIComponent(name) + '&id=' + encodeURIComponent(id)
});

But honestly the first method seems kinda more readable and preferable.

Upvotes: 5

Related Questions