Lacking of Serializing or Encoding - php

function autosave()
{
setTimeout("autosave()", 15000);
var did = $("#did").val();
var content = $('.nicEdit-frame').contents().find('#nicEditContent').html();
if (content.length > 0)
{
$.ajax(
{
type: "POST",
url: "inc/autosave.class.php",
data: "did=" + did + "&content=" + content,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
cache: false,
success: function(message)
{
$("#message").empty().append(message);
}
});
}
}
What this does is takes what is in a textarea and sends it over to the autosave.class.php, which sends it off to the MySQL database.
The problem is that the data ends up in the database cut off, showing only the first few sentences of it; often cutting off at the quotation mark.
I am positive that this isn't the PHP to MySQL issue (already tested that), it's the AJAX/JQuery data to PHP part.
Is it the lack of serializing/encoding? If so, how would I fix it?

Have your data properly escaped, if someone puts Me & You in a field, the field will only contain Me since & is considered a argument separator.
data: "did=" + encodeURIComponent(did)
+ "&content=" + encodeURIComponent(content),
If data is still truncated, check the size of your database fields. MySQL does not fail if the passed data is larger than the field can actually hold.

You should let jQuery build the POST string for you by passing an object:
data: { did: did, content: content },

Couldn't you use serialize? http://api.jquery.com/serialize/

Related

php lost some path of string after submition using ajax post

I am trying to submit a comment using ajax post with php, it's working very fine as i expected it to but when i try to submit some sting that contain & it lossess path of the sting only show from beginging till where the and is.
I really don't know how to fix this, i have no idea about what is the problem please i need help.
See example
MY ajax
<script>
$('#submitcomment').on('click', function(){
try{
var message = $('.commentTextinput').val();
var key= $(this).attr('data-keyname');
$.ajax({
url: UrlExistsA('snippet/snippetcomment'),
data: 'message=' + message + '&key=' + key,
type: 'POST',
beforeSend: function(){
$('#submitcomment').html('Wait....');
},
success: function(data){
$('tr.replyList:last-child').after(data);
$('.commentTextinput').val('');
$('#submitcomment').html('Comment');
},
error: function(data){
alert('Processing Error' + '<br/>' + data);
}
});
}catch(err){alert(err.message);}
finally{}
});
</script>
Here is test php
<?php
if(isset($_POST['message'])){
$postReply = htmlentities($_POST['message'], ENT_QUOTES, "UTF-8");
echo $postReply;
}
The above will output this
tomorrow we will run faster, stretch out our arms farther... And then
one fine morning
But the original string posted was
tomorrow we will run faster, stretch out our arms farther... And then
one fine morning— So we beat on, boats against the current,
borne back ceaselessly into the past.
also when i tried to submit &&&&&&&&&&&&&&&&&&&&&&& it return empty But when i echo the above string without using ajax it was very okay
You need to call encodeURIComponent to encode special characters in the parameter string. & is the separator between parameters, so you need to encode it.
data: 'message=' + encodeURIComponent(message) + '&key=' + encodeURIComponent(key),
But a simpler way is to use an object instead of a string, then jQuery will encode it automatically.
data: { message: message, key: key },

Cant POSTing value of CKEDITOR and Lose the Format of CKEDITOR [PHP with JQUERY AJAX ]

I had ckeditor's values, when those content contained special characters, in my case it happened when a was inside the content of the editor. It "killed" the url since ?data=blabla is a malformed url..
var this = "conten=" + CKEDITOR.instances.tIsi.getData();
$.ajax({
url: "action/prosesPOST.php",
type: "POST",
data: this,
cache: false,
success: function(msg) {
alert(datanya);
if (msg == "yes") {} else {
alert("Failde to Update data," + msg);
}
}
});​
and i change it be
var this ={
conten: CKEDITOR.instances.tIsi.getData();
}
and viola i can update and posting that but all format of ckeditor lose when showed it on ckeditor on showing on table.
=================================== SOLVED ====================================
the problems is when i am posting it like this :
var this = "conten=" + CKEDITOR.instances.tIsi.getData();
ckeditor value unshowed,i know it because use alert(this); before ajax sending and value is null
when i am using :
var this = {conten: CKEDITOR.instances.tIsi.getData()}
data not null and inserted to database but my format style lose like "margin","align",etc make it like string,ex : BOLD be => < b >BOLD < / b >
and i solved this with simple trick make it be *html_entity_decode($value_on_database)* changing the object data to normal when i want showing it on ckeditor or the other.
CHEERS :))
Not sure how if I understood your question correctly. Is the issue with POSTing data or is the data malformed somehow? Meaning is it not as you expected on the server?
Does the following work (Edited to be more complete)?
$.ajax({
url: "action/prosesPOST.php",
type: "POST",
data: {conten: CKEDITOR.instances.tIsi.getData();}
cache: false,
success: function(msg) {
alert(datanya);
if (msg == "yes") {} else {
alert("Failde to Update data," + msg);
}
}
});​
Is the data posted correctly? If you debug the data in PHP, is it as you expected? How do you output the data if it looks OK before using it?
I would also use another variable name rather than "this" as it already has an expected meaning in JavaScript.

