Accessing DOM element created using jquery .load() - php

My goal is to obtain an array of data from a mysql database using PHP for use in a javascript function; graph() in the example below.
I have chosen to do this by loading the data i need to a DOM element. I am now trying to access it. The query works and I can see the information I need in my #loadTarget div. I am having trouble accessing the innerHTML though.
According to Jquery documentation, i can use a complete function which will execute once the load is done:
.load( url [, data ] [, complete ] )
Why then, when I can see the database data I need rendered in my element, can i not access it using getElementByID and innerHTML?
var dataLocation = document.getElementById("arrayTargetOne");
var data = dataLocation.innerHTML;
The above returns data is null. If i do the same getElementById on the parent element (not the one created in my PHP .load file, the one already there), i can see the data I need. It is like the .load function is not complete. Am i missing something minor or should i take a different approach?
The Javascript/Jquery
$( ".selectUser" ).click(function() {
var userChoice = document.getElementById(this.id);
var user = x.innerHTML;
$("#loadTarget").load("example.php",{"data":user},function() {
var dataLocation = document.getElementById("arrayTargetOne");
var data = dataLocation.innerHTML;
alert(data);
graph();
});
The PHP
<?php
$login_errors = array();
require ("config.php");
require (MYSQL);
$arrayOne = array();
$arrayTwo = array();
$exampleQuery = $dbc->prepare("SELECT exampleFieldOne,exampleFieldTwo FROM exampleTable WHERE userID=? AND name=?");
$exampleQuery->bind_param('ss',$_SESSION['user_id'],$_POST['data']);
$exampleQuery->execute();
$exampleQuery->bind_result($a,$b);
while($exampleQuery->fetch()){
array_push($arrayOne,$a);
array_push($arrayTwo,$b);
}
echo '<span id="arrayTargetOne">';
echo json_encode($arrayOne);
echo '</span><span id="arrayTargetTwo">';
echo json_encode($arrayTwo);
echo '</span>';
?>
});

var list = document.getElementById('loadTarget').children;
for (var i=0, len = list.length; i<len; ++i) {
var data = list[i].nodeValue; //for text nodes, use innerHTML for elements
//do stuff with data
}
The list will be a list of the created DOM nodes.

Related

Fetch data from database in JS file

