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")
Related
I have a form that does a lookup on a database the lookup is done using load(). This is fine.
What I've like to do is to read the value of an input which is returned via the php.
I was thinking that I needed to use the .live() method but I'm not certain how.
My current code is:
var recordCount = $("input[name=noOfCusts]").val();
console.log("Number is " + recordCount)
So input[name=noOfCusts] is loaded from PHP so I can't get at it. I just get a value of undefined.
How do I roll live() into var recordCount = $("input[name=noOfCusts]").val();
Thanks
My load code is
$("input[name=findCust]").keyup(function(){
var key = $(this).val();
var type = 1;
$("div#CustomerResults").html("<img src='../images/loading.gif' alt='loading'/>").delay('500').load("../../ajax/customerFinder.php",{"key":key,"type":type}).fadeIn(300);
//#############################################
// Extra bit to make the search form work with a return
$("input[name=findCust]").live('keyup',function(){
var recordCount = $("input[name=noOfCusts]").val();
console.log("Number is " + recordCount)
});
//var recordCount = $("input[name=noOfCusts]").find("input[name=noOfCusts]").val();
//
//$('input[name="noOfCusts"]').val(data);
//console.log("Number is " + data)
//#############################################
});
Instead of returning an HTML input tag, return just the value for that input that is already present within HTML DOM.
Then in load call on success set the obtained value to that input:
// success
$('input[name="noOfCusts"]').val(data);
alert(data);
I want to do an update statement in my database, after an element gets dropped on a jQuery UI droppable element.
$("#pictures th div").droppable({drop: function(ev, ui) {
alert('You filled this box with a picture');
var this_id = $(ui.draggable).attr("alt");
var draggableId = ui.draggable.attr("id");
}
I know how to get the information (see the code above) I need, but how can I put them now into the database ?
Thank you !
At this point, you can use jQuery's $.post() method to post to a PHP file you've written. In the $.post(), you can pass the ids you would like to have written to your database.
So something like this:
$.post("/save.php", { imageId: this_id, draggedId: draggableId }, function (data) {
alert("success!");
});
Post the variable values to other page lyk this:
$.ajax({
type: "POST",
url: "data.php",
data: "Cat=" + id + "&Wid=" + WID
});
and then on data.php page get the values lyk this:
$Cat=$_POST['Cat'];
$WID=$_POST['Wid'];
simply store them in database by using insert query,hope it will help you.
I am having a problem that I cannot figure out.
I am using the tableDND jQuery add in, which allows me to drag and drop rows of a table. I want to send those rows to the server and have them uploaded to a mySQL database.
My code is below, basically when I get to the PHP the first element of the batting variable is gone. Any ideas?
So I have the following javascript:
$('#order').tableDnD({
onDrop: function(table, row) {
var batting = $.tableDnD.serialize();
var id = <?php echo $id;?>;
$.ajax({
type: 'POST',
url: 'update_batting.php',
data: '{ "batting":' + batting + ', "id":'+ id +' }',
dataType: 'json',
});
}
});
and the following php:
<?php
$batting = json_encode($_POST['order']);
$query = "INSERT INTO test (t) VALUES ('$batting')";
mysql_query($query);
?>
Ok so this is my crude guess at this one since I have to go soon...
I think since "data" is converted to a query string it is being misread.
I think your post is probably reading this:
$_POST['batting'] = 'order[]=110209';
$_POST['order'] = 'order[]=100245&order[]=100007&order[]=100296&order[]=100213&order[]=100071&order[]=100125&order[]=110206&order[]=110205&order[]=100152&order[]=100247&order[]=100329&order[]=100299&order[]=100243';
$_POST['id'] = '662852670';
Because the first occurrence of the ampersand is terminating your variable.
It might seem silly, but you can probably escape this whole problem by surrounding "batting" with double quotes. Effectively containing it as a string.
data: '{ "batting":"' + batting + '", "id":'+ id +' }',
This would change your expected $_POST['order'] variable to "$_POST['batting']
However, your data object should be contained like I originally mentioned in the comment above.
data: {order: '"' + batting + '"', id:id},
Instead of sending it as a string with no key as in your sample code.
Try var_dump($_POST) in php to see all values you're getting... just out of curiosity.
**Sorry for all the edits. I'm being distracted constantly at work...
Have you tryed to remove the spaces on each side of ' + batting + ' ....
like '+ batting +'....
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);
I've googled around, but i can find a way to build json with jQuery and send it to php using a for loop. I have a html table, and i want to take values from each row (i dont know how many rows/values there will be) construct a json string, ie. [{"row": 1, "supp_short_code" : blah blah....}, {"row": 2, ....} ....]
but i dont know how to keep adding to the json datastring each time jQuery finds more values if that makes sense??
EDIT:
So if i have this
$('#submit').live('click',function(){
var supp_short_code=$('.supp_short_code').text();
var project_ref=$('.project_ref').text();
var om_part_no=$('.om_part_no').text();
var description=$('.description').text();
var cost_of_items=$('.cost_of_items').text();
var cost_total=$('.cost_total').text();
var dataString = 'string=//' + supp_short_code + '//' + project_ref + '//' + om_part_no + '//' + description + '//' + cost_of_items + '//' + cost_total
$.ajax
({
type: "POST",
url: "order.php",
data: dataString,
cache: false,
success: function()
{
alert("Order Submitted");
}
});
});
So what (roughly) would i need to change in this code?
Ok, so as you can see by the screenshot, i'm using jquery to dynamically add the bottom table when a user click a row from the top table, its calculating totals and they can specify which supplier they want to use. I'm then using jquery to grab these values into the $('submit') bit of jquery code at the top. I then want to send these values to a php page that will somehow parse the received data at insert it into a mysql db, as something like "id 1 product blah price blah supplier blah total cost £x, id 2 product blah2 price blah2 supplier blah total cost £x" so some fields, ie the total cost and supplier will be the same, but the php might be receiving 3 different products for the same order if that makes sense? Thanks!
You don't need to build the json, just build the data array and send it with .post, .get or .ajax. jQuery will take care of encoding the array for you:
var data = {};
for (var i = 0; i < 3; ++i) {
data['field' + i] = 'value' + i;
}
$.post ('http://mysite.com/page', data, function() { alert('succes!'); });
Your server-side code's $_POST array will containing:
array( 'field1' => 'value1', 'field2' => 'value2', 'field3' => 'value3');
For your example, I would reconsider sending the data as a string and instead send the data as well-formated key/value pairs. Your server-side code can more easily decide what to do with it, and your JS won't require a rewrite if the server-side code needs the string to be built differently.
$.ajax ({
type: "POST",
url: "order.php",
data: {
supp_short_code: $('.supp_short_code').text(),
project_ref: $('.project_ref').text(),
om_part_no: $('.om_part_no').text(),
description: $('.description').text(),
cost_of_items: $('.cost_of_items').text(),
cost_total: $('.cost_total').text()
}
//...
});
Update
You could reduce the amount of typing by throwing your field names into an array, and appending the class name of any fields you want to include in the data array. Then loop over each of your table rows and extract the values:
var fields = [ 'supp_short_code', 'project_ref', 'om_part_no',
'description', 'cost_of_items', 'cost_total'];
var data = [];
// loop over each row
$('#my-table tr').each(function (i, tr) {
// extract the fields from this row
var row = {};
for (var f = 0; f < fields.length; ++f) {
row[fields[f]] = $(tr).find('.' + fields[f]).val();
}
// append row data to data array
data.push(row);
});
Here's a quick way to grab data from your table, and format it as an array:
var data_to_send = $('#yourtable').find('tr').map( function(idx){
return [
'row': idx+1,
'supp_short_code' : $(this).find('td').eq(2).text(),
'something_else' : $(this).find('td').eq(3).text() // etc
];
}).get();
Now you have data_to_send, an array formatted similarly to the example in your question. As #meagar points out, you can simply post this to the server with .ajax() et al., and allow jQuery to automatically handle the encoding. Something like this:
$.ajax ({
type: 'post',
url: 'your_script',
data: data_to_send
});