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)
Related
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.
I have googled and looked at SO for a while now and can't seem to figure this out. The only requirement Im trying to meet is to return a properly formatted javascript array that contains the results of the sql statement.
I.E.
Given a query:
SELECT NUMBERS FROM TABLE
And results:
NUMBERS
1
2
3
I would like to eventually get back an array like so
["1","2","3"]
Please help me understand where I am going wrong
Here is my php code
<?php
$mysqli = new mysqli("local.host.com", "user", "pass", "db");
$sql = "SELECT DISTINCT NAME FROM table";
$result = $mysqli->query($sql);
while($row = $result->fetch_array())
{
$rows[] = $row['NAME'];
}
echo(json_encode($rows));
$result->close();
/* close connection */
$mysqli->close();
?>
Here is my javascript:
function GetCards()
{
var cardarray = new Array();
//alert('test');
$.getJSON('getcardlist.php', function(data)
{
for(var i=0;i<data.length;i++)
{
cardarray.push(data[i]);
}
//return cardarray;
});
return cardarray;
}
EDIT:
Little more information, Im trying to setup an autocomplete list for jquery ui, this is my setup for the autocomplete widget.
var list = GetCards();
$( "#name" ).autocomplete({
source: list,
minLength: 2
And this is the error Im getting from chrome console
Uncaught TypeError: Cannot read property 'label' of null
GetCards is returning an empty array -- which is what you're passing on to the Autocomplete widget -- and causing the widget to throw up the TypeError exception. To pass on the populated array, move the code that instantiates Autocomplete into your getJSON success callback (I'm not sure you even need to loop through data -- unless you need to actually transform its contents in some way):
$.getJSON( 'getcardlist.php', function( data ) {
$( "#name" ).autocomplete( {
source: data,
minLength: 2
} );
} );
Alternatively, consider using Autocomplete's shorthand for loading directly from the data feed (see passing source as a string). However, this approach may require some additional work on the server-side to filter down the list as the user types -- if you want that behavior.
you have to use $.each to get the data
$.getJSON('getcardlist.php', function(data)
{
$.each(data, function(key, val) {
cardarray.push(val);
});
//return cardarray;
});
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
I attempt to fill a drop down from a database. I query and add my result to an array. I then use json_encode to send my data to a php file.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => $proj_option);
echo json_encode($output);
In my php file, I use jquery ajax to fill the drop down.
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
This is great, BUT the only item in my drop down is the last item in the db. For example, my database has the following under Project:
Project: up, down, low, right
But my drop down only fills with the last entry, "right." Why is this? How can I fix it?
PHP json_encode() in while loop was similar, and I made the changes, but there is something missing here.
may be try this
success:function(response) {
$.each(response.proj,function(key,value){
$("#exp").append(value);
$("#project").append(value);
});
}
each time thru your loop in javascript you are overwriting your html. The .html() method sets the innerHTML property of the tag, so each time you call it you are resetting the html and only the last one will show. try not using a loop, instead join you response together and then call .html()
$("#exp").html(response.proj.join(''));
$("#project").html(response.proj.join(''));
Edit:
Solved using the below suggestion of removing:echo '{"results":'.json_encode($arr).'}';
and replacing with echo json_encode($arr);
This combined with replacing these lines:
var items = [];
$.each(data, function(key, val) {
$.each(val, function(key, val)
{
//Test insert into box using customer number
$("#chatbox").html(val.number);
});
});
with
$.each(data, function(key, val) {
$("#chatbox").html(this.number);
});
Made it work, I can now access the object data using the this followed by the property I want.
End Edit
Hi could anyone help me with these JSON feed. I am almost there with it (I think) however whenever I put this feed into JQuery it is picked us as a string rather than as an array of JSON objects and I can't figure out why.
The PHP to create the feed:
<?php
session_start();
include 'connect.php';
$number = $_SESSION['number'];
$query = "SELECT * FROM $tableName WHERE number='$number'";
$result = mysql_query($query, $sqlCon);
$arr = array();
while($obj = mysql_fetch_object($result)) {
$arr[] = $obj;
}
if (count($arr) == 0)
{
echo "Your reference number is: $number";
} else {
echo '{"results":'.json_encode($arr).'}';
}
?>
The returned JSON looks like this:
{"results":[{"id":"40","number":"466741","message":"dsfdsv","date":"2011-10-05","time":"00:28:32"},{"id":"41","number":"466741","message":"sacsac","date":"2011-10-05","time":"00:30:17"}]}
What I instead want is:
[{"id":"40","number":"466741","message":"dsfdsv","date":"2011-10-05","time":"00:28:32"},{"id":"41","number":"466741","message":"sacsac","date":"2011-10-05","time":"00:30:17"}]
Or a return value which would allow me to iterate over the objects.
The JQuery I'm reading it with:
$.getJSON('get.php', function(data) {
var items = [];
$.each(data, function(key, val) {
$.each(val, function(key, val)
{
//Test insert into box using customer number
$("#chatbox").html(val.number);
});
});
});
I'm guessing my problem is the way in which I'm creating the JSON feed but I'm just stuck and cant figure out how to fix it.
Any help would be appreciated, thanks.
You should set the headers from PHP to specify that it is json content. This isn't 100% required but good practice and you'll see the content-type parsed correctly in tools like firebug.
header('Content-type: application/json');
You are wrapping your json content with a results key that that you aren't looking for in your javascript so you either need to remove that part or look for that your javascript. Since you say you want the array and not the object with the results key/value just replace echo '{"results":'.json_encode($arr).'}'; with echo json_encode($arr);