I think what I want to do is really simple but can't get it to work. I'm looping through a table and getting some values from the existing rows, that part works. Then I'm using AJAX to try and make a multidimensional array without duplicates but something isn't working. What I really want to do is delete the duplicate part, reorder the array and array_push new values. Here's what I have:
AJAX:
function getData(){
$("#table .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
$.ajax({
type: "POST",
async: false,
data: {key: key, s: sel, q: q}
});
});
}
PHP:
if(isset($_POST['key'])){
$title = $_POST['key'];
$s = $_POST['s'];
$q = $_POST['q'];
if(!empty($_SESSION['check'])){
foreach ($_SESSION['check'] as $key=>$value){
if(in_array($title, $value)){
unset ($_SESSION['check'][$title]);
$_SESSION['check'] = array_values($_SESSION['check']);
array_push($_SESSION['check'], array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
}else{
$_SESSION['check'] = array(array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
Is there something wrong with the logic? It seems like it should work. The same foreach loop works when trying to delete a table row. It finds the correct KEY and deletes it. Why doesn't it work here?
Here's the answer I got by hours and hours of searching. I avoided using serialize since...well I don't understand how to use it. In JS I'm looping to find values in the table and making an array like this:
function getData(){
var checkArray = new Array();
$("#shopCart .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
checkArray.push(key);
checkArray.push(sel);
checkArray.push(q);
});
$.ajax({
type: "POST",
data: {ch: checkArray}
});
}
In my PHP is where I found a cool trick. Since I'm controlling the data in the array, I know how many values will be in it. The trick I found is "array_chunk" so for the 3 values I'm doing this:
if(isset($_POST['ch']) && (!empty($_POST['ch']))){
unset($_SESSION['check']);
$_SESSION['check'] = array_chunk($_POST['ch'], 3);
}
So I'm just clearing the session variable and adding the new values. That eliminates all the checking and clearing and all that. I'm sure there are better ways to do this but this method is short and works and that's what I'm looking for. Hope this helps someone!
Related
So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.
I attempt to fill a drop down from a database. I query and add my result to an array. I then use json_encode to send my data to a php file.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => $proj_option);
echo json_encode($output);
In my php file, I use jquery ajax to fill the drop down.
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
This is great, BUT the only item in my drop down is the last item in the db. For example, my database has the following under Project:
Project: up, down, low, right
But my drop down only fills with the last entry, "right." Why is this? How can I fix it?
PHP json_encode() in while loop was similar, and I made the changes, but there is something missing here.
may be try this
success:function(response) {
$.each(response.proj,function(key,value){
$("#exp").append(value);
$("#project").append(value);
});
}
each time thru your loop in javascript you are overwriting your html. The .html() method sets the innerHTML property of the tag, so each time you call it you are resetting the html and only the last one will show. try not using a loop, instead join you response together and then call .html()
$("#exp").html(response.proj.join(''));
$("#project").html(response.proj.join(''));
hello friends i m trying to make a inbox system in which we select all checkbox with the help of one checkbox and then through ajax pass the value to all checkbox and update the database. but the problem is that they values and being selected one by one and then forming a array
for eg
fst time 2
second time 2,3
third time 2,3,4
and at the sql query where i am trying to get the list of array and break them so that i can update the value in database its also not happening , can anyone help ?here is what i coded.
to get the value of checkbox
$(function(){
$('.massmsgdelbutton').click(function(){
var val = [];
$('.sltchk:checked').each(function(i){
val[i] = $(this).val();
var dataString = 'massmsgdel='+ val;
if(confirm("Sure you want move all these messages to Trash? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "modules/messages/sql_ex.php",
data: dataString,
cache: false,
success: function(html){
alert(html);
}
});
}
});
});
});
my sql code using expode to explode the array
if(isset($_REQUEST['massmsgdel']))
{
$id=$_REQUEST['massmsgdel'];
$myArray[] = explode(',', $id);
echo $id;
$sql=mysql_query("update message set trash='1' where message_id='$myArray'");
}
Well, there are really two approaches you can use here. From my experience, anyway.
You can either loop through the array(foreach loop) you have and perform an UPDATE each time, something like the following:
$sql=mysql_query("update message set trash='1' where message_id='$messageID'");
Or you could try using the IN SQL Operator(which you can find more info on here), something like so:
$sql=mysql_query("update message set trash='1' where message_id IN ('$messageID1', '$messageID2', '$messageID3', '$messageID4')");
The IN Operator will match the message_id to any of the parameters in the parenthesis.
Does it work?
if(isset($_REQUEST['massmsgdel']))
{
$id=$_REQUEST['massmsgdel'];
$myString = implode(',', $id);
echo $id;
$sql=mysql_query("update message set trash='1' where message_id IN ($myString)");
}
guys i found the solution .
in the jquery i had to use
var dataString = 'massmsgdel='+ val[i];
instead of
var dataString = 'massmsgdel='+ val;
and in sql i had to use
$sql=mysql_query("update message set trash='1' where message_id IN ('$myArray')");
thanks #Frank Allenby for helping me the way out
With thanks to Elf Sternberg (I couldn't get your solution working, sorry), I think I am heading in the right direction, but I am having trouble writing the php to the mysql database.
The original post: jQuery AJAX POST to mysql table for dynamic table data- Am I doing this in anything like the right way?
Firstly, the dynamic table form on my webpage has multiple user input data, and I am using this jQuery function and the AJAX call to send to a php file. Am I correctly creating the multidimensional array here? Firebug shows dataString to have all the data I want, but the POST parameters and source just say dataString. Also the alert function shows the data is all there:
EDIT: With thanks to Jancha and Andrew, I have changed the data source for the AJAX post. The database is being written to now, but only BLANK data gets written, for as many entries as were in the table. The firebug console is showing all the data as it should look in the post. I just don't know how to structure the php loop now.
jQuery(function() {
jQuery(".button1").click(function() {
// process form here
var rowCount = jQuery('#dataTable tr').length;
var dataString = [];
dataString.length = rowCount - 2;
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();
// previous code: dataString[i-2] = 'txtRow1='+ txtRow1 + '&tickerRow1=' + tickerRow1 + '&quantRow1=' + quantRow1 + '&valueRow1=' + valueRow1;
// new code:
dataString[i-2] = [txtRow1, tickerRow1, quantRow1, valueRow1];
}
//alert (dataString);return false;
jQuery.ajax({
type: "POST",
url: "form_action2.php",
data: { 'data': dataString }
});
return false;
});
});
If this is sending the data okay then I am thinking that the php function needs to look something like this:
Could I have help with the php function please. Thankyou for your time.
$data = $_POST['data'];
foreach ($data as $key => $value){
$txtRow1 = $data['txtRow1'];
$tickerRow1 = $data['tickerRow1'];
$quantRow1 = $data['quantRow1'];
$valueRow1 = $data['valueRow1'];
$sqlinsert = "INSERT INTO stock_port (name, ticker, quantity, value) VALUES ('$txtRow1', '$tickerRow1', '$quantRow1', '$valueRow1')";
mysql_query($sqlinsert, $conn);
}
FINAL EDIT: Ok so this works to enter the data into the database:
$data = $_POST['data'];
foreach ($data as $value){
$txtRow1 = $value[0];
$tickerRow1 = $value[1];
$quantRow1 = $value[2];
$valueRow1 = $value[3];
$sqlinsert = "INSERT INTO stock_port (name, ticker, quantity, value) VALUES ('$txtRow1', '$tickerRow1', '$quantRow1', '$valueRow1')";
mysql_query($sqlinsert, $conn);
}
It seems using data: {'data':dataString} in the AJAX jQuery call means I lost all the variable names of the data sent in the array to POST. Even though this is working, it doesn't feel like the way it should have been done. I have seen others use array structure in their id or names for input on forms, and that seems like it should have been the way to go.
change data: "dataString" to data: dataString or else you are not passing variable but a 'string'.
there is a problem with your foreach statement try this
$data = $_POST['datastring'];
foreach($data as $key => $value){
$txtRow1 = $data['txtRow1'];
}
It is not tested still you try once
Okey, this is what I've got.
<?php
$options[1] = 'jQuery';
$options[2] = 'Ext JS';
$options[3] = 'Dojo';
$options[4] = 'Prototype';
$options[5] = 'YUI';
$options[6] = 'mootools';
That is my array, but I'd like to make it a bit more dynamic so that the array is built according to input id, so he won't have to change the php-code whenever he want's another poll. How would I import those input id's and push them into an array?
To the extent I can understand your question, you could use JSON to pass the data from the client to the server like this:
JAVASCRIPT (using jQuery):
var arr = [];
arr.push("option1");
arr.push("option2"); // and so on..
//Use AJAX to send the data across ..
$.ajax({
url: 'poll.php?jsondata=' + encodeURIComponent(JSON.stringify(arr)),
success: function(data) {
// response..
}
});
});
I think that PHP script will put those options into a database or something for using it later on.
Now, in PHP(poll.php):
<?php
$options = json_decode($_GET['jsondata']);
//...
?>