Ajax form gets sometimes urlencoded - php

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?

Related

Decode $_POST data from ajax/Jquery serilized form

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!

PHP - String gets chopped after nbsp character

I'm having a hard time using a combination of TinyMCE, Ajax and PHP Post to an ExpressionEngine database. The TinyMCE area collects the data from my database when the website loads, and I can edit it with rich text.
However, when I save these changes using ajax and POST to PHP, the string gets chopped off whenever the string contains . I haven't tried any other special characters, but it accepts <p> and <h1>
PHP code looks like this:
$tinyMCEData = $_POST['tinyMCEData'];
And when I echo this out, it's chopped off at this point. I've tried to replace the nbsp before it's sent off via Ajax, but I've no luck yet. I don't really care if there's a nbsp in there either, as long as it's accepted.
I've also tried htmlentities, like this:
$tinyMCEData = htmlentities($_POST['tinyMCEData']);
No luck there either. So why is this happening? I'm guessing there's a reason for this. Any help much appreciated!
Edit: My case looks exactly like the example from this question:
TinyMCE + Jquery + PHP + AJAX Special chars issue
Only the bottom two screenshots of the alert boxes. All I have in my tinyMCE editor are more than once space in the text.
Edit2: Here's what the javascript looks like:
var tinyMCEData = tinyMCE.activeEditor.getContent();
var pars = 'tinyMCEData=' + tinyMCEData;
var myAjax = new Ajax.Request(url, {
method: 'post',
postBody: 'pars,
onSuccess: success,
onFailure: failure
});
At this point, the data that's being sent looks like this for example:
<p>One two three four</p>
What the value is after php post:
<p>One two
you have a syntac error:
var myAjax = new Ajax.Request(url, {
method: 'post',
postBody: 'pars,
onSuccess: success,
onFailure: failure
});
shoud be
var myAjax = new Ajax.Request(url, {
method: 'post',
postBody: pars,
onSuccess: success,
onFailure: failure
});
also, are success and failure defined as functions?
complex857 was right! I only had to escape the string before it was sent to POST.
Like this:
var tinyMCEData = escape(tinyMCEData);
Another solution for those who still have an issue with this (And especially if you want to submit more details)...
I separated the text data from the other variables instead of using a datastring. Then make sure one of the variables contains your text
data: {var1: var1,
var2: var2,
var3: var3}

jQuery/AJAX send autogenerated Email without form and stay on page

I know this is a widely covered subject, but I kept searching the Web and couldn't find a solution for my specific problem.
What I am trying to do with jQuery/AJAX (as mentioned in the title):
I DON'T want any sort of Form that the user can fill out.
I just want a button (some HTML-Element) that when clicked sends an automatically generated mail to a predefined addess.
Neither the content nor the subject or anything else needs to be "filled in" by the viewer/user.
There will only be one variable (a script will insert the right value) that should be put somewhere in the content of the Email.
On clicking the button, the mail should be sent, the button should be replaced by a "Thanks whatever..."-message and that's IT!
No redirecting to another page or whatnot.
What I found that might be useful so far:
$.ajax({
type: "...",
url: "...",
cache: ...,
contentType: "...",
data: "{ 'body':'" + myMsg + "'," +
"'to': '" + myAddr + "'," +
"'from': 'AUTOMAILER'," +
"'subject': " + mySubject + mySpecVar + "'" +
"}",
dataType: "...",
complete: function (transport) { if (transport.status == 200) $("#myButtonContainer").html("Success"); else alert("Please try again later"); }
});
Let's say my HTML is:
<p id="notify">Notify!</p>
And my JS-part would start something like this:
<script>
$(document).ready(function(){
$("#notify").click(function(){
// THE JQUERY/AJAX STUFF HERE?
});
});
</script>
I assume I need at least some sort of a .php-File as well? Apparently I still don't get it...
I still very much lack experience and would be very grateful for a solution, or even for a nudge in the right direction!
If this problem has already been solved for someone on this site, I apologize. I didn't find it.
EDIT : This should all happen on the client-side (as far as possible). Meaning that the Email content is ultimately generated on the client-side. Sorry, forgot to mention.
You forgot to mention something important. That "script" that generates the email content is it client or server side?
All you need is the clickable element:
<button type="button" onclick="doStuff()">Send</button>
The ajax method:
<script>
function doStuff()
{
//var data =... ANY DATA YOU MIGHT NEED
$.ajax({
type: "POST",
url: "sample.php",
data: data,
dataType: "text"
});
}
//ADD here some jquery to change the button text
</script>
And then you can easily find a php script to send email. You can hardcode the email address if it never changes
Your $.ajax approach is fine, but you need a server action (set in the "url") that will finally send the mail. The browser can't do it alone.
Email sending is done server side ie php. post to an email.php file which then sends the email. Make sure to use json functions in php too if you need to do a callback.

