Build json to send to php using a for loop (maybe) - php

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

Related

Pass JS Array to server through $.ajax call

Here is my piece of code :
$('#addType').on('submit', function(e) {
$form = $(this);
var type = [];
$(this).find('input[type=number]').each(function() {
type[$(this).attr('id')] = $(this).val();
});
console.log(type);
$.ajax({
type: 'POST',
url: '<?php echo $this->url(array(), 'addType');?>',
data: {type: type},
success: function() {
$form.find('input[type=submit]').attr('disabled','disabled');
}
});
e.preventDefault();
});
As you can see, it builds an javascript array from the inputs in form#addType and send it to a server side script supposed to handle this array. My problem is that no data is passed through $.ajax({}).
UPDATE
It seems that it comes from the values of the array keys that cannot by litteral. If I put an incremented number as key, the array is successfully passed. How come?
Make the type an object, not an array:
var type = { };
You created type as an array (using []). Array is an object, too, so You can add named members to it, which is what You do in Your loop:
type['my-item-id'] = xxx;
But when You add the type variable to the Ajax request, jQuery checks that the variable is an array and so it iterates through the type as trough an array, so it looks for it's "numerical-indexed" items using type.length (which is 0 as You added none):
for (var i = 0; i < type.length; i++)
... type[i] ...
When You create type as an Object (using {}), jQuery sees that it should iterate over type as over an object and does it so and "sees" the "named" items:
for (var i in type)
... type[i] ...

jQuery Looping JSON Data

