Store database values in javascript array - javascript

I am making a kind of reservation page where you can reserve a location for a specific day, all the dates will be stored in a database for each location.
But I want to get all the dates from the database and store them in a javascript array so I can disable these dates from the datepicker on the page.
I know how to select the dates using php and mysql but I can't figure out a way to store the data in a javascript array.
This is the js code for the datepicker:
var disableddates = ["20-05-2015", "12-11-2014", "21-05-2015", "12-20-2014"];
function DisableSpecificDates(date) {
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [disableddates.indexOf(string) == -1];
}
$(function() {
$("#date1").datepicker({
beforeShowDay: DisableSpecificDates
});
});
I want the array to hold the dates from the database.

You need to fetch data from database and json_encode them
var disableddates = <?php echo json_encode($response)?> ;

You can't write JS code directly in you PHP script.
PHP runs on the server, JS runs on the client.
JS from PHP's point of view is just like HTML.
What you can do, is output this to tag.
Something like ($dates contain the disabled dates):
function outputDatePickerScript($dates) {
echo 'var disableddates = ["' . implode('","', $dates) . '"]';
echo .... // Rest of the JS script
}
Call this function before the end of your HTML Body output.

You have options like
1.to write jquery function in php scipt echo '<script></script' and store the date values in array by select & fetch statement e.g.
/*Your select statement for dates*/
while loop{
$dates .= '"'.$row["date"].'",'
}
$dates = rtrim($dates, ",");
var disableddates = ['.$dates.'];
2> Store db values in a hidden field on front html with an id and pass the value in javascript varaible by selecting id

That's only your js code, show a little of the php too.
if you're not using any fancy ajax you could use something like this:
<?php
$dates = "";
while () { //this while would be your database while
$dates .= '"'.$row["date"].'",';
}
$dates = rtrim($dates, ",");
?>
var disableddates = [<?php echo $dates; ?>];

Related

Get JSON response in PHP using jQuery

Here is my code to call AJAX and get the response from another PHP file:
$.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km},
function(data){
$('#fare').html(data);
$('#loading_spinner').hide();
});
ajaxscript.php file
$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';
$json = json_decode($jsonData,true);
echo $json['fare'];
This code gives me the fare at the time of $('#fare').html(data);
But I need to extract the city from JSON, too, and for this I added an extra line in ajaxscript.php:
echo $json['city'];
After doing this, it gives me 30580Islamabad
How can I store these two values separately in JavaScript? I need them for future work.
You are doing everything backwards
Your PHP should be
$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';
//$json = json_decode($jsonData,true);
echo $jsonData;
As you already have a JSONString to send to your javascript.
Then your javascript will recieve a javascript object in the data parameter of
$.post( '<?php echo get_site_url(); ?>/ajax-script/',
{pickup:pickup,dropoff:dropoff,km:km},
function( data ) {
$('#fare').html(data.fare);
$('#city').html(data.city);
$('#loading_spinner').hide();
}, "json");
Note the "JSON" at the end of the javascript to tell it to expect a JSON Object, it will then convert the JSONString to a javascript Object automatically for you so the data parameter will be an onbect
Add Special characters at the end of each value and in jquery, using jquery split, cut the variable and display
like below;
$jsonData = '{"fare":30580^^,"actual_distance":1519^^,"city":"Islamabad^^","status":true}';
$json = json_decode($jsonData,true);
echo $json['fare'];
in jquery
function(data){
var tdata = data.split("^^");
$('#fare').html(tdata[0]);
$('#loading_spinner').hide();
});

Compare php array to javascript array same data

