Decode $_POST data from ajax/Jquery serilized form - php

I submit a form using AJAX and JQuery.
serializedData = $form.serialize();
request = $.ajax({
url: "processData.php",
type: "post",
data: serializedData
});
The problem is when I use the data on processData.php the text is urlencoded.
cuando=Una+fecha+%C3%BAnica
I tried using php's urldecode() but it is not working. it's still urlencoded..
$cuando = $_POST['cuando'];
$cuando = urldecode($cuando);
Any suggestion? Thanks a lot!

Can't reproduce it..I made this:
<?php
echo urldecode('Una+fecha+%C3%BAnica');
Output is this:
Una fecha única
My only guess is that in your question you mean that your output is still what my input is, in that case you are somehow double urlencoding it on the other end

The form data is encoded in the same way as if it was a normal HTML form submission without Ajax, so there is nothing special to do, just use:
echo $_POST['cuando'];
PHP has already decoded and parsed the request body (post data).

First I tried changing the contentType attribute on JQuery $.ajax function, but it didn't work out:
$.ajax({
url: "insertar_datos.php",
type: "post",
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
data: serializedData
So, I found that there some issues at working with other charset encodings that are not UTF8 on JQuery-ajax.
http://forum.jquery.com/topic/serialize-problem-with-latin-1-iso-8859-1-and-solution
Then, I tried with no hope the php function utf8_decode():
utf8_decode($_POST['cuando']);
And it worked. what I found on this link is that:
"utf8_decode simply converts a string encoded in UTF-8 to ISO-8859-1. A more appropriate name for it would be utf8_to_iso88591. If your text is already encoded in ISO-8859-1, you do not need this function. If you don't want to use ISO-8859-1, you do not need this function."
So, if someone is using iso-8859-1 and is having some problems with ajax posted data. You can decode it for sure with utf8_decode(). Maybe there is an easier way to decode all data before post it, but as you can see it didn't worked to me.
If someone knows a better/more efficient way I'll choose your answer happily.
Hope it helps someone,
Regards!

Related

Ajax form gets sometimes urlencoded

I have an own made ticket system and lately I have an annoying thing going on. What's happening is that sometimes when making reply, all spaces are being replaced with the + sign. So far it is only happening recently and only at certain messages, so not all of them. I haven't been able to detect a special condition or character in the messages where it is happening.
The code is as following:
$(document).on('submit', '#newticket, #addreply', function () {
$(".loadingadd").show();
var eid = $(this).attr("id");
var xform = $(this).serialize();
$("#"+eid+" :input").prop("disabled", true);
$.ajax({
type: "POST",
url: "/a/tickets",
dataType: "json",
data: xform,
success: function(data) {
The Form:
<form class="form-inline" role="form" action="" method="post" id="addreply">
I'm using Firefox 50.1.0.
I have not been able to catch the event in Firebug in action, so there is a chance the server side is causing it, but I doubt that since it's not happening every time.
Does anyone know if a browser can decide to urlencode a POST or something? Or should I always encode in JS and decode server side? If so, how to do this with the serialize?
How to encode value with jquery serialize?
I saw this, but I don't have that currently and yet I only sometimes have the + signs. And doesn't that replace removes valid + uses?
Basically I'm now just using the serialize to send the form, and using $_POST['message'] to get the contents, not using any decoding or encoding.
Or should I specify an enctype? If I read http://www.w3schools.com/tags/att_form_enctype.asp the + sign is only not replaced when using multipart/form-data?
Anyone knows whats going on here and what I should use for forms, ajax encoding and server side (php) decoding? Whats best practice?

$.ajax and accented characters issue

I am using this ajax code to send data to server:
$.ajax({
data: postData,
type: method,
url: url,
timeout: 20000,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
error: function(jqXHR,textStatus,err){alert("Error returned from ajax call "+err);},
success: function(data,status,jqXHR){
// process response...
}
});
postData is a query string with many values while method is GET or POST
The problem is that, when I send a query string that contains a value like Älypuhelimen lisävarusteet, the result in database is �lypuhelimen lis�varusteet
The database connection collation is utf-8, and this works fine when I do not use ajax to post and save to database... It is definitely ajax that messes up the encoding...
I have also tried using encodeURIComponent() function on the data, and it becomes %C4lypuhelimen%20lis%E4varusteet if I use it... same goes for escape() function...
any help will be appreciated...
You should try jQuery Base64 encode.
JavaScript:
<script src="jquery.min.js"></script>
<script src="jquery.base64.min.js"></script>
<script>
enctext = $.base64.encode("yourtext");
//your ajax code goes here.
</script>
PHP :
<?php
$org_text = base64_decode($_POST['your_variable']);
?>
jQuery Base64 plugin.
download from here.
https://github.com/carlo/jquery-base64
Try changing the column in the database to utf16_bin Collation
Post you php database connection code.
Just for information and to help others that might fall in the same situation...
The problem was with the postData itself... it was parsed such that every post variable was applied with escape()... Using encodeURIComponent() instead of escape() worked!
Summary:
Donot use escape() function to url-escape query components... use encodeURIComponent() instead...

jQuery / AJAX / php encoding nightmare

First of all, my database encoding is utf-8.
I must send the string Fußball to index.php via the POST method. When I send it using an HTML form with action="index.php", it is sent as Fu%DFball and to return it correctly I use htmlentities() on the php file. It works great. The problem starts when I try to send it using jQuery/AJAX.
$("#Form").submit(function() {
$.ajax({
type: "POST",
dataType : "text",
url: "index.php", //Does the validation
data: $("#Form").serialize(),
success: function(data) {
alert(data)
},
});
return false;
});
It is sent as Fu%C3%9Fball and returned as Fuà and I tried everything to decode it or send it in a different way. Here is what is returned in various scenarios:
Sending normally, with htmlentities() on the php file:
FuÃ
Sending normally, without htmlentities() or with htmlspecialchars() on the php file
Fußball
Sending normally, with utf8_decode() on the php file
Fu
Using escape(), encodeURIComponent() or contentType: "utf-8" on the jQuery script before sending the string makes the form to be submitted in a way the .php file can't understand, but not only that, it still sends the string as Fu%C3%9Fball.
I also used the proper command for each file type to encode all my documents as utf-8, which didn't make any difference so I assume it was all utf-8 to start with.
Make sure your web page's encoding is also UTF-8.
If it is ISO-8859-1 by default, it'll parse UTF-8 characters wrongly, as experienced by you.
To check, look in your browser's "encoding" menu when opening the page: That's the final word on what encoding is used.
It could be that your server is configured to output ISO-8859-1 content type headers for HTML files. See How to change the default encoding to UTF-8 for Apache? for how to fix that.

Proper way to format user-entered text input for sending via JSON/AJAX to PHP?

I'm running into some problems with user-entered input that I want to send to PHP as JSON via AJAX that contains special characters, like ", ', etc. I'm sending the contents of an array (used for slickgrid), and everything works fine unless those characters are included. I know that PHP has the handy function mysql_real_escape_string, but is there any sort of jquery analogue? Here is the relevant code:
req = $.ajax({
url: url,
dataType: "text",
data: {"data": $.JSON.encode(data)},
type: "post",
success: onSaveSuccess,
error: onSaveError
});
Here's the PHP it is submitted to:
<?php
//$data = array();
//if (isset($_POST['data']))
//{
//$data = json_decode($_POST['data']);
//}
//header('Content-Type: text/javascript');
//echo json_encode($data);
print_r($_POST);
?>
To be clearer, when special characters are included, neither the success nor error events are triggered.
I looked in firebug and it doesn't appear to send anything at all when the special characters are included... Of course, it does when it's just letters or something.
It was due to the script from here apparently failing on certain kinds of input. Switching to json2.js and using JSON.stringify has solved the problem.
data: {"data": $.JSON.encode(data)},
Passes up a more complex JSON object than you need.
$data = json_decode($_POST['data']);
Is looking for a serialized JSON object but jQuery is doing a lot of work for you in the background.
Try this
data: $.JSON.encode(data),
In your AJAX call. Then in PHP
$data['myPostValue'] = $_POST['myPostValue'];
You're sending a JSON object to the $.ajax call, and it is changing it into the name value pair that the server would normally get from a post.
javascript has an escape() function. you can $.JSON.encode(escape(data)) might work

Mysql not retaining line breaks from Jquery ajax post?

I've got a PHP/Mysql app that lets users post text from a form. When I insert text from an HTML textarea into my mysql table, it's not keeping the carriage returns/line breaks. The text is not stored in the DB as "Hey SO, \n This is a new line". It's stored with white space in the column (exactly like it's typed), but there is no way for me to output it with nl2br() and keep the breaks. I'm escaping before inserting the text like so:
$foo_text = mysql_real_escape_string(ucfirst($_POST['foo_text']));
But even if I remove everything and just use the POST parameter, it still does the same thing. Would this have anything to do with me serializing and posting this form via ajax (I'm using JQUERY)? I found this on stackoverflow, but I don't really see a solution. I'm posting with:
$.ajax({
type: "POST",
url: "insertFooBar.php",
data: $("#foo_form").serialize(),
success: function(msg) {
ETC...
}
})
Is there something really obvious I'm missing here? I'm stuck...
Thanks in advance for any help!
The problem is that serialization should encode a line break as %D0%DA, but jQuery encodes it as %0A.
The only (graceless) solution i found was to get the form serialized string, then modify it with a replacement function such as :
function keepLB (str) {
var reg=new RegExp("(%0A)", "g");
return str.replace(reg,"%0D$1");
}
Once the serialized string is modified, i send it using the $.post() function.
Hope it will help !
Thanks for the answers. I ended up removing the serialize() and sending each parameter manually as a string. I added $("#foo_bar").replace( /\n/g, '<br>' )) to my textarea as a workaround and now I'm getting my breaks. Wish I didn't have to hack this to make it work, but it gets the job done.
I never got any problems inserting data from a HTML Form into database, either the form submitted normally or using AJAX.
Have you try to submit the form without AJAX? What is the result? I want to suggest you to use jQuery form plugins so you don't have to do the AJAX request manually.
I'm also want to suggest you to use AdoDB to save the data into database. This library provide a great cross-database abstraction. I haven't found any problems when insert/update the data, all value escaping is done automatically. Here is the example way to do update using AdoDB:
$data['foo_text'] = ucfirst($_POST['foo_text']);
$adodb->AutoExecute($tablename, $data, 'UPDATE', "id=$id");
I hope this libraries will help you.

Categories