Upload file using jQuery and Ajax

I have a form that I am sending to the server using jQuery $.post method. I am sending several fields with something like:
var myName = "Pedro";
var myDescription = "Description of Pedro";
$.post("~/insert_user", { name: myName, description: myDescription }, function(data){
alert("Successfully inserted " + data.name + " in DB");
}, "json");
This works great, as I take the values in insert_user.php and treat and insert the in the data base.
What if I need to add a field to my form to let the user upload an image?
How would I do that in my $.post call and how would I get it in the PHP?
I am using Symfony2.0, by the way, just in case it changes something. But the important part is how to add a file typed field to the ajax call.
Thanks in advance.
Pedro
You will find it would be a lot easier to use a pre built jquery plugin. My favourite is uploadify http://uploadify.com.
Its simple and easy to use and it will save you a lot of time trying to figure out a method of your own <>
$.post is the same as the code block bellow. In order for you to do what you need to you need to change it to use this atleast and then things will become simpler. So start by changing the $.post to this
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
Then add a parameter in the ajax block contentType : "multipart/form-data" or try mimeType (cant remember so clearly) and in the data : $("#form").serialize(), that should work.
please tell me if it didn't work
--NEW EDIT LOL-- Excuse my blind coding, you may need to test this
I did a bit more research and came across this. You need to build this array and add it to the data in your ajax block
var files = new FormData($('#fileinputid'));
jQuery.each($('#fileinputid')[0].files, function(i, file) {
files.append(i, file);
});
If what i read was accurate you should be able to pass that array with the rest of the ajax data. Although i am not completely sure how to add it to the serialized data.
Please test this and let me know. if it doesn't work ill do a full javascript script test for you and then post it here
This tutorial might help: Nettuts+: Uploading Files With AJAX
Make iframe and put form in it, submit the form and voila. Or you can use one of these AJAX File upload scripts
I finally used this:
http://malsup.com/jquery/form/#faq
It just works great for what I need.
Thank you guys for your help.

Cannot post absolute filepath in ajax call - it drops back slashes no matter what I do

Below is my javascript function that makes an ajax call via post. It sends a file location and the contents of a file to a php page that saves the file. The idea is so users can manage config file templates for a small application via the browser instead of manually logging into remote servers, making edits, and submitting the edits back to src control to be pulled into each application (it's all automated on the page that this ajax call posts the data to).
My problem is with fileloc. I CANNOT get my ajax call to post the fileloc and keep the dir structure intact. I've tried escape(), encodeURI(), encodeURIComponent(), and JQuery's versions of these functions. No matter what, my fileloc comes through on the saveConfigTemplates.php page as: "D:TestPHPconfigurationautomationtemplatesservernamefilename.cfg". I've tried php's decode and it doesn't make a difference... it's like the post loses all encoding and treats the single slashes as escape chars. Driving me nuts, any suggestions are appreciated.
function saveFile(){
var fileContents = $("#fileContent").val();
alert(fileContents);
var fileloc = "D:\TestPHP\configuration\automation\templates\servername\filename.cfg";
var fileconts = "fileloc="+encodeURIComponent(fileloc)+"&fileconts="+fileContents;
$.ajax({
type: "POST",
url: "saveConfigTemplates.php",
data: fileconts,
success: function(data) {
alert(data);
}
});
}
escape the backslashes:
var fileloc = "D:\\TestPHP\\configuration\\automation\\templates\\servername\\filename.cfg";

Categories