JQuery ajax php post problem - php

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);
}
});

Related

How to serialize form inputs in a .change event with javascript/PHP/CURL?

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?

sending increment value from jquery to php file with for loop help

I have this for loop in jquery
$(document).ready(function() {
for(i=0; i<counter; i++)
{
dataCounter = i;
$.ajax({
url: 'file.php',
dataType: 'json',
data: dataCounter,
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});
}
});
And then I want to bring in my dataCounter into the file.php as a variable and have it change each time so I can get different records in mysql in file.php, am I doing this right? How would the php portion look like? I know how pass variables to a php file with this method if I had a form, but I don't have a get or a post form to work with. Also, my variables are going to change.
Can someone help me? Thank you!
While I don't recommend running an ajax query inside of a loop, I am wiling to explain the data option for $.ajax(). Ideally, you pass an object as the data option, and it is translated by jQuery into a query string where each object property name is a key and its value is the value:
data: {
count: dataCounter
}
becomes
?count=1
in the query string of the ajax request if datacounter is equal to 1.
In PHP you would access it as $_GET['count'].
data needs to be a key-value pair, not just a value as you have it here. Try something like: (not tested)
$.ajax({
url: 'file.php',
dataType: 'json',
data: ({dataCounter : dataCounter}),
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});

& Value not appearing with AJAX call

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.

JQuery Ajax post data not arriving

my Ajax post data is not arriving - any clues please.
The data is a serilaized form that "alerts" correctly with all the data using this
$(document).ready(function() {
var serial = $('#frm_basket').serialize();
alert(serial);
$.ajax({
url: "basket-calc.php",
type: "post",
data: serial,
success: function(){
("#basketTotal").load('basket-calc.php');
}
});
});
The alert gives me a string like product=p1&qty=1&product=p2&qty=2
But when I try to php echo out the results on basket-calc.php I get an "empty" array
basket-calc.php:
$test = $_POST;
print_r($test);
You can debug your request with firebug to make sure what is happening.
Also try setting the post type to GET:
type: "GET",
to see if it makes any difference.
try:
$(document).ready(function() {
var serial = $('#frm_basket').serialize();
alert(serial);
$.ajax({
url: "basket-calc.php",
type: "post",
data: serial,
success: function(result){
("#basketTotal").html(result);
}
});
});
Also note following points:
make sure basket-calc.php is not returning 404
try sending blank data and echo your response
once you get sample string from server, just attach the real data
hope this helps
If your htaccess is stripping the .php from the , the POST gets converted to GET. I think.
Try and remove .php from your url.

serialize function for string values to use in jQuery ajax datastring

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...

Categories