jQuery posts error text when posting with ajax - php

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.

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

Blank response message from JQuery .ajax() call is 13 characters in length?

I am using JQUERY .ajax() to send serialized form data to MySQL using PHP. The backend PHP being called will return a message if there was an issue processing the data. My Javascript function then checks for a message being returned before deciding what to do next. If the message length is '0', then the post was successful and it can carry on. If the message length > '0', then an error must have occured in the form processing, and it traps there to deal with it. However, when testing, I found that a successful processing of my form data, returned a message of size 13, even though the message itself was blank.
The javascript function I used is below. I have modified it to test for a message length of more than 13 characters, and this is working fine now. I' am just curious as to why a blank response is 13 characters in length. Ignore the complicated .load() statements, they just return the user to a different page depending on whether an error message was detected or not.
$("button#update").click(function() {
var cat = $("select#cat_select").val();
var dataString = $("form#project_update").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
dataType: 'text',
success: function( msg ) {
console.log('msg is ' + msg);
length = msg.length;
console.log('length is ' + length);
if (length > 13) { // no idea why a blank msg has a length of 13!!
alert(msg);
$("#main").load('?app=$app&func=$func&sub=ajax&ajaxSub=edit_project&cat=' + cat + '&proj_id=' + $proj_id).fadeIn('fast');
}
else {
$("#main").load('?app=$app&func=$func&sub=ajax&ajaxSub=project_detail&cat=' + cat + '&proj_id=' + $proj_id).fadeIn('fast');
}
}
});
return false;
});
Instead of
length = msg.length;
try with
length = msg.replace(/\s/g,'').length
Note
But you should make sure that there are no spaces or newlines within <?php and ?> tags, I would be better if you remove them.
Check for hard-coded spaces outside your <?php and ?> tags. I suppose the script calls itself via ajax, right?

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 Ajax error

I am posting some form values through ajax to a PHP script. The PHP echoes 1 if it's successful and 2 if not.
The PHP seems to be working ok but I am being redirected to the url in the javascript and shown the number 1 on a blank page instead of it being echoed back to the ajax request.
This is my javascript, can anyone see where I am going wrong?
$(".save").click(function() {
var area = $("input#area").val();
var january = $("input#january").val();
var target = $("input#target").val();
var ach = $("input#achieved").val();
var comments = $("input#comments").val();
var token = "<?php echo $token; ?>";
var dataString = 'area='+ area + '&january=' + january + '&target=' + target + '&achieved=' + ach + '&comments=' + comments + '&ci_token=' + token;
$.ajax({
type: "POST",
url: "review/update-review/<?php echo $yr; ?>",
data: dataString,
success: function(msg) {
if(msg == 1)
{
alert("Your review has been updated.");
}
else
{
alert("There was a problem updating your review. Please try again.");
}
}
});
return false; });
I think the problem may be down to the format of your data parameters. for
type : "POST"
then for
data : "{param1: 'param1', param2: 'param2'}"
do you have a tool like fiddler to view the communications between your browser and server. if not i would recommend downloading fiddler (it's free). it will give you a lot of insight as to what is actually happening behind the scenes and can give invaluable information about what might have gone wrong with an ajax style post.
The code looks pretty much fine to me, including the syntax. Still some possibilities arise, which are:-
The URL for executing the PHP code, which you are using in the example ("review/update-review/<?php echo $yr; ?>"), may be incorrectly given with reference to your current page.
The variables which you are using it here to capture the values of the INPUT elements, may be producing some extra special characters (like "&") which may lead to erroneous processing, resulting in the JavaScript problem.
Hope it helps.
For starters if(msg == 1) will not be == 1 because what your fetching is a string so it would b if(msg == '1').
Where you have
var dataString = 'area='+ area + '&january=' + january + '&target=' + target + '&achieved=' + ach + '&comments=' + comments + '&ci_token=' + token;
Change that to an object like so:
var dataObject = {
area : area,
january : january,
target : target,
achieved : ach,
comments : comments,
ci_token : token
}
and then change it in the ajax request to dataObject
Debug
Firefox: firbug.
if your using chrome hit Ctrl+Shift+J to open the javascript console and debug. look out for all the heaDers and data your sending and you can use console.log(varaible) to track the values of a variable.

Categories