I'm fetching a row of data from a mysql-server using php, then encode it to a json array. I then pull the information using the following PHP. The strange part is that if I send "vname" to it's own div, I get "NaN" as a result. If I display it in the first div, everything turns out fine. Any idea why? Btw, is it right of me to use .html to send to the div? I've tried .appendTo and .text with the same result.
<h3>Output: </h3>
<div id="output">Content1</div>
<div id="username">content2</div>
<script id="source" language="javascript" type="text/javascript">
$(function() {
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data) {
var id = data[0];
var vname = data[1];
var message = data[2];
var timestamp = data[3];
$('#output').html(+id + timestamp + message);
$('#username').html(+vname);
}
});
});
</script>
I;m going to guess its because of the first +. Javascript is trying to add nothing to all of the other stuff, which would output a NaN
$('#output').html(id +timestamp +message );
$('#username').html( vname );
In this case text() might be a better to use because there aren't any html elements in your strings, but it really doesn't matter.
+variable is shorthand for casting a variable to a number: Unary plus/minus (MDN)
var x = "5";
+x; //Gives you 5 as a number
x = "Hello";
+x; //Gives you NaN
You can use regular append.
$('#output').append(id + timestamp + message);
$('#username').append(vname);
$('#output').html(+id + timestamp + message);
$('#username').html(+vname);
These are probably your problem. The plus sign in front of the variables would throw an error. If you are trying to concatenate (add together) the existing the value and your response from the ajax change it to some thing like this:
$('#output').html($('#output').html() + id + timestamp + message);
$('#username').html($('#username').html + vname);
Related
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 },
I have a php page which includes the following javascript:
<script>
$(document).ready(function(){
$('#search').hide();
});
$('#L1Locations').live('change',function(){
var htmlstring;
$selectedvalue = $('#L1Locations').val();
$.ajax({
url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
type:'GET',
dataType:'json',
success: function(returnDataFromController) {
alert('success');
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=[returnDataFromController];
alert('string length is' + JSONdata.length);
if(JSONdata.length > 0)
{
for(var i=0;i<JSONdata.length;i++){
var obj = JSONdata[i];
for(var key in obj){
var locationkey = key;
var locationname = obj[key];
htmlstring = htmlstring + "<option value='" + locationkey + "'>" + locationname + "</option>";
}
}
$('#l2locations').html(htmlstring);
}
else
{
alert('i think undefined');
$('#l2locations').html('');
}
}
});
$('#search').show();
});
</script>
what i'm trying to accomplish is dynamically show a combo box if the variable "returnDataFromController" has any items.
But I think I have a bug with the line that checks JSONdata.length.
Regardless of whether or not the ajax call returns a populated array or an empty one, the length always shows a being 1. I think I'm confused as to what is counted when you ask for the length. Or maybe my dataType property is incorrect? I'm not sure.
In case it helps you, the "console.log(returnDataFromController)" line gives the following results when i do get data back from the ajax call (and hence when the combo should be created)
[16:28:09.904] ({'2.5':"Admin1", '2.10':"Admin2"}) # http://myserver/myapp/index.php/mycontroller/getbranches:98
In this scenario the combo box is displayed with the correct contents.
But in scenario where I'm returning an empty array, the combo box is also created. Here's what the console.log call dumps out:
[16:26:23.422] [] # http://myserver/myapp/index.php/mycontroller/getbranches:98
Can you tell me where I'm going wrong?
EDIT:
I realize that I'm treating my return data as an object - I think that's what I want because i'm getting back an array.
I guess I need to know how to properly check the length of an array in javascript. I thought it was just .length.
Thanks.
EDIT 2 :
Maybe I should just chagne the results my controller sends? Instead of returning an empty array, should I return false or NULL?
if (isset($buildingforbranch))
{
echo json_encode($buildingforbranch);
}
else
{
echo json_encode(false);
}
EDIT 3:
Based on the post found at Parse JSON in JavaScript?, I've changed the code in the "success" section of the ajax call to look like:
success: function(returnDataFromController) {
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=returnDataFromController,
obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
alert(obj);
}
But i'm getting an error message on
[18:34:52.826] SyntaxError: JSON.parse: unexpected character # http://myserver/myapp/index.php/controller/getbranches:102
Line 102 is:
obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
The problem was that the data from the controller is malformed JSON.
Note the part of my post where I show the return data:
({'2.5':"Admin1", '2.10':"Admin2"})
The 2.5 should be in double quotes not single quotes.
I don't understand how / why this is happening but I will create another post to deal with that question. Thanks everyone.
Used this script many times to pass 1 or 2 values to a PHP file, works fantastic. Using it now to pass 7 values and only the first 2 get through.
$(document).ready(function(){
$("form#send_note").submit(function() {
var to_user = $('#to_user').attr('value');
var from_user = $('#from_user').attr('value');
var defaultpic_from = $('#defaultpic_from').attr('value');
var defaultpic_to = $('#defaultpic_to').attr('value');
var your_username = $('#your_username').attr('value');
var message_title = $('#message_title').attr('value');
var message_contents = $('#message_contents').attr('value');
$.ajax({
type: "POST",
url: "../inbox/send_note.php",
data: "to_user="+ to_user +"& from_user="+ from_user + "& defaultpic_from="+ defaultpic_from + "& defaultpic_to="+ defaultpic_to + "& your_username="+ your_username + "& message_title="+ message_title + "& message_contents=" + message_contents,
success: function(){
$('form#send_note').hide(function(){$('div.success2').fadeIn();});
}
});
return false;
});
});
I have double checked all of the names, all is in order it's just the values after from_user (defaultpic_from) and so on won't go through.
I believe it's the way I have the "data:" listed. I am a complete newbie when it comes to javascript so any advice on the properway to get these through would be fantastic!
1) you know with jquery you can just do this, right?
var defaultpic_from = $('#defaultpic_from').val();
2) also, you don't need to turn the & into an entity, but as mentioned, you should be using encodeURIComponent in the values
3) have you verified all the variables actually have values before the ajax request gets made? what happens when you look in POST? Are you getting the members in POST, but no values? or no keys and no values?
4) Try using Chrome's Network tab in the developers tools to examine the request and response
here is an example I am using now, where params is nvp string and sync is true
var callService = function(sync, params, successCB, errorCB){
console.log('ENTER callService');
$.ajax({
type : 'POST',
url : 'required/core/Service.php',
async : sync,
data : params,
dataType : 'json',
success : function(data){
console.log('ENTER POST SUCCESS');
successCB(data);
},
error : function(){
console.log('ENTER POST ERROR');
errorCB();
}
});
};
what would be really helpful if you could go into the request and response headers and show them to us. you could have PHP echo
echo json_encode($_POST);
to make it easier to get the response
I bet the value of your default pic is terminating the query string. You can wrap your vars like this to ensure they are properly escaped:
$(document).ready(function(){
$("form#send_note").submit(function() {
var to_user = encodeURIComponent($('#to_user').attr('value'));
var from_user = encodeURIComponent($('#from_user').attr('value'));
var defaultpic_from = encodeURIComponent($('#defaultpic_from').attr('value'));
var defaultpic_to = encodeURIComponent($('#defaultpic_to').attr('value'));
var your_username = encodeURIComponent($('#your_username').attr('value'));
var message_title = encodeURIComponent($('#message_title').attr('value'));
var message_contents = encodeURIComponent($('#message_contents').attr('value'));
$.ajax({
type: "POST",
url: "../inbox/send_note.php",
data: {to_user:to_user, from_user:from_user, defaultpic_from: defaultpic_from, defaultpic_to:defaultpic_to, your_username:your_username, message_title:message_title, message_contents:message_contents},
success: function(){
$('form#send_note').hide(function(){$('div.success2').fadeIn();});
}
});
return false;
});
});
You will need to urldecode the post vars in php but that should do it.
I have a table which I can dynamically add and delete any number of rows to. Once the data is all entered by the user I am using the jQuery AJAX functionality to POST it to a mysql database so there is no page redirect or refresh.
The only way I could think of getting it to work was using this for loop in my jQuery, effectively posting each row to the database separately. How dumb is this? Should I be getting all the table data and posting it once? There could be any number of rows varying on user and the user could add and delete rows as much as he wants before submitting.
The strange i variable counting is due to there being two th rows at the top of the table. I couldn't work out a smart way of doing this.
I was a bit paranoid about the data always being associated with the correct row.
Thankyou for your time.
jQuery(function() {
jQuery(".button1").click(function() {
// process form here
var rowCount = jQuery('#dataTable tr').length;
for (var i = 2; i < rowCount; i++){
// the four elements of each row I am storing to the mysql
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
var dataString = 'txtRow1='+ txtRow1 + '&tickerRow1=' + tickerRow1 + '&quantRow1=' + quantRow1 + '&valueRow1=' + valueRow1;
//alert (dataString);return false;
jQuery.ajax({
type: "POST",
url: "http://rccl.co.uk/form_action1.php",
data: dataString
});
};
return false;
});
});
It looks very clearly to me as if you have a well-established index of the row in question, using your variable i. Most form handlers server-side will unpack repeated keys of the form into a list, for stuff like many checkboxes with the same name. You could exploit that here.
datastring = '';
for(var i=2; i<rowCount; i++) {
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
dataString = datastring + 'index[]=' + (i-1) + 'txtRow1[]='+ txtRow1 + '&tickerRow1[]=' + tickerRow1 + '&quantRow1[]=' + quantRow1 + '&valueRow1[]=' + valueRow1;
}
Then make the ajax call with the whole string.
On the server-side, you should get arrays for each of these, the first of each of which corresponds to the first row, the second of each of which corresponds to the second row, and so on.
It's been a long time since I used PHP, but I believe the [] symbols for each key item are necessary to clue PHP's $_POST that it should convert the various keys' contents into arrays.
I would try posting it all at once.
Reasons
fewer calls, less chance of your message getting lost in transit (your server rejecting requests because of flood)
you don't have to worry about requests responding out of order (maybe not an issue, but having an ass load of jumbled responses could potentially be an issue)
it will be faster for large numbers of rows getting saved at once
I have a checkbox on a webpage that when you click it, updates the value in the database as well as the editedBy and editedDate columns in a table in the database. I am doing the update via an ajax call to a php page. I am trying to get the updated editedDate and editedBy data in the callback on success so i can update the sorresponding span tags that hold this information. I'm trying to use jQuery to accomplish this. This is what i have so far:
var updateUserDate = function(data){
var table = data.table;
var rowId = data.rowId;
var editedDate = data.editedDate;
var editedBy = data.editedBy;
//alert(table+' - '+rowId+' - '+editedDate+' - '+editedBy);
$('"#'+table+' .row'+rowId+' .newEditedDate"').html('"'+editedDate+'"');
}
var submitDataCheckbox = function(target){
var project = target.attr('project');
var tableName = target.attr('table');
var rowId = target.attr('rowId');
var checkboxValue = (target.attr('checked'))?true:false;
$.ajax({
type: 'GET',
url: '/checklistpost.php?projectId='+project+'&table='+tableName+'&rowId='+rowId+'&value='+checkboxValue,
success: function(data){
updateUserDate(data);
},
error: function(){
alert('There was an error submitting data to the database.');
},
dataType: 'json'
});
}
The checklistpost.php page takes the variables that are in the query string and posts them to the database. It also then puts the variables in an array which is then encoded in json so that i have a json object to work with. Basically, i am trying to take that json object that gets called back and use it to update the span as mentioned above. When i have used an alert() inside of the updateUserDate function before to verify that i can see the variables and they all have the right data (you can see the code i used to do this is commented out). However, whenever i try and use the variables with jQuery as you see on the 6th line of the code. It doesn't do anything. BTW, The jQuery code that should be output based on what is written above should look like this $("#tableName .row1 .newEditedDate").html("April 14, 2011 # 5:15pm") What am i missing? Thanks in advance for any help!
Your selector is broken, you've got extra quotes in there:
'"#' + table+' .row' + rowId + ' .newEditedDate"'
should be:
'#' + table + ' .row' + rowId + ' .newEditedDate'
So:
// you're surrounding editedDate with extra quotes too, or is that intentional?
$('#' + table + ' .row' + rowId + ' .newEditedDate').html(editedDate);
Why are you using single and double quotes? The command you are passing to jQuery will evaluate to this:
$('"#tableName .row1 .newEditedDate"').html('"April 14, 2011 # 5:15pm"')
instead of this:
$("#tableName .row1 .newEditedDate").html("April 14, 2011 # 5:15pm")