0

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? Screenshot

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!

2 Answers 2

5

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);
});
Sign up to request clarification or add additional context in comments.

6 Comments

I understand, but how do i know the number of times for it to loop over. The user may want 3 items (ie. 3 rows of data) or 45 items (45 rows of data)? Thats the bit thats confusing me...
@benhowdle Post some sample rows of HTML data and we can help you automate that part. There's no solution we can suggest without seeing the markup other than "Loop over the table and extract values".
Looks good! But as i mentioned, what if the data wasnt in a table row, would this affect your code above. Could i loop over a div (i'm not sure if thats a stupid question?)
@benhowdle You could loop over any series of DOM elements you can build a selector for.
"data.push is not a function" according to Firebug!?
|
2

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
});

2 Comments

thanks for this, but (due to being new at this) i havent got the data i want to send in one nicely formatted row in a table, more of i'm grabbing values from various elements, ie p tags, etc...so its a bit haphazard
@benhowdle89, if the data are not in a regular format, then you'd need to take an approach as in @meagar's answer (i.e., grabbing values manually).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.