how to sanitize user inputs that you gather by jquery .val() so you can write it in a dataString... in the example you see below when user writes
if some text that contains & the rest
of the comment doesn't seem to work
fine because it counts the rest as an
other variable to POST..
is there a sanitaziation or
serialization code? jQuery's
sanitize() function works on forms but
i want something that i can use
directly use on strings...
var id = $("some_id_value_holder_hidden_field").val();
var comment = $("#sometextarea").val();
var dataString = "id=" + id + "&comment=" + comment;
$.ajax({
type: "POST",
url: "write_comment.php",
data: dataString,
dataType: "json",
success: function(res) {
// Success
},
error: function(xhr, textStatus, errorThrown) {
// Error
}
});
Any suggestion will be much appreciated
Regards
Since you're using jquery, you can use the included Form plugin to serialize the array.
serialize() - Creates a url string from form fields (eg, someEle=someVal&anotherEle=anotherVal)
serializeArray() - Returns a key/value array of all the form elements (useful to know)
$.ajax({
url : 'write_comment.php',
type : 'post',
data : $('#form-element').serialize(),
success : function(data)
{
alert('yay!');
}
});
Edit: Edited to remove incorrect escape() part.
there is a built-in encodeUriComponent that does exactly what you're looking for. Besides that, you can provide an object in "data" field, in which case url encoding will be handled by jquery. In your example:
$.ajax({
type: "POST",
url: "write_comment.php",
data: { id: id, comment: comment},
etc...
Related
I'm working on a small project that requires Ajax to fetch data from database and update a page. The query to the database is built on the fly by the user and the query strings build like a chain. So for example the first item of the chain effects the next and the next and so on. Therefore it creates a list of post variables that I can't "know" ahead of time. I figured this would be a pretty simple thing to achieve however it's proving not to be. Here is my issue.
When I use a .changed event and try to seralize the form before posting it. I get nothing but empty strings. I've noticed that if I hard code the post variables everything works just fine. Is there something I'm missing? Does .changed not have a seralize method?
I am also using a CURL bridge since the server with the data is on another domain. I don't think that is causing any issues though. I believe it has to do with my event choice.
Here is the code:
$('#selector').change(function() {
$.ajax({
type: "post",
dataType: 'json',
url: "/pages/curlbridge.php",
data: $("#queryform").serialize(), //"select=all&date=2013"
success: function(data)
{
console.log(data);
var resultset = data;
}
});
Was Asked to attach the HTML. It's just a simple form
<form id="selector">
Select: <input type="text" id="select" />
Date: <input type="text" id="date" />
</form>
<br />
I agree with #m1ket that #queryform doesn't exist, although you can't use serialize() on a single input element, so the following line is incorrect:
data: $(this).serialize(), //"select=all&date=2013"
Perhaps what you can do is this (which gets all the data in the form the #selector is a part of):
data: $(this).closest('form').serialize(), //"select=all&date=2013"
EDIT
My bad, I didn't pay attention to the HTML posted in the original question
Scope issue maybe? Does this work:
$('#selector').change(function() {
var formData = $(this).serialize();
$.ajax({
type: "post",
dataType: 'json',
url: "/pages/curlbridge.php",
data: formData, //"select=all&date=2013"
success: function(data)
{
console.log(data);
var resultset = data;
}
});
});
$("#queryform") does not exist. Your jQuery should read like this:
$('#selector').change(function() {
$.ajax({
type: "post",
dataType: 'json',
url: "/pages/curlbridge.php",
data: $(this).serialize(), //"select=all&date=2013"
success: function(data)
{
console.log(data);
var resultset = data;
}
});
});
Also, are you using .change() because you want to submit the AJAX request every time a user enters a key?
This may sound strange but I have a JQ/AJAX/PHP post problem.
My "code" is all there and works in most situations except 1 - when I try to pass a tag through the process.
I grab the html like this
var ed = $('#fraRTE').contents().find('body #editarea').html();
#fraRTE is an iframe width an editable div #editarea hence .contents().find('body #editarea').html()
So if var ed is just "hello world etc...." there is no problem and the data is processed BUT if var ed is something like "hello world etc.... <img src="image.png">" the data is not processed - stangely if var ed is "hello world etc....<img src="image.png">" - no gap between text and the image the data is actually processed.
If I alert(ed) before the post then I see the "correct" string - whatever it's contents, post like this:
var data = 'content='+ed;
$.ajax({
type: 'post',
url: 'script.php',
data: data,
success: function(msg) {
alert(msg);
}
});
I create the data string before "data:data" as there are a few more items in the string.
my alert(msg) is set by echo $_POST['content']; on script.php
the alert(msg) tells me what has (or has not) been posted to the DB. this is where I see the problem mentioned above. i.e. the inclusion (or not) of <img...>
Suggestions please
jQuery is smart enough to handle turning your request data into a query string for you.
$.ajax({
type: 'post',
url: 'script.php',
data: { content: ed },
success: function(msg) {
alert(msg);
}
});
This issue you are having is the data not being properly escaped.
In order to stringify it yourself, you would have to use encodeURIComponent()
"content=" + encodeURIComponent(ed);
But it's far simpler to just let jQuery do it for you.
Don't use string concatenations when constructing request parameters or they won't be properly url encoded and if the parameter contains some special characters it won't be properly received. Here's the correct way:
var data = { content: ed };
$.ajax({
type: 'post',
url: 'script.php',
data: data,
success: function(msg) {
alert(msg);
}
});
ok, i have these two input fields where a user puts in two twitter names. When the submit button is pressed, both names should be send to a .php file with the POST method that checks if both usernames exsist on twitter.
Sending and receiving the answer for one value already works, but how can i also add the second? I already have this:
<script type="text/javascript">
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
**data: {'user1' : $('#user1').val() },** //how to append user2?
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
</script>
the fields in the form:
<td><input type="text" name="user1" id="user1"/></td>
<td><input type="text" name="user2" id="user2" /></td>
and this is how the values should be able to be cathed in the .php:
$user1 = $_POST['user1'];
$user2 = $_POST['user2'];
So the question really is: how can I append the second username to the above jQuery POST function?
p.s. I am starting with javascript and jQuery, how do you guys work with this as no error messages are shown ever.. is there an environment/programm where I get debugging help with javascript?
data: {
'user1' : $('#user1').val(),
'user2' : $('#user2').val()
},
It's a simple enough extension-- just follow the same pattern.
<script type="text/javascript">
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: {
'user1' : $('#user1').val(),
'user2' : $('#user2').val()
},
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
</script>
That said, jQuery does also have a .serialize() function that you could apply on the containing form, which automatically serializes the whole form. This could prove useful for you.
EDIT: It's worth mentioning that the jQuery selectors above look on the id for the name "user1" (etc.), whereas the PHP script expects the form elements' name to be "user1" (etc.). Here you have them as the same thing.
A more reliable jQuery selector that would allow you to always use the name in both jQuery and PHP is simply to use an attribute selector in jQuery:
$('input[name="user1"]').val()
This will catch any <input> element with the name attribute set to "user1".
You're probably looking for serialize. Your code would look something like this:
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: $("#your_form").serialize(),
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
If you're sure you don't want serialize you could try this:
data: {'user1' : $('#user1').val(), 'user2' : $('#user2').val() }
As for your PS, check out Firebug and Webkit developer tools.
You actually don't even need the serialize function. If you just select your form, all form elements will be passed. This way if you just add another form element, like another textbox, it will all be passed in your ajax call.
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: $("#your_form"),
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
I am working on submitting values into a database through AJAX. It currently uses JQuery Ajax object.My Ajax code basically looks like this:
enter code here
var genre = form.new_album_genre.value;
form.new_album_genre.value="";
$.ajax({
type: "POST",
data: "genre="+genre+"&app="+app,
url: 'apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php',
success: function(data) {
$('#'+divID).html(data);
}
});
In short, it gets a value from a form and then submits the data through a post. Where it fails if the genre is something like R&B. The & symbol is not sumbitting and only the R is. So how do I submit values through AJAX including &, + and = ?
You need to encodeURIComponent to deal with characters which have special meaning in URIs.
(Or pass an object containing key/value pairs to jQuery instead of the query string String you have now)
I've never had a problem with special chars using
$.post('apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php', {
'genre' : genre,
'app' : app
},
function(data) {
$('#'+divID).html(data);
});
Piggybacking off David Dorward's answer
$.ajax({
type: 'POST',
url: 'apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php',
data: { genre : form.new_album_genre.value, app: form.app.value },
success: function (data, textStatus) {
$('#'+divID).html(data);
}
});
Use
$.ajax({
type: "POST",
data: "genre="+encodeURIComponent(genre)+"&app="+encodeURIComponent(app),
url: 'apps/PVElectronicPressKitAdmin/ajax_add_album_genre.php',
success: function(data) {
$('#'+divID).html(data);
Because of the & it is interpreted as a new parameter.
In your case data will look like genre=R&B&app=somethig -> this means 3 parameters: genre, B and app.
I want to post an array using Jquery Ajax to php. Is this possible ?
Thanks
EDIT:
I tried following :
type: "POST",
url: "path",
data: "styles=" + strstyles + "&templateId=" + custTempId, //strstyles is an associative array
dataType: "json",
success: function (data) { .....}
but, styles hold no data. I spent a lot of time, before adding data type to the declaration. What can be the reason for "styles" being posted as null ?
Second Edit
I want to post style sheet dom object and save the class names and properties to DB. With the above edit, adding datatype did not help. I think it is b'coz the string is not in json format as follows -
{"a":1,"b":2,"c":3,"d":4,"e":5}
As the my string has double quotes, it is not following the format, and I think that's the reason, I'm getting an empty array. How can I handle this ?
With jQuery it is very easy:
$.ajax({
type: "POST",
url: location.href,
data: data,//data is array
dataType: "json",
success : function () {
// Something after success
}
});
You can use in following way too
$.ajax({
type: "POST",
url: location.href,
data: ({'data[]' : array}),//array is array
dataType: "json",
success : function () {
// Something after success
}
});
if you don't want to use JSON, PHP can automatically create arrays from Html forms
so you could do something like this:
type: "POST",
url: "path",
data: "styles[key1]=" + strstyles.val1 + "&styles[key2]=" + strstyles.val2 + ... + "&templateId=" + custTempId
...
that is if you want to have an associative array in php, but if you want just an array you could do
data: "styles[]=" + strstyles.val1 + "&templateId=" + custTempId
In POST call you dont use & , So your code should be
something like
type: "POST",
url: "path",
data: {styles: strstyles , templateId: custTempId}, //strstyles is an associative array
dataType: "json",
success: function (data) { .....}
is that point clear?
So coming to my solution,
you should download JSON parser from http://www.mediafire.com/?x6k3su7bbdrcta8.
Create object strstylesOBJ, code: var strstylesOBJ = {};
insert your strstyles array into strstylesOBJ and stringify it then pass to it in your post call
strstylesOBJ.styles = strstyles;
strstyles = JSON.stringify(strstylesOBJ);
In PHP code you refecth your array using $strstyles = json_decode($_POST['styles']);
do var_dump($strstyles) and please tell what was the output.
regards
Ayaz Alavi