I've created a tag input for my user in my site, for that purpose I coded a tag function with dropdown help. So my problem is that, I want to fetch data from data base in JavaScript file.
Js
var FormSamples = function () {
return {
//main function to initiate the module
init: function () {
// use select2 dropdown instead of chosen as select2 works fine with bootstrap on responsive layouts.
$('.select2_category').select2({
placeholder: "Select an option",
allowClear: true
});
$('.select2_sample1').select2({
placeholder: "Select a State",
allowClear: true
});
$(".select2_sample2").select2({
placeholder: "Type to select an option",
allowClear: true,
minimumInputLength: 1,
query: function (query) {
var data = {
results: []
}, i, j, s;
for (i = 1; i < 5; i++) {
s = "";
for (j = 0; j < i; j++) {
s = s + query.term;
}
data.results.push({
id: query.term + i,
text: s
});
}
query.callback(data);
}
});
function format(item) {
opt = $(item.element);
sel = opt.text();
og = opt.closest('optgroup').attr('label');
return og+' | '+item.text;
}
$("select").select2({
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
$(".select2_sample3").select2({
tags: ['Karachi','Lahore']
});
}
};
}();
In the end of JS file you'll see:
$(".select2_sample3").select2({
tags: ['Karachi','Lahore']
});
Instead of "Karachi","Lahore" I want to fetch tags from data base.
I am fetching data like this:
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT * FROM tags";
$result = mysqli_query($conn, $sql);
mysqli_query ($conn,"set character_set_results='utf8'");
$row = mysqli_fetch_assoc($result);
Any body please help me that how can I fetch data in JS by PHP.
You can use json_encode in php:
$ar = array('Karachi','Lahore');
echo json_encode($ar);
and in javascript:
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>
output:
['Karachi','Lahore']
You are almost there. Now you can access the relevant data members of $row by selecting based on column name. For example you can look at the value of ˚$row["id"]. Also fetch_assoc type functions work row by row, so you will have to run it for each row, not each column, when you have multiple results. You can store the results in a php array but you will have to output them to the javascript portion of your file, or store them in a file javascript can access, before ending the php portion of your script. Below I write a little about each of your options.
Save data obtained form php data query to csv file, from which javascript can read.
Take a look at this SO post to learn how you can read data from csv. So in this example, your php script could read data from a database and then generate, via php, a csv file. Your javascript could then read from the csv file.
Alternately you can write from php directly to the javascript encoded in the same page assuming you can use your script in the same web page and not as a .js include. In that case, you can use json_encode to print your php arrays to javascript arrays as described in this SO post.
For example, to create two arrays accessible in Javascript of cities and countries I would do this:
<?php
...
$city = array();
$country = array();
while($row = mysqli_fetch_assoc($result)){
array_push($city, $row['city']);
array_push($country, $row['country']);
}
...?>
<script>
var city = <?php echo json_encode($city); ?>;
var country = <?php echo json_encode($country); ?>;
...
</script>
Here I am assuming you stored the data in a database with column names 'city' and 'country'
You should also consider using PDO objects for safer SQL manipulation.

Get response array from jquery ajax to php

I am trying to populate a table from mysql based on a select box option using jquery ajax, so far this is my jquery code. I can show the result on the alert box but i dont know how to send it to php so that i can loop thru the array and create the table.
// selector de campaña en reporte de clientes mas activos
$(document).ready(function(){
$('.selector-camp').change(function(){
var campaing = $('.selector-camp').val();
$.post( "../campanas/test", { 'camp': campaing },
function( data ) {
alert( data.result );
}, "json");
});
});
As I use JavaScript more than jquery, I'll write it in JavaScript and I am sure you can do that in Jquery too, but in JavaScript it's also easy to do
function( data )
{
createTable(data.result); //pass your json array to JS function
}, "json");
//here i create js function
function createTable(array)
{
var array = JSON.parse(array); //decoding from json format
//So if i have numbers in array like [1, 2, 3, 4] and want
//to create row with them something like this should be done
var table = document.createElement("table"); //create table
var tr = document.createElement("tr"); //create row
for(var i=0; i<array.length; i++)
{
var td = document.createElement("td");
td.innerHTML = array[i];
tr.appendChild(td);
//for each array element creates cell and appends to row
}
table.appendChild(tr);
//Then you can have some empty div and append table to it
var div = //your empty div
div.appendChild(table);
}
Please check below php prototype code as per your requirement.
From ajax please make a call to this file it will return you a json response since I have used json_encode() function, you can directly return array as well but I would not suggest that, also you can edit this code for further mysql query.
<?php
test();
function test(){
$camp = htmlspecialchars($_POST['camp']);
isset($camp)&&!empty($camp)?
$data = array('test_key'=>'test_value');
echo json_encode($data);
}
?>

Updating list of <select> options using jquery and ajax

I am trying to make an html select list of options update according to a selection made on a prior html select object. My jquery is below. This is being called correctly.
var brandName = $("#Brand").val();
$.get("updateTypes.php?q="+brandName, function(data) {
$("#Type").remove();
var typeData = JSON.parse(data);
for (loop=0; loop < typeData.length; ++loop) {
$("#Type").options.add(new Option(typeData[loop]));
}
});
As I am using a singleton to interface with my mySQL database, this jquery function calls a 'go-between' .php file called updateTypes.php which is below:
include 'databaseInterface.php';
$brand = $_GET["q"];
$typesData = databaseInterface::getBrandTypes($brand);
return $typesData;
This calls the getBrandTypes function in my singleton below:
$query = "SELECT psTypeName FROM types WHERE brands_psBrandName='$BrandName'";
$result = mysqli_query($con, $query) or die ("Couldn't execute query. ".mysqli_error($con));
$resultArray = array();
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$resultArray[] = $psTypeName;
}
return json_encode($resultArray);
The webpage correctly removes the existing options from the jquery function but fails to update them. It seems to go wrong when I decode the JSON data in the jquery. Why is it going wrong? Is the loop for updating the select object appropriate?
You can use $.getJSON if your expecting a json response. You might also be able to use $.each() and then simply .append() to the select tag. You can reference this.property inside the .each().
Something like the following:
$.getJSON("updateTypes.php?q="+brandName, function(data) {
$("#Type").html('');
$.each(data, function(){
$("#Type").append('<option value="'+ this.value +'">'+ this.name +'</option>')
)
})
This would assume your json response is something like the following:
[ { name : "foo", value : "bar" }, { name : "another", value : "example" } ]
Your code $("#Type").remove(); removes the select object not its options. The correct way of removing options is:
$("#Type option").remove();
or
$("#Type").html('');
The second solution seems to be better as stated here: How to remove options from select element without memory leak?
There is also an error in the part that adds new options. Your javascript code should be:
var brandName = $("#Brand").val();
$.get("updateTypes.php?q="+brandName, function(data) {
$("#Type option").remove();
var typeData = JSON.parse(data);
for (loop=0; loop < typeData.length; loop++) {
$("#Type").get(0).options.add(new Option(typeData[loop]));
}
});
The $('#Type').get(0) method refers to the raw DOM object which has the "options" property that you wanted to use (How to get a DOM Element from a JQuery Selector)

calling php and javascript functions with one button

This is what I'm trying to achieve, but my Googling hasn't helped:
I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.
PS I understand that PHP is server side as opposed to JS. But surely this is possible.
here's a simple implementation of such a thing using jQuery's ajax and php.
html
<select data-source-url="/category/list"></select>
javascript using jQuery
$("select[data-source-url]").each(function(){
var url = $(this).attr("data-source-url");
var el = $(this);
$.get(url, function(data){
for (i=0;i<data.length;i++){
el.append("<option>" + data[i] + "</option>");
}
},"json");
});
category/list endpoint (a php script)
$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";
echo json_encode($list);
a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.
Please note that on initial load of the page, the select box will be empty.
yes ofcourse you can. for storing s php variable in a js ariable you can do like this.
before storing it into js variable store the required value in your php variable
var value = '<?php echo $value;?>';
Javascript cannot connect directly to a database.
You want AJAX. A basic flow for this functionality looks like this.
Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.
Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.
Option 1
Pass a php array with all possible values to the client side using something like this on the client side:
var opt_values = [<?php echo $php_values; ?>]; //javascript array
or
var opt_values = <?php echo json_encode($php_values); ?>; //json object
Option 2
Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:
PHP function:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'id' => $row['id'],
'text' => $row['name']
);
array_push($json, $bus);
}
return = json_encode($json)
Jquery
$('#button-id').click(function(){
//adds a new row to a table dynamically
$.ajax({
type: "get",
dataType: "json",
url: "/get_values.php",
success: function (response) {
var $el = $("#myselect"); //get the select
$el.empty(); // remove old options
//Append the new values
$.each(response, function(key, value) {
$el.append($("<option></option>")
.attr("value", value.id).text(value.text));
});
}
});
});
Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post.
W3Schools PHP & AJAX communication

How to Populate multiple divs using jQuery's ajax?

I was trying to get my head around jQuery's Ajax. I have a page made up of a number of divs. I also have an XML document generated from a MySql resultset.
In the jQuery function below I am able to populate the titleDiv with data. The question I have is how do I populate the other divs on the page without having to build the page from scratch? I hope this makes sense......
$(document).ready(function() {
$("#getData").click(function(){
var data = "";
$.get("phpAjax.php", function(theXML){
$('row',theXML).each(function(i){
var title = $(this).find("Title").text();
var rating = $(this).find("Rating").text();
data = data + title;
});
$("#titleDiv").html(data);
$("#ratingDiv").html(?????);
});
});
});
did u try with??
first decalre variable
var title='';
var rating ='';
& then inside each
title+ = $(this).find("Title").text();
rating+ = $(this).find("Rating").text();
$("#titleDiv").html(title);
$("#ratingDiv").html(rating);

Categories