jQuery posts error text when posting with ajax

When I'm posting via ajax I'm sometimes getting extra characters posted for example. If the text passed though ajax yo a php $_POST I end up getting:
This is my messagejQuery127638276487364873268_374632874687326487
99% of the time posts pass though fine... I'm unsure how to capture and remove this error as it only happens some of the time.
// this is the ajax that we need to post the footprint to the wall.
$('#submitbutton').click(function () {
var footPrint = $('#footPrint').val();
var goUserId = '1';
$.ajax({
type: 'POST',
url: '/scripts/ajax-ProfileObjects.php',
data: 'do=leave_footprint&footPrint=' + footPrint + '&ref=' + goUserId + '&json=1',
dataType: 'json',
success: function(data){
var textError = data.error;
var textAction = data.action;
var textList = data.list;
if (textError == 'post_twice' || textError =='footprint_empty' || textError == 'login_req') {
// display the error.
} else {
// lets fade out the item and update the page.
}
});
return false; });
Try set cache to false. From http://api.jquery.com/jQuery.ajax/
cache Boolean
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser. Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.
I found out through a process of elimination that the error was being caused by invalid data being passed to the query string.
The line:
data: 'do=leave_footprint&footPrint=' + footPrint + '&ref=' + goUserId + '&json=1',
I noticed that the footPrint variable would always break the script if '??' was passed. A number of members when asking a question would use a '??' when and not a single '?'
By wrapping the footPrint var in encodeURIComponent() I can send all the text though to the PHP script without breaking the URL string.
New Line:
data: 'do=leave_footprint&footPrint=' + encodeURIComponent(footPrint) + '&ref=' + goUserId + '&json=1',
This solution has worked for me... questions comments and suggestions still welcome.

Ajax not sending data at all

im working on a script that sends a few data stored using GET to a PHP script(process it then put it into database).
here's the ajax script , im using jQuery ajax
(i have included the latest jQuery script)
function send(){
$.ajax({
type: "GET",
url: "http://examplewebsite.com/vars/parse.php",
data: "id=" + id + "&purl=" + purl + "&send" + "true",
cache: false,
success: function(){
alert("Sent");
}
});
}
id and purl are JavaScript variables .
send() function is set in :
Send
PHP code:
<?php
//Connect to database
include ("config.php");
//Get the values
$id = $_GET['id'];
$purl = $_GET['purl'];
$send = $_GET['send'];
if ($send == 'true') {
$insertdata = "INSERT INTO data (id,purl,send) VALUES ('$id','$purl',+1)";
mysql_query($insertdata) or die(mysql_error());
} else {
//do nothing
}
?>
when i type http://examplewebsite.com/vars/parse.php?id=123&purl=example&send=true
it works, the php injects the data into the database as i wanted but when i use send() and wanted to use ajax to send the data, failed.
Is there any mistakes that im making?
You're missing the = after send,
function send(){
$.ajax({
type: "GET",
url: "http://examplewebsite.com/vars/parse.php",
data: "id=" + id + "&purl=" + purl + "&send=" + "true",
cache: false,
success: function(){
alert("Sent");
}
});
}
should fix it, also. post more information about your javascript. We just have to assume id and purl are filled out. Did you try debugging them (if this doesn't work).
Also, debug the URL that is requested, you can use firefox or chrome dev-tools for this. What url is being send to the PHP page and is it correct
missing "=" in the data string.
data: "id=" + id + "&purl=" + purl + "&send" + "true",
should be
data: "id=" + id + "&purl=" + purl + "&send=" + "true",
It depends where you are running your script, because ajax calls are not meant to work on other domains. If you need to run the js on http://example1.com and the call to go to http://example2.com you need another approach.
An idea is to use json
Try
data: { id: id, purl: purl, send: true }
See if that makes any difference
First, i suggest (if you use Chrome or Safari) to use the Web Inspector (Right Click anywhere - inspect element) and then press ESC to show to console, this will assist you in validating your JS code. That would show you you have a '=' missing.
Second, i would try something a bit more simple just to make sure you get to the file.
JS:
// Don't forget encoding the data before sending, this is just a simple example
$.get("parse.php?sent=true",
function(data){
alert("I think i got a nibble...");
alert(data);
}
);
On the php file :
$sent = (isset($_GET['sent']) && !empty($_GET['sent']))?$sent:false;
if($sent) echo 'whatever data you want back';
Just make sure that you actually get the alert, and if so , move on from there to build the PHP file as needed for your data.
Hope this assists,
Shai.

JQuery ajax php post problem

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

Categories