I am submitting a form using .ajax().
The current script contains:
data: dataString,
dataString contains:
var list = $('.listsummary').val()
The class listsummary belongs to a textarea which users fill in,
or will be (partially) filled in dynamically through a different script.
The problem is that users nearly all of the time use the '&' sign, for example:
Potato & Patota blah blah blah
This screws up the dataString allowing to post everything written before the first '&' is found.
How can I achieve that the var list will be properly sent to the PHP handler in order to store the entire textarea content into the database WITH the use of '&'?
You can encode the string with encodeURIComponent()
var list = $('.listsummary').val();
var urlEncoded = encodeURIComponent(list);
You have 2 options. Either pack the data as an object:
data: { list: $('.listsummary').val() }
Or encode the URI components:
var dataString = "list=" + encodeURIComponent($('.listsummary').val());
Welcome to the world of injections. This is a simple problem, but there are multiple approaches that you can take:
If your data is simple unstructured text, you should set contentType to text/plain or application/octet-stream:
$.ajax({
....
data: "Hello & world",
contentType: "text/plain",
...
});
If your data is key values structured, then you should encode your data as application/x-www-form-urlencoded. This can be achieved in JQuery by passing a JavaScript key-value object to data:
$.ajax({
....
data: { text: "Hello & World", location: "Boston" },
...
});
If your data has more complex structure, you should encode your data in the most appropriate Content Type (e.g. JSON, XML, CSV) and set contentType to (e.g. "application/json", "application/xml", "text/csv")
$.ajax({
....
data: JSON.stringify(["Hello & world", {"Hello & World"}]),
contentType: "application/json",
...
});
--
On the PHP side, if you need to process anything other than application/x-www-form-urlencoded, you'll need to read the request body directly as a string. Which can be fine with this code:
$body = file_get_contents('php://input');
Or if you have PECL:
$body = http_get_request_body();
If you use a web framework, they probably also have ways to process custom content types. Check the documentation of your web framework.
Related
please consider following snippet
i have submited a form which contains a background image url , i have serialize the form data . in php the URL is not decoding , how to get orignal url
$("#slider_settings_form").submit(function(e) {
var postData = $(this).serialize();
submited form
$.ajax({
url: ajaxurl,
data: {
"params": postData,
"action": "saveFormSettings"
},
method: "POST",
success: function(response) {
alert(response);
},
});
Use string urldecode( string $str ) function to decode your encoded URL data
for more follow this link
A successful parsing could be done by adding urldecode like this:
parse_str(urldecode($_REQUEST['params']), $params);
urldecode is important because it converts url encoded string into parsable string.
If you want to achieve it from javascript you can use these methods:
var uri = "http://stackoverflow.com/questions/30587877/how-to-decode-serialize-url-from-javascipt-in-php"
var uri_enc = encodeURIComponent(uri); //for encoding
var uri_dec = decodeURIComponent(uri_enc); //for decoding
Here is the link for more details:
Url decode and encode
Have a look at this related question.
We need to see how you're decoding the data in PHP to help you, but in addition to the answer ahead of mine (suggesting the use of urldecode), you should also make sure postData actually has data in it.
Only "successful controls" are serialized to the string [...] - second answer
It's entirely possible postData is nil. You should test it by alerting it and go from there. The question I linked to has a more thorough answer with code examples.
var postData = $(this).serialize(); -- this would create a query string like 'a=1&b=2', where a and b are form fields. You might want to fetch the value of a or b -- the following code will help you:
parse_str($_GET['params'], $params);
// then you can use $params['a'] to fetch form field 'a'
print_r($params);
// =>
//Array
//(
// [a] => 1
// [b] => 2
//)
For more about parse_str, see http://php.net/manual/en/function.parse-str.php
Im creating a simple upload script. I use a simple form to let people upload a picture and then a external php script will upload the picture and return some vars to the upload page.
But I cant get the part to return some vars to work. currently im using this:
The page that also contains the form:
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
document.getElementById("titel" + amount).innerHTML = response['naam'];
});
The upload page that should return some data:
echo json_encode(array('naam'=>$naam));
This scripts returns undefined..
If I remove the ['naam'] after response on the form page it will print out:
{"naam":"test.png"}
Hope someone know what im doing wrong.
Thanx in advance!
You said:
dataType: 'text', // what to expect back from the PHP script, if anything
… so jQuery will ignore what the server claims the data is (which seems to be HTML as you haven't changed the Content-Type header in your PHP) and process the response as if it was plain text.
response will therefore be a plain text string and not the results of parsing JSON.
Change dataType to "json".
The response you get from the server is the string. To use it as object, you need to parse it to JSON format using JSON.parse().
var obj = JSON.parse(response);
Then you can use:
obj.naam;
to get the value of naam from the object.
Please change datatype from "text" to "json" then parse that JSON using JSON.parse(//return value ").
Var jsonObject = JSON.parse("Ajax Response object");
then use it jsonObject.keyName and it will return the value.
I'm trying to create a gist with multiple lines of content but not sure the best way to go about it. \n isn't working and neither is adding two empty lines. It shows up as a single line of text.
var content = 'content on\nnewline here';
$.ajax({
url: 'https://api.github.com/gists',
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "token TOKEN-HERE");
},
data: '{"description": "a gist for a user with token api call via ajax","public": true,"files": {"file1.txt": {"content": "' + content + '"}}}'
}).done(function(response) {
console.log(response.id);
});
How do I change the content variable to contain newline characters? I want the output to eventually show up as a .txt so I don't think I can change the media type? Thanks.
This is just a guess, but it might be because you're JSON-ifying manually, and the \n isn't being escaped properly. Try using JSON.stringify:
JSON.stringify({"description": "a gist for a user with token api call via ajax","public": true,"files": {"file1.txt": {"content": content }}})
Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.
So I am trying to do a post using jQuery.ajax instead of an html form. Here is my code:
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/$org_ID',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Here is my problem:
When this was in an html form, the $org_ID that was part of the URL would actually pull the variable and send it as part of the URL. Now that this is in jquery, its just sending $org_ID as text. How can I get this to figure out what the variable, $org_ID is? I tried declaring it in the javascript but I am brand new to jquery/javascript and don't really know what i'm doing.
Thanks!
Are you rendering this in PHP? In that case you need to do:
url: '/groups/dissolve/<?php print $org_ID; ?>'
Otherwise, you need to do something like
var org_id = 'foo';
// or
var org_id = '<?php print $org_id ?>';
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/'+org_ID,
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Unlike PHP, you can't interpolate variables in javascript, you have to concatenate them with the string.
If you're trying to POST a variable (org_id) then you should put it in data:
data['org_id'] = org_id;
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
While you can concatenate params onto your url to send them in an HTTP request, putting them in a data object not only lets jQuery do more work for you & escape HTML entities etc (and keep your code cleaner), but also allows you to easily debug and play around with ajax() settings.
It's not clear in the question where your data comes from, but you can use something like:
url: '/groups/dissolve/'+orgId,
or:
url: '/groups/dissolve/?orgId='+orgId,
Short answer, concatinate
url: '/groups/dissolve/' + $org_ID