I have created APIs to retrieve data from my server and then I get the data with json format like this :
{
"items": [
{
"2013-03-28": 1771,
"2013-03-29": 1585,
"2013-03-30": 1582,
"2013-03-31": 1476,
"2013-04-01": 2070,
"2013-04-02": 2058,
"2013-04-03": 1981,
"2013-04-04": 1857,
"2013-04-05": 1806,
"2013-04-06": 1677,
"2013-04-07": 1654,
"2013-04-08": 2192,
"2013-04-09": 2028,
"2013-04-10": 1974,
"2013-04-11": 1954,
"2013-04-12": 1813,
"2013-04-13": 1503,
"2013-04-14": 1454,
"2013-04-15": 1957,
"2013-04-16": 1395
}
]
}
How do I looping with my json data dynamically using jQuery?
My code :
<html>
<head></head>
<body>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type : "GET",
url: "myurl.php",
cache: false,
dataType: "jsonp",
success:function(data){
if(data==''){
alert('Fail');
}else{
alert('Success');
}
}
})
});
</script>
</body>
</html>
How do I modify my jQuery to get data dynamically following the date that the data will change every day as in the example I wrote above data??
Thanks before...
There are a few things to consider with your example data, but in your case, the following will do the trick:
var importantObject = data.items[0];
for(var item in importantObject ){
var theDate = item;//the KEY
var theNumber = importantObject[item];//the VALUE
}
Here is a working example
But what does all this mean?...
First of all, we need to get the object that we want to work with, this is the list of dates/numbers found between a { } (which means an object) - an array is defined as [ ]. With the example given, this is achieved like so:
var importantObject = data.items[0];
because items is an array, and the object we want is the first item in that array.
Then we can use the foreach technique, which effectively iterates all properties of an object. In this example, the properties are the date values:
for(var item in importantObject ){ ... }
Because we are iterating the properties, item will be the property value (i.e. the date bit), so item is the date value:
var theDate = item;//the KEY
Finally we get the number part. We can access the value of any given object property by using the string value of the property index (relative to the object), like so:
var theNumber = importantObject[item];//the VALUE
If you already know which date you want the value for, then you can access it directly like so:
var myValue = data.items[0]["2013-04-16"];//myValue will be 1395 in this example
Using jQuery.each() loop through the items
$.each(data.items[0], function (key, value) {
console.log(key + ": " + value);
var date = key;
var number = value;
});
DEMO HERE
You can use the jQuery each function to do this. For example like this:
$.each(data, function(k, v) {
// Access items here
});
Where k is the key and v is the value of the item currently processed.
//get your detail info.
var detail = data.items[0];
$.each(detail, function(key, val) {
console.log(key + ": " + val);
}

How to get text filed value in ajax?

I have a table with dynamic data from database, each row consist of a text filed and 2 link (accept or reject). then if user clicks on any of these link, the row will disappear and the rest of the rows are only visible in table.
I get ID of each row with ajax by clicking on each link, however I also need to get the text-field value.
how can I get it?
I need to have in ajax cause after getting value I need to insert in database with php+sql.
this is my ajax part for link:
$('a.accept').click(function(d) {
d.preventDefault();
var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'Test.php',
data: 'ajax=1&accept=' + parent.attr('id').replace('record-',''),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
});
how can I include text filed value in it?
please comment me which I'm really in need to solve it,
Thanks
You can add manually your text to the GET request.
(snippet)
data: 'ajax=1&accept=' + parent.attr('id').replace('record-','') + '&text=VALUE',
Substitute text with the name you want to be received in PHP. Substitute VALUE with the text entered on the page that you want to grab - and don't forget to encode the value.
You will need the name of id of the textfield first. Then you could do something like this:
var textboxvalue = $('name or id of textfield').val();
Then you will need to append this value to your data string:
data: 'ajax=1&textvalue='+textboxvalue+'accept=' + parent.attr('id').replace('record-',''),
Then you can use $_GET['textvalue']; to get the value of textbox.
Use following and you're good to go. Also you had extra '});' at the end line of JS fragment. I had it removed. But make sure you give id to text fields in following pattern : text-fld-RECORD_ID where RECORD_ID is the ID of the record.
$('a.accept').click(function(d) {
d.preventDefault();
var parent = $(this).parent();
var id = parent.attr('id').replace('record-','');
//make sure that text field has ID in pattern 'text-fld-RECORD_ID'
var text_fld = $('#text-fld-'+id).val();
$.ajax({
type: 'post', // I suggest using post; get will be harmful in such occasions
url: 'Test.php',
data: {ajax:1,accept:id,text:text_fld},
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});

Json getting "Undefined" values in my Listbox

The user is required to click on an actor from a actors list. The existing movie titles are removed and then only movies titles pertaining to the chosen actor show.
My "dvdtitle" listbox receives a list of "Undefined" after an actor is chosen. However I checked the response data from json_encode function with $('#actor').text(data) to get it visual and I do get correct.
[{"503":"Caught In The Crossfire"},
{"690":"Dead Man Running"},
{"1064":"Get Rich Or Die Trying"},
{"1145":"Gun"},{"1254":"Home of The Brave"},
{"2184":"Righteous Kill"},
{"2519":"Streets Of Blood"},
{"3273":"Twelve"}]
I don't know what I'm doing wrong.
//getactors.php
include("includes/connection.php");
$q = $_POST['input'];
$final_array = array();
$resultActor = mysql_query("SELECT id, title, plot, catagory, release_date, rated FROM dvd WHERE actors LIKE '%".$q."%' ");
while($rowActor = mysql_fetch_array($resultActor)) {
$final_array [] = array( $rowActor['id'] => $rowActor['title'] );
}
echo json_encode($final_array);
// JavaScript Document
$('#actorsname').click(function(){
var actorValue = $('#actorsname option:selected').text();
$.ajax({
type: "POST",
url: 'getactors.php',
data: {input: actorValue},
cache: false,
datatype: "json",
success: function(data) {
$('#dvdtitle option').each(function(i, option) {
$(option).remove(); // Empty DVD Listbox
});
$('#actor').text(data); // to visualy check my json Data
$.each(data, function(i, j) {
var row = "<option value=\"" + i.value + "\">" + j.text + "</option>";
$(row).appendTo("select#dvdtitle");
});
}
});
});
The problem is that your Ajax is returning an object containing one key/value pair with the movie ID as a key and the movie title as a value. This makes retrieving the data more difficult because you don't know in the each loop which ID to look for.
Ideally, you'd have your JSON formatted this way instead:
[
{"id":503,"title":"Caught In The Crossfire"},
{"id":690,"title":"Dead Man Running"}
]
That would allow you to retrieve the data in your each loop using j.id and j.title because the JSON uses "id" and "title" as keys. But because you don't have it organized that way, you need to loop through each key/value pairs of the object.
Ideally, you'd want to change your PHP to this:
$final_array[] = array(
'id' => $rowActor['id'],
'title' => $rowActor['title']
);
And use j.id and j.title (e.g. var row = "<option value=\"" + j.id + "\">" + j.title + "</option>";).
Here's an example without modifying your PHP code:
This example is based on your example above. The data variable is what's received in your Ajax request.
// This is the data retrieved using Ajax.
var data = [{"503":"Caught In The Crossfire"},{"690":"Dead Man Running"},{"1064":"Get Rich Or Die Trying"},{"1145":"Gun"},{"1254":"Home of The Brave"},{"2184":"Righteous Kill"},{"2519":"Streets Of Blood"},{"3273":"Twelve"}];
// Loop through each object in the data array.
$.each(data, function(key, movie)
{
// Because the ID is a key and the title a value, we can't determine the ID/title unless we loop through each one of the key/value pairs in the object. Each movie only has one key/value pair so this won't be a problem.
$.each(movie, function(id, title)
{
$('<option />').attr('value', id).text(title).appendTo('select#dvdtitle')
});
});
jsFiddle: http://jsfiddle.net/j7HGr/
I hope that makes sense.
PS: You may also want to change $q=$_POST['input']; to use mysql_real_escape_string to prevent SQL injections.
data is an array of objects. The value of i is the index of the object, and j is the object.
Here:
$.each(x, function(i, j){
$.each(j, function(k, v){
var row = "<option value=\"" + k + "\">" +v+ "</option>";
$(row).appendTo("select#dvdtitle");
});
});
You can see the jquery documentation for more information: http://api.jquery.com/jQuery.each/

jQuery ajax callback not firing jQuery code

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")

Categories