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

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?

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.

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/

Barcode reading values to textbox?

I have a barcode scanner which reads the string of the barcode and displays in the active text box. also there is no consistent end character to the barcode, or standard length (I have 5 diffent length sizes. 16,17,18,19,20). I need to extract values from scanned data. so extracting values also depend on the barcode length.
So how would I go about firing a method when the WHOLE string has been read in?
Im using php and ajax to do this.
$(document).ready(function()
{
$("#bcode").focus();
//prevents autocomplete in some browsers
$("#bcode").attr('autocomplete', 'off').keyup(function(event)
{
var name = $("#bcode").val();
$("#status").empty();
if(name.length > 17 ) `// need to check all possible length values like this`
{
selectAll();
$("#status").html('<img align="absmiddle" src="images/loading.gif" /> Checking availability...').show();
$.ajax({
type: "POST",
url: "namecheck.php",
data : "bcode=" + name,
success: function(msg)
{
$("#status").html(msg).show();
}
});
}
else
{
$("#status").html('').addClass('err').show();
}
});
});
I did some work with a card swiper, there are similar challenges there. The data comes in a rapid burst, but there isn't a consistent "end-of-data" string being sent. The solution is to use setTimeout and wait - when the input stops, then you fire your processing code.
Depending on your hardware, the amount of waiting you'll want to do varies. Experiment with this code, to adjust the wait time, simply adjust the duration argument of setTimeout. I've started it on 500ms - that works pretty well for the card swipers. Forgive me if there are any minor wobbles in my code here - I am not a jQuery guy :)
$(document).ready(function() {
$("#bcode")
.focus()
.attr('autocomplete', 'off')
.keyup(function(event){
// if the timer is set, clear it
if (barcode_watch_timer !== false)
clearTimeout(barcode_watch_timer);
// set the timer to wait 500ms for more input
barcode_watch_timer = setTimeout(function () {
process_barcode_input();
}, 500);
// optionally show a status message
//$("#status").html('waiting for more input...').show();
// return false so the form doesn't submit if the char is equal to "enter"
return false;
});
});
var barcode_watch_timer = false;
function process_barcode_input() {
// if the timer is set, clear it
if (barcode_watch_timer !== false)
clearTimeout(barcode_watch_timer);
// grab the value, lock and empty the field
var name = $("#bcode").val();
$("#bcode").attr('disabled', true);
// empty the status message
$("#status").empty();
// add a loading message
$("#status").html('<img align="absmiddle" src="images/loading.gif" /> Checking availability...').show();
// send the ajax request
$.ajax({
type: "POST",
url: "namecheck.php",
data : "bcode=" + name,
success: function(msg) {
// unlock the field, show a success status
$("#bcode").attr('disabled', false);
$("#status").html(msg).show();
}
});
}
Does it need to be a text area?
The last barcode reader I used always ended with a newline. If you are inputing into a <input type="text"/> the return char will likely try to submit the form, and you can use an onSubmit to capture the event and process your input.
Try observe the field with code by interval
Example
setInterval(function() {
var value = $("#code").val(),
prev_value = $("#code").attr("prev_value");
if (prev_value == value) {// compare with prevent value for detecting canges
console.log("value is not changed");
return;
}
//if (value.length < 17) {
//exeption
// or reset value $("#code").val(prev_value);
//return;
//}
if (value[value.length-1] == "\n") {// check last symbol
console.log(value);// Do something with you code eg send by AJAX
}
$("#code").attr("prev_value", value); // save current value for compare later
}, 1000 );

Categories