php lost some path of string after submition using ajax post - php

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 },

Related

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.

Lacking of Serializing or Encoding

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/

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 php issue

Hey everyone. This one is puzzling me. I'm using PHP and Jquery. I am making an ajax request to a PHP file containing a get url. Eg. Path/to/file/?ID=369
The request goes out fine, I've watched it in fire bug.
However in the PHP file, the ID variable doesn't exist. When I do
var_dump($_GET)
I can see that there are two arrays inside the GET array. These are JSON and action.
Can anyone explain to me what's going on here and how I can receive my ID variable?
here are my codes:
<?php
$program_price_id = $_GET['id'];
$programDepatures = getProgramDepaturesGreaterThanToday($program_price_id);
echo "[{optionValue: 0, optionDisplay: 'Select a date'}";
while ($programDepartureData = mysql_fetch_array($programDepatures)) {
echo ", {optionValue: ".
$programDepartureData['id'].", optionDisplay: '".
tidyDateEnglish($programDepartureData['departure_date'])."'}";
}
echo "]";
?>
Best wishes,
Mike
i think you need to specify the ajax method you are using.It might be a $.ajax, $.get or $.getJson.
but i use $.ajax and here is a snippet
$.ajax({
url:"event/service_ajax_handler.php",
type: "GET",
data: {action:"getTime"},
dataType : "json",
success: function(data) {
$("#cmbTimeRange").html("<option value='-1'>Please select time range</option>");
$.each(data, function(){
$("#cmbTimeRange").append("<option value='"+ this.id +"'>" + this.hours +"</option>")
});
},
error: function(){
alert("error");
}
});
pay attention to the data parameter. see also
getJSON
This may be obvious, but I noticed in the sample URL you have ID capitalized, but in your PHP code you have it lowercase. PHP is case sensitive, so it could be as simple as that.

Jquery .val() not returning line-breaks in a textarea

I got problem with line breaks in a textarea.
I get the text with .val() function:
var messageBody = $('#composeInput').val();
This is my ajax request
$.ajax({
url: 'serverScripts/messages/addMessage.php',
data: 'messageBody='+messageBody+'&invitedJSONText='+invitedJSONText,
success: function(){
//Do something
}
});
And PHP:
$messageBody = nl2br(mysql_real_escape_string($_GET['messageBody']));
The text:
Hi!
How are you?
Becomes:
Hi! How are you?
If I insert the variable messageBody to an another div-element I can't see any \n is this normal. How do I fix this?
When you pass a string as the data parameter, you must URL encode it like this:
'messageBody=' + encodeURIComponent(messageBody) + '&invitedJSONText=' + encodeURIComponent(invitedJSONText)
If you pass the parameters as an object, jQuery takes care of encoding the data:
$.ajax({
url: 'serverScripts/messages/addMessage.php',
data: {
messageBody: messageBody,
invitedJSONText: invitedJSONText
},
success: function (data, textStatus, jqXHR) {
$("#foo").html(data); // <-- did something
}
});
You may want to look at PHP's nl2br function. Newlines characters do not render in the browser, so you have to replace them with line breaks.http://us.php.net/nl
Is not that a known issue?
http://api.jquery.com/val/
The workaround is using valHooks as explained in the Note section.

Categories