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/
Related
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);
}
I have the following class in a php file:
function calcTotal(){
var productID = <?php echo $product_info['products_id'];?>;
var sizeID = 0;
$(".mine_sizes").each(function() {
if ($(this).is(':checked')) sizeID = $(this).val();
});
//alert(sizeID);
var colorID = 0;
$(".mine_color").each(function() {
if ($(this).is(':checked')) colorID = $(this).val();
});
$.ajax({
type: "POST",
url: 'get_product_price.php',
data: "product_id="+ productID +"&color_id="+ colorID +"&size_id="+ sizeID,
success: function( response ) {
$("#price_container").html(response);
;
}
});
}
and the php file get_product_price.php:
if($_POST){
$product_info_query = tep_db_query("select products_price, products_tax_class_id from " . TABLE_PRODUCTS . " where products_id = '" . (int)$_POST['product_id']."'");
$pricePrice = tep_db_fetch_array($product_info_query);
$productPrice = $pricePrice['products_price'];
$sizesPrices = tep_db_query("select options_values_price from products_attributes where products_id='".$_POST['product_id']."' and options_values_id='".$_POST['size_id']."'");
// echo "select options_values_price from products_attributes where products_id='".$_POST['product_id']."' and options_values_id='".$_POST['size_id']."'";
// exit;
if(mysql_num_rows($sizesPrices)>0){
$priceRow = tep_db_fetch_array($sizesPrices);
$productPrice = $productPrice + $priceRow['options_values_price'];
}
$sizesPrices2 = tep_db_query("select price from product_attributes_color_relation where product_id='".$_POST['product_id']."' and color_id='".$_POST['color_id']."' and color_size_option_id='".$_POST['size_id']."'");
if(mysql_num_rows($sizesPrices2)>0){
$priceRow2 = tep_db_fetch_array($sizesPrices2);
$productPrice = $productPrice + $priceRow2['price'];
}
//echo $productPrice; exit;
echo $currencies->display_price($productPrice, tep_get_tax_rate($product_info['products_tax_class_id']));
//echo $productPrice;
}
The function is called on a radio button click and is currently working but I am trying to understand how it works for myself (and to possibly recreate a similar function)
What I am not really understanding is the data parameter from the ajax api. How is that data parameter used?
another question I have is the success parameter. Is the "response" parameter a standard or can in be called anything?
Thanks for any help explaining this to me. I don't think any other information is necessary, there is a div with a class id #price_container which is where the price is echo'd.
The data parameter passes the information the same way an HTML form will. At least that's the easiest way to think of it. So that "data" will come through as $_POST or $_GET arrays. I always setup my data as JSON format:
data: { "product_id": productID,"color_id": colorID, "size_id": sizeID },
With your type set as "POST" that would come through as:
$_POST['product_id']
$_POST['color_id']
$_POST['size_id']
You can specify any variable name for the response - but 'response' is nice and easy to remember and work with. :)
from the ajax documentation
data
[Object, String]
Data to be sent to the server. It is converted to a
query string, if not already a string. It's appended to the url for
GET-requests. See processData option to prevent this automatic
processing. Object must be Key/Value pairs. If value is an Array,
jQuery serializes multiple values with same key based on the value of
the traditional setting (described below).
Basically if you set the data variable to a query string, it sends it to the server as is, other wise it will generate a query string from the key value pairs that you set. Once the php server receives the query string it is parsed and you can access your values using
$_POST['key']
i have a php file i have three dropdown in one php file like region province district so based on selecting region the provinces should be shown and based on the province the district should be shown so i want to implement these in one php file how to do that i can do it in different php file but i want to do it in one php file and the problem is that i can't pass the first dropdownlist value to the secand using ajax i want this in ajax.
if any one help me that will be highly appreciated.
thanks
This is what i usually do in php/ajax for region - province:
jQuery code:
$('#idRegion').change(function(){
if($(this).val() == ''){
$('#idProvince').attr('disabled', 'true');
}else{
var idRegione = $(this).val();
$.getJSON('index.php',
{
option: "com_spin",
controller: "guest",
task: "getProvincieByRegionId",
idRegione: idRegione
},
function(json){
$('#idProvince').html(json.html);
}
);
$('#idProvince').removeAttr('disabled');
}
});
PHP code:
function getProvincieByRegionId() {
Zend_Loader::loadClass ( 'Zend_Json' );
$idRegione = JRequest::getVar ( "idRegione" );
$modelProvince = new Spin_lkpprovincia ();
$provincie = $modelProvince->getElencoProvinciePerRegione ( $idRegione );
$html = "<option value=''>Selezionare una voce</option>";
foreach ( $provincie as $provincia ) {
$html .= "<option value='" . $provincia ['idProvincia'] . "'>" . $provincia ['nome'] . "</option>";
}
$json = array (
success => "OK",
html => $html );
$json = Zend_Json::encode ( $json );
echo $json;
die ();
}
You can use this as a starting point
I don't completely understand what you mean about one PHP file but this is the code I use for dynamically populating sub select boxes. Basically on select box change grab the ID and do Ajax via jQuery to get JSON response of cities and populate dropdown.
I use this code for populating a select box of cities (from one PHP file) based on the country you have selected:
<script type="text/javascript">// <![CDATA[
$(document).ready(function(){
$('#country').change(function(){ //any select change on the dropdown with id country trigger this code $("select[id$=cities] > option").remove(); //first of all clear select items
var country_id = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "GET",
url: "home/get_cities/"+country_id, //here we are calling our user controller and get_cities method with the country_id
success: function(cities) //we're calling the response json array 'cities'
{
$.each(cities,function(id,city) //here we're doing a foeach loop round each city with id as the key and city as the value
{
var opt = $('<option />'); // here we're creating a new select option with for each city
opt.val(id);
opt.text(city);
$('#cities').append(opt); //here we will append these new select options to a dropdown with the id 'cities'
});
}
});
});
});
// ]]>
</script>
You could post the data instead if you wanted to. In the PHP you would do something like this:
function get_cities($country){
$this->load->model('cities_model');
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->cities_model->get_cities($country)));
}
I wrote a post on this here: http://theninthnode.com/2011/01/dropdown-filtering-with-codeigniter-and-ajax/
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
});
I have a button on a pge thats fetches json data from a php page,
the data seems to arrive ok but i have gone through hundreds of examples and i just cant seem to reference the returned data, here is my script:
EDITED SCRIPT from previous comments
$('#geo_batch').click(function (){
var ajax_load = "<label><img src='/images/icons/loadinfo.gif' alt='saving location...' /> Loading data...</label>";
$("#batch_detail").html(ajax_load);
$('#batch_buttons').hide();
var form = $("form"); //Grab the form element from the DOM
//alert(form.serialize());
var mydata = form.serialize();
$.ajax({
type: "POST",
url: 'geo_getupdate_list.php',
data: mydata,
datatype: 'json',
success: function(dat) {
alert('dat:'+ typeof dat ) //RETURNS STRING
//alert(dat.location[0].id_mdt); //RETURNS UNDEFINED
// Cache the batch_detail element
var $detail = $("#batch_detail").html('<label>Locations have been retrieved:<br>' + dat + '<label>');
$('#batch_buttons').show();
// Instead of several .append() calls on the same element, create a
// single string, and do one.
var appendString = '';
for(var key in dat) { alert(key); return false; };
/*for(i=0; i < count; i++){
appendString += 'display address: ' + data.location[i].displayaddr_mdt + 'flag: ' + data.location[i].flag_mdt;
}*/
$detail.append(appendString);
},
error: function(dat) { //Triggered if an error communicating with server
//alert('fail');
$("#batch_detail").html('<label>There was an error: '+dat+'<label>');
$('#batch_buttons').show();
}
});
return false; //Ignore the default behavior of the button click
});
the json that is returned is:
{"location":[{"id_mdt":"5","idetp_mdt":"1","name_mdt":null,"geoaddr_mdt":null,"displayaddr_mdt":"31a Arundel Gardens London W11 2LW","telephone_mdt":null,"email_mdt":null,"website_mdt":"http:\/\/","lat_mdt":"51.513561","lng_mdt":"-0.206519","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null},{"id_mdt":"1","idetp_mdt":"1","name_mdt":null,"geoaddr_mdt":null,"displayaddr_mdt":"via todde 29 Ales Sardegna 09091","telephone_mdt":null,"email_mdt":null,"website_mdt":"http:\/\/","lat_mdt":"39.7670964","lng_mdt":"8.813689","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null},{"id_mdt":"4","idetp_mdt":"1","name_mdt":null,"geoaddr_mdt":null,"displayaddr_mdt":"31a Arundel Gardens London W11 2LW","telephone_mdt":null,"email_mdt":null,"website_mdt":"http:\/\/","lat_mdt":"51.513561","lng_mdt":"-0.206519","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null},{"id_mdt":"3","idetp_mdt":"1","name_mdt":null,"geoaddr_mdt":null,"displayaddr_mdt":"31a Arundel Gardens London W11 2LW","telephone_mdt":null,"email_mdt":null,"website_mdt":"http:\/\/","lat_mdt":"51.513561","lng_mdt":"-0.206519","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null},{"id_mdt":"6","idetp_mdt":"1","name_mdt":null,"geoaddr_mdt":null,"displayaddr_mdt":"31a Arundel Gardens London W11 2LW","telephone_mdt":null,"email_mdt":null,"website_mdt":null,"lat_mdt":"51.513561","lng_mdt":"-0.206519","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null},{"id_mdt":"7","idetp_mdt":"1","name_mdt":"Test","geoaddr_mdt":null,"displayaddr_mdt":"31a Arundel Gardens London W11 2LW","telephone_mdt":null,"email_mdt":null,"website_mdt":null,"lat_mdt":"51.513561","lng_mdt":"-0.206519","active_mdt":"1","flag_mdt":"1","id_etp":"1","name_etp":"Stockist","icon_etp":null}]}
how do i access the data in the array?
i have tried so many examples on here and other places and i cant get any to work.
I think it may be to do with the returned json object it has [ symbols in it which i think is wrong?
the php i have to generate the json is as follows:
//have defined a recordset called $rs_locations
$rows = array();
while($r = mysql_fetch_assoc($rs_locations)) {
$rows[] = $r;
}
$jsondata = json_encode($rows);
// trying to strip out the [ ] brackets but doesn't work
str_replace ("[", "", $jsondata);
str_replace ("]", "", $jsondata);
echo($jsondata);
any ideas anyone, i am so stuck, thanks
EDIT: Your dataType property is mis-spelled.
It should be dataType, not datatype.
Also, try changing the data parameter to some other name, like dat. I've seen problems with that before when your $.ajax() call has the data property set.
success: function( dat ) {
// Then change all references from data to dat
Try this for your success: callback.
You were fetching the same #batch_detail element several times and continuously calling .append() on that element.
This way you cache a reference to the element, create a single String to append, and then do the append once after the loop is done.
The specific trouble you were having was that you needed to reference the Array stored at data.location directly.
success: function(dat) {
// Cache the batch_detail element
var $detail = $("#batch_detail").html('<label>Locations have been retrieved:<br>' + dat + '<label>');
$('#batch_buttons').show();
var count = dat.location.length - 1;
// Instead of several .append() calls on the same element, create a
// single string, and do one.
var appendString = '';
for(i=0; i < count; i++){
appendString += 'display address: ' + dat.location[i].displayaddr_mdt + 'flag: ' + dat.location[i].flag_mdt;
}
$detail.append( appendString );
},
If I get your script right, you have to get the location array from data first:
var locations = data.location;
for(var location in locations) {
console.debug(locations[location]);
}