How to use loop for multiple arrays imported from Database - php

In server side I give table data from MySql and I send it with json_encode to JQuery:
<?php
include 'DB.php';
$result20 = mysql_query("SELECT * FROM Gallery WHERE Section = 'Chosen' AND ID = 19");
$array20 = mysql_fetch_row($result20);
$result19 = mysql_query("SELECT * FROM Gallery WHERE Section = 'Chosen' AND ID = 19");
$array19 = mysql_fetch_row($result19);
$data = array();
$data['Div20'] = $array20;
$data['Div19'] = $array19;
echo json_encode($data);
?>
json_encode export this arrays: {"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]}
but, in client side I need use a loop for use all arrays in events. When I use for, it's not work with multiple arrays, how to do it?
$(function() {
$.get('data.php' ,function(response)
{
var data = jQuery.parseJSON(response);
var array;
for(array in data)
{
var ImageID = data.array[0];
var ImageSrc = data.array[1];
$('#'+ImageID ).click(function(){
//some codes
})
}
})
})

Try this
$(function() {
$.get('data.php' ,function(response) {
var data = jQuery.parseJSON(response);
$.each( data, function( key, value) {
var ImageID = value[0];
var ImageSrc = value[1];
$("#"+ImageID ).click(function(){
//some codes
})
})
})

It will work if you add # to your imageid like,
$('#'+ImageID ).click(function(){
//some codes
});
I've tried some code for you,
var json={"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]};
for(div in json){
ImageID=json[div][0];
ImageSRC=json[div][1];
$('#'+ImageID)
.attr('src',ImageSRC)
.click(function(){
alert(this.src);
});
}
Demo

Replace .array with [array] in your for loop:
for(array in data)
{
var ImageID = data[array][0];
var ImageSrc = data[array][1];
}

"array" is not an attribute of your json object, it's just an argument of your for ... in loop. So you must use it as a dynamic value. Moreover you missed using a # to target properly the element id.
var data = {"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]};
for(array in data)
{
var ImageID = "#"+data[array][0];
var ImageSrc = data[array][1];
$(ImageID).on("click",function(){
//some codes
});
};
Avoid using $.each() loop as someone recommended above, jQuery loops are usually slower than native loops.

Try this..
$(function() {
$.get('data.php' ,function(response)
{
var data = jQuery.parseJSON(response);
$.each(data,function(k, v){
var ImageID = v[0];
var ImageSrc = v[1];
$('#'+ImageID ).click(function(){
//some codes`enter code here`
})
})
})

Related

How to add order list into jQuery Nestable JSON serialize

I've using jQuery Nestable menu from http://robertan.com/blog/?p=108
But I want make an enhancement on the JSON serialize from
[{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5}]}]
become
[{"id":1,"order":1},{"id":2,"order":2},{"id":3,"order":3,"children":[{"id":4,"order":1},{"id":5,"order":2}]}]
Any suggestion?
I don't know javascript well,but PHP is OK~
This gives your expected result, find the inline comments for more details
<script>
$(document).ready(function(){
//create the json object
var menu = $.parseJSON('[{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5}]}]');
//final result variable menu
var final_menu = [];
//initial variable
var i = 1;
//process each element
$.each(menu, function(index, value){
//local variable
var item = {};
//type of validation
if(typeof(value.children) !== 'undefined')
{
var j = 1;
item['id'] = value.id;
item['order'] = i;
item['children'] = [];
//process each children
$.each(value.children, function(index1, value1){
var child = {};
child['id'] = value1.id;
child['order'] = j;
item['children'].push(child);
j++;
});
}
else
{
item['id'] = value.id;
item['order'] = i;
}
//create the final menu
final_menu.push(item);
i++;
});
console.log(final_menu);
});
</script>

How to use jQuery variable in PHP

Im using a MVC in PHP and I have this script created in my form page to validate three text boxes. When these three text boxes contain a value my php code in my controller asks Google Map Api for the closest directions based on the input of these three fields.
In my script I have the variable "direccion" which is what I need to pass to the controller using PHP but im not sure how to accomplish this.
Script Code (View):
jQuery(document).ready(function () {
var direccion="";
var flag = false;
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
alert("false");
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#ff_elem295").val();
var municipio = jQuery("#id_municipio option:selected").text();
var provincia = jQuery("#id_provincia option:selected").text();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
//alert(direccion);
}
});
jQuery.ajax({
url: "index.php?option=com_cstudomus&controller=saloninmobiliarios&task=calcularDistancias",
data : direccion,
dataType : 'html'
}).done(function(){
var data = data;
});
});
PHP Code (Controller):
function calcularDistancias(){
$valor = JRequest::getVar('direccion');
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='. $valor .'&sensor=false';
$data = file_get_contents($url);
$data_array = json_decode($data,true);
$lat = $data_array[results][0][geometry][location][lat];
$lng = $data_array[results][0][geometry][location][lng];
......
}
data property in the object passed to jQuery.ajax is an object.
data : { direccion: direccion }
Then you can access the value of direccion in your controller as a request parameter.
In the if condition put your ajax request like
if(flag == true) {
jQuery.ajax({
url: "index.php?option=com_cstudomus&controller=saloninmobiliarios&task=calcularDistancias",
data : {direction : direccion},
dataType : 'html'
}).done(function(){
var data = data;
});
}
In addition the retrieved data are missing in your code, don't forget to put data in done function :
.done(function(){
var data = data;
});
To
.done(function(data){
var data = data;
});

how to use two $.post methods very well for give data from 2 different database

function ChangeGallery(){
var GalleryName = $('.SubSubGalleryLock').text();
/*Send string to Data1.php and include Tags from Database*/
$.post("Data1.php", { Sections: GalleryName },
function(data){
$(".IncludeData").append(data);
});
/*send string to Data2.php and include Events data from Database*/
$.post("Data2.php",{ GallerySec: GalleryName },
function(response){
/*when i use alert method, this function works very well, why?*/
alert('SomeString');
var data = jQuery.parseJSON(response);
var ImageID = data[0];
var ImageSrc = data[1];
$(ImageID).click(function(){
$(".LargeImage").attr('src', ImageSrc);
});
});
};
in Data1.php
/*give data from database1 and print to HTML File*/
if ($_POST['Sections']) == "String")
{ $results = mysql_query("SELECT * FROM Table1");
while($row = mysql_fetch_array($results))
{ echo $row['Tags']; }
in Data2.php
/*give data from database2 and Use for events*/
if ($_POST['GallerySec']) == "String")
{ $results = mysql_query("SELECT * FROM Table2");
while($row = mysql_fetch_array($results))
{ echo json_encode($row); }
in Client side when i use it then Data1.php works very well but Data2.php only when i write an
alert('Some stringh');
after
var data = jQuery.parseJSON(response);
line, it's work well, why? what's due to this problem?
I'm going to guess that you need the second .post() to be processed AFTER the first .post() and when you put the alert() in, that guarantees that it will go in that order, but without the alert(), it is a race condition and depends upon which .post() returns quicker.
There are a couple ways to fix the sequencing. The most straightforward is to start the second .post() from the success handler of the first so that you know the first has already completed.
You can also use jQuery promises or you could use your own flags to keep track of which has finished and call the last bit of code only when both have finished.
Here's how you would start the second .post() from the success handler of the first to guarantee the order:
function ChangeGallery(){
var GalleryName = $('.SubSubGalleryLock').text();
/*Send string to Data1.php and include Tags from Database*/
$.post("Data1.php", { Sections: GalleryName },
function(data){
$(".IncludeData").append(data);
/*send string to Data2.php and include Events data from Database*/
$.post("Data2.php",{ GallerySec: GalleryName },
function(response){
var data = jQuery.parseJSON(response);
var ImageID = data[0];
var ImageSrc = data[1];
$(ImageID).click(function(){
$(".LargeImage").attr('src', ImageSrc);
});
});
});
};

How Do I Extract a PHP JSON Array Name

I have a PHP file that returns a JSON array. I need to extract the array name, in this instance, *Regulatory_Guidance_Library* with jQuery as a var to $('#navHeaderTitle').text(arrayName); of my function. I don't know how this is done.
Thnx for your help
My Function in the HTML Doc:
function loadNav(url, container, appendE) {
$.getJSON(url, function(data){
var arrayName = "";
$.each(data.Regulatory_Guidance_Library, function(){
var newItem = $('#' + container).clone();
// Now fill in the fields with the data
newItem.find("h1").text(this.label);
newItem.find("h2").text(this.title);
newItem.find("p").text(this.description);
// And add the new list item to the page
newItem.children().appendTo('#' + appendE)
});
$('#navHeaderTitle').text(arrayName);
//transition(pageName, "show");
});
};
The served PHP:
<?php
//MySQL Database Connect
include 'andaerologin.php';
mysql_select_db("andaero");
$sql=mysql_query("select * from regulatory_list");
$output = new stdClass();
while($row = mysql_fetch_assoc($sql)) {
$output->Regulatory_Guidance_Library[] = $row;
}
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo (json_encode($output));
mysql_close();
?>
Modify php:
$output = array();
/* used "key" as name...could change to suit your app*/
$output['key']='Regulatory_Guidance_Library';
while($row = mysql_fetch_assoc($sql)) {
$output['items'][]= $row;
}
AJAX:
$.getJSON(url, function(data){
$.each(data.items, function(){
var newItem = $('#' + container).clone();
// Now fill in the fields with the data
newItem.find("h1").text(this.label);
newItem.find("h2").text(this.title);
newItem.find("p").text(this.description);
// And add the new list item to the page
newItem.children().appendTo('#' + appendE)
});
$('#navHeaderTitle').text(data.key);
//transition(pageName, "show");
});
The other answer is probably more helpful, but if you want to get the names of an object's properties with javascript you can do:
for (var name in data) {
alert(name);
}
In your case, since you have only one property you could do:
for (var name in data) {
$('#navHeaderTitle').text(name);
}

how to pass a php array to javascript array using jquery ajax?

I followed other reslted question but still unable to solve this problem. I want to store the values of an array from php into an array of js. I tried myself butr getting indefined value in all the cases i tried
Plese anyone let me know where i am wrong
my Php code
<?php
$var=5;
$myArray = array();
while($var<10){
$myArray[]=$var;
$var++;
}
echo json_encode($myArray);
?>
and the js code
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array(); var i= 0;
jQuery.getJSON("phparray.php", function(data) {
while(i<5){
res[i]=data.i;
i++;
}
});
});
jQuery("#result").html(res[0]);
});
also treid this js
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array();
var i= 0;
jQuery.getJSON("phparray.php", function(data) {
jQuery(data).each(function(key, value) {
res[i]=value;
i++;
});
});
jQuery("#result").html(res[0]);
});
Try below code
<?php
$var=5;
$myArray = array();
while($var<10){
$myArray[]=$var;
$var++;
}
$dataarray=array("myarray"=>$myArray);
echo json_encode($dataarray);
?>
Jquery
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array();
jQuery.getJSON("phparray.php", function(data) {
var i= 0;
while(i<data.myarray.length){
res[i]=data.myarray[i];
i++;
}
jQuery("#result").html(res[0]);
});
});
});
The problem with your code is you are updating the result before the JSON has been loaded. There is also no reason to copy every item in the array in this case just set res = data (although the above example of sending back an associative array or JS object is good practice).
PHP
<?php
for($var=5; $var<10; $var++){
$myArray[]=$var;
}
echo json_encode($myArray);
JavaScript
$(document).ready(function() {
var res;
$("#result").bind('update', function() {
$("#result").html(res[0]);
});
$("#previous").click(function(){
$.getJSON("phparray.php", function(data) {
res = data;
$("#result").trigger('update');
});
});
});

Categories