Scenario: I need to compare a database cell on the page load (php) against itself in an interval loop every x amount of minutes for changes.
My Initial load data looks like this:
var olddata = JSON.stringify(<?php echo json_encode($data1); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data2); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data3); ?>);
So on page load, I save the cells into a javascript variable with a "~|~" delimiter, where $data1, $data2, and $data3 are 3 different cells in the database (arrays of data).
And my interval loop data (ajax call) looks like this:
// PHP on the AJAX page
echo json_encode($data1)."~|~".json_encode($data2). "~|~".json_encode($data3);
// AJAX code that gets called every x Intervals
$.get("ajaxpage.php", function(data) {
if (data == olddata) {
console.log("Good!");
}
});
When I compare olddata against data they look almost identical except... data that has a / in it will look like \/ in the data variable and not in theolddata` variable.
Example:
"10":["10"],"11":["11 5\/25"] // data = return from the AJAX call
"10":["10"],"11":["11 5/25"] // olddata = what was originally echoed on page load.
How can I compare the two so that they will match perfectly? So that what I echo from the database and json_encode, will line up with what I get from the exact same thing echoed on a page and jason encoded from the json function return.
Note: If I remove the JSON.stringify then it will return [object Object]
You're using a very bad practice. Just use AJAX to get this:
var olddata = JSON.stringify(<?php echo json_encode($data1); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data2); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data3); ?>);
And store "olddata" in a JavaScript Global var, then compare the old data with the new data returned by $.get. This isn't the solution for your bug, but it's a better way to do what you're doing.
To fix the bug just declare the type of the return value in the your $.get function, like that:
$.get("ajaxpage.php", function(data) {
if (data == olddata) {
console.log("Good!");
}
}, 'text');
For more information about the return type, look the jQuery Documentation: jQuery $.get Documentation
Just change it to:
var olddata = '<?php echo json_encode($data1, JSON_HEX_APOS); ?>~|~<?php echo json_encode($data2, JSON_HEX_APOS); ?>~|~<?php echo json_encode($data3, JSON_HEX_APOS); ?>';
And the backend to:
echo json_encode($data1, JSON_HEX_APOS)."~|~".json_encode($data2, JSON_HEX_APOS). "~|~".json_encode($data3, JSON_HEX_APOS);
Now you're simply comparing two strings.

Autocomplete not working when array is filled from database

I used to use this kind of code before like 1 year ago and it worked.
Now I got a problem with the php code when I fill my array with elements from the database I can't do the autocomplete, but when I comment the part where I get the code form the database and uncomment //$elements = array("25qt", "45tr", "az12"); than the autocomplete works.
It looks like the array is filled correctly from the database cause when I open the php file alone and do a var_dump($elements); i get the content of the array accordingly. Any idea why its not working when i fill the array from the db but it works if I use an array like $elements = array("25qt", "45tr", "az12");.
HTML code:
<input id="tegjithepjeset" type="text" class="form-control">
jQuery code:
<script type="text/javascript">
$(document).ready(function(){
$("#tegjithepjeset").autocomplete({
source:'allParts.php',
minLength:1
});
});
</script>
Php code:
<?php
// An empty array:
$data = array();
// Create connection
include 'dbinfo.php';
$con=#mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$queryString = "SELECT code FROM ".$table;
$query =mysqli_query($con,$queryString);
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
$elements[]="".$rowDB[0];
}
//var_dump($elements);
//$elements = array("25qt", "45tr", "az12");
//Loop through the array to find matches:
foreach ($elements as $elm) {
// Add matches to the $data array:
if (stripos($elm, $_GET['term']) !== false) $data[] = $elm;//here we fill our empty array with values
} // End of FOREACH.
// Return the data:
echo json_encode($data);
?>
Replace the $elements array code as shown below.
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
// $elements[]="".$rowDB[0];
$elements[]=$rowDB[0];
}

Passing Array From PHP to JQuery json_encode

I have an HTML form generated by php which has a dropdown of voucherproviders.
I want to select the provider and have this populate the form for editing.
Here is my JQuery code:
$(document).ready(function() {
$(document).on('change','#id_voucherprovider',function(){
var voucher_providers = <?php echo json_encode($voucher_providers); ?>;
//The value I have got from the drop down is....
var value = $('#id_voucherprovider option:selected').val();
var vendortext = $('#id_voucherprovider option:selected').text();
//so the voucher provider is
alert(vendortext);
$('.ftext input').val(vendortext);
$("textarea#id_vendornotes").val(voucher_providers[value]);
});
});
voucherproviders is not being passed into the JQuery despite the echo json_encode($voucher_providers); code working when inline with the php code.
It seems to return a null array. Can anyone see what is wrong?
Many Thanks
Dave
var voucher_providers = <?php echo json_encode($voucher_providers); ?>;
json_encode returns a string, unless it is parsed it will not be usable. Use JQuery .parseJSON and you should have better results. :)
var jsonString = <?php echo json_encode($voucher_providers); ?>;
var voucher_providers = $.parseJSON(jsonString);
try this (note the quotes):
var voucher_providers = JSON.parse('<?php echo json_encode($voucher_providers); ?>');
parse your json ex: obj = JSON.parse(data);
Hi please check the json format at below site:-
http://jsonlint.com/
and check if this is fine.

Inserting MySQL results from PHP into JavaScript Array

I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.

Categories