Updating Pickadate Input via AJAX - javascript

I use Pickadate.js and JQuery Form Plugin. I have date and time pickers seperately. What I want to do is to disable times in timepicker according to value of datepicker. So, I am trying to get the JSON data into picker.set("disable", [ ]);. I can console.log the plain text but it remains aimless.
I tried a lot and have come across these solutions in that question. But I couldn't launch them. (I adapted pickadate functions and classes to pickatime's.)
// Javascript
$(document).ready(function() {
$("input").click(function() {
$(".datepicker").pickadate({
format: 'yyyy-mm-dd',
formatSubmit: 'yyyy-mm-dd',
min: true,
max: false
});
var $input = $(".timepicker").pickatime({
format: 'HH:i',
formatSubmit: 'HH:i',
formatLabel: 'HH:i'
});
$('.datepicker').change(function() {
$('#form').ajaxSubmit({
target: '#check_result',
url: 'check.php',
success: function showResponse(responseText, $form) {
var picker = $input.pickatime('picker');
picker.set("disable", [
console.log(responseText)
]);
}
});
return false;
});
});
});
// PHP (check.php)
<?php
// Database connection done.
$date = mysqli_real_escape_string($con, $_POST['date']);
$match_query = mysqli_query($con, "SELECT * FROM booking WHERE DATE(time) = '$date'");
$disabled_times = array();
if ($result = $match_query) {
while ($row = mysqli_fetch_assoc($result)) {
$disabled_times[] = $row['time'];
}
mysqli_free_result($result);
}
echo implode($disabled_times);
?>

Can you post an example of the json being returned from your php?
According to the docs (http://amsul.ca/pickadate.js/api/#method-get-disable)
your json should be something like this: [2,30], [4,30], [9,0]
If your json is correct, be sure it is not being passed to the timepicker as a string. Try something like:
var json = JSON.parse(responseText);
picker.set("disable", [ json ]);
UPDATE:
I guess with the following code, your json will return properly:
...
$time = explode(',', $row['time']);
$time[0] = (int)$time[0];
$time[1] = (int)$time[1];
$disabled_times[] = $time;
...
echo json_encode($disabled_times);

Related

How to get JavaScript variable through PHP post request?

I am posting the PHP file (post.php) through jquery ajax. And I want to get the data from it in the form of a javascript variable. I successfully get the data in my console. But I don't know how can I use this variable. You can see my code below.
$.post(
"post.php",
{
region: region,
district: district
},
function(data) {
console.log(data);
}
);
my post.php page looks like this
#include('../../_partials/_dbConnect.php');
$region = $_POST['region'];
$district = $_POST['district'];
$sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";
$result = pg_query($db_connection, $sql);
while ($row = pg_fetch_row($result)) {
$cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);
}
<script>
var cols = [<?php echo '"'.implode('","', $cols).'"' ?>];
</script>
And the console.log(data) output like this,
<script>
var cols = ["94","32","361","0","118","159","0","243","702","1775","8","0","2","0","150","135","381","2","0","0","0","0"];
</script>
Your help is highly appreciated.
In your post.php, you can simply echo the array and jQuery should automatically convert it to an array as the response
// post.php
<?php
#include('../../_partials/_dbConnect.php');
$region = $_POST['region'];
$district = $_POST['district'];
$sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";
$result = pg_query($db_connection, $sql);
while ($row = pg_fetch_row($result)) {
$cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);
}
echo json_encode($cols);
?>
// Somewhere in your js
$.post(
"post.php",
{
region: region,
district: district
},
function(data) {
console.log(data[0]);
}
);
in javascript use JSON.parse()
$.post(
"post.php",
{
region: region,
district: district
},
function(data) {
data=JSON.parse(data);
}
);```
And here you go, u can play with it as you need
Happy learning!

Display JSON Array as html list

I want to display my JSON array which i got from the PHP server as list in HTML. The code I used loops through the array, but when i replace the array with the variable it does not work.
$(document).ready(function(){
$(document).bind('deviceready', function(){
//Phonegap ready
onDeviceReady();
});
var ownproducts = $('#ownproducts');
$.ajax({
url: 'MYURL',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var products = '<br>'+item.item;
var ul = $('<ul>').appendTo('body');
var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] };
$(json.items).each(function(index, item) {
ul.append($(document.createElement('li')).text(item));
});
ownproducts.append(products);
});
},
error: function(){
ownproducts.text('Error Message');
}
});
});
So i get a JSON file containing data from my database, item.item contains an array but when i replace this:
var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] };
for:
var json = { items: item.item };
or:
var json = { items: products };
it does not work (not displaying anything javascript related).
EDIT:
I try to get some items from my database through PHP
<?php
header('Content-type: application/json');
require 'config.php';
$con = mysqli_connect($url,$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$userid = $_GET['userID'];
mysqli_select_db($con, $database);
$sql = "SELECT shoppingListID AS id, shoppingListUserID AS userid, shoppingCheckBox AS checkbox, shoppingItem AS item, shoppingDate AS date
FROM shoppinglist
WHERE shoppingListUserID='$userid'
ORDER BY shoppingDate DESC";
$result = mysqli_query($con,$sql) or die ("Query error: " . mysqli_error());
$records = array();
while($row = mysqli_fetch_assoc($result)) {
$records[] = $row;
}
mysqli_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
the ShoppingItem field contains an array like ["Tomatos","Apples","Mangos","Bananas"] the SQL returns multiple shoppinglists from a single user, I want to display the shoppinglists on cards with the items of each list in an html list.
Anyone any suggestions? I appreciate the help.
Let me suppose that your JSON endpoint does in fact return the right data -- in this case visiting what you"ve labeled MYURL generates (I believe!) the text:
jsoncallback({"items":["Banana","Cherry","Apple","Strawberry","Pear","Pineapple"]})
Then we can move on to your logic, which consists in this callback function:
function (data, status) {
$.each(data, function (i, item) {
var products = "<br>" + item.item;
var ul = $("<ul>").appendTo("body");
var json = {
items: ["Banana", "Cherry", "Apple", "Strawberry", "Pear", "Pineapple"]
};
$(json.items).each(function (index, item) {
ul.append($(document.createElement("li")).text(item));
});
ownproducts.append(products);
});
}
What is the problem here? There are a lot. The first is that you should probably not be iterating over data, since that is not your array. Instead you should be iterating over data.items.
The second is that you should probably just be creating the HTML rather than creating a ton of DOM stuff. You can use vanilla JS's Array.prototype.map or Array.prototype.join functions rather than delegating this to JQuery: it is a part of the JS spec that this is sufficient:
function (data, status) {
var html = '<ul><li>' + data.items.join('</li><li>') + '</li></ul>';
$(html).appendTo('body');
}

Array json between ajax and php

I'm developing a simple guestbook and I want to update the table with all messages without refreshing the page because if someone it's writing a comment and the page refreshes the comment will be lost.
So I began writing some code with ajax to update the table but I don't know how to send an array (with comment, username, date ecc) from php to ajax.
In the database I have a column named "wrote" and it can be 0 (unread) or 1 (read). 1 it's when the messages it's already on the table.
This is what I've done since now, maybe it's wrong
getGuest.php
<?php
include("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$result = $Database->unreadMessages();
$rows=mysql_fetch_array($result);
echo json_encode($rows);
?>
Script.js
window.onload = function(){
interval = window.setInterval('updateGuest()',5000);
}
function updateGuest() {
$.ajax({
url: 'getGuest.php',
method: 'get',
success: on_getGuest_success,
error: on_error
});
}
function on_getGuest_success(data) {
for(var i=0; i<data.length;i++) {
// HERE I WANT TO ADD A ROW WITH ALL MESSAGE UNREAD BUT I DONT KNOW WHAT I HAVE TO DO
}
}
function on_error() {
//do something
}
Make sure the JSON contains an array
Add headers
use getJSON
Like this:
PHP
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
header("content-type: application/json");
echo json_encode($data);
JS:
$(function() { // when page has loaded
var tId = setInterval(function() { // save the tId to allow to clearTimeout if needed
$.getJSON("getGuest.php",function(data) { // call the server using jQuery's JSON access
$('.guestbook').empty(); // empty the container
var rows = []; // create an array to hold the rows
$.each(data,function(_,item) { // loop over the returned data adding rows to array
rows.push('<tr><td class="name" width="10%">' + item.name + '</td></tr>');
});
$('.guestbook').html(rows.join()); // insert the array as a string
});
},5000); // every 5 secs
});
I would personally only return what was new since last time

Inserting PHP while in JQuery

I am trying to embed a data picker calendar in my php site. The code, which came off the shelf from DatePicker, allows to select some pre-highlighted dates, which is good as I have a list in a db table with the dates I need.
However, I have had no success in finding a way to include php within the script, or the other way round.
The original calendar script is as follows:
<script type='text/javascript'>
$(function() {
$("#txtDate").datepicker({dateFormat: 'yy-mm-dd'});
});
$(document).ready(function() {
var SelectedDates = {};
SelectedDates[new Date('02/24/2014')] = new Date('02/24/2014');
SelectedDates[new Date('03/10/2014')] = new Date('03/10/2014');
$('#txtDate').datepicker({
beforeShowDay: function(date) {
var Highlight = SelectedDates[date];
if (Highlight) {
return [true, "Highlighted", Highlight];
}
else {
return [true, '', ''];
}
}
});
});
</script>
I would like to be able to select a long list of dates to go in
SelectedDates[new Date('03/10/2014')] = new Date('03/10/2014');
so my original idea was to do as follows:
$(document).ready(function() {
var SelectedDates = {};
<?php
$query = "SELECT eventDate FROM database.calendar WHERE tag='R' AND competition='1'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$eventdate = $row[0];
SelectedDates[new Date('$eventdate')] = new Date('$eventdate');
}
?>
Sadly, this doesn't work (and neither do any of the various attempts to re-add tags within the PHP.
Any idea? Thank you so much for your help!
You have to close your PHP tags to output JavaScript (or use echo as mentioned in a comment):
$(document).ready(function() {
var SelectedDates = {};
<?php
$query = "SELECT eventDate FROM database.calendar WHERE tag='R' AND competition='1'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$eventdate = $row[0];
?>
SelectedDates[new Date('<?php echo $eventdate; ?>')] = new Date('<?php echo $eventdate; ?>');
<?php
}
?>
});
Although I should mention that what you are trying to do is not really ideal. Do the PHP while loop separately, get that into an array, and json_encode that.

jquery autocomplete dont return suggestions data onselec

I have input with id aktForm_tiekejas and is jquery autocomplete code:
$('#aktForm_tiekejas').autocomplete({
serviceUrl: '_tiekejas.php',
width: 185,
deferRequestBy: 0,
noCache: true,
onSelect: function(suggestion) {alert('You selected:'+suggestion.value+','+suggestion.data);}
});
_tiekejas.php:
<?php
include("../Setup.php");
$query = ($_GET['query']);
$reply = array();
$reply['query'] = $query;
$reply['suggestions'] = array();
$reply['data'] = array();
$res = mysql_query("SELECT id,pavadinimas FROM sarasas_tiekejas WHERE pavadinimas LIKE '%$query%' ORDER BY pavadinimas ASC");
while ($row = mysql_fetch_array($res)) {
$reply['suggestions'][] = $row['pavadinimas'];
$reply['data'][] = $row['id'];
}
mysql_close();
echo json_encode($reply);
?>
If query is 'vac' php returns from server:
{"query":"vac","suggestions":["UAB Vivacitas"],"data":["866"]}
but
alert('You selected:'+suggestion.value+','+suggestion.data);
doesn't alert data (866)
why?...
Probably because suggestion.value doesn't exist. Looking at your JSON response code I can see the suggestion.data but no suggestion.value. Since JS will be looking for a value that doesn't exist it will throw an error. Also you're missing out the array for the second part of the return. Try this:
alert('You selected: '+suggestion.data[0]);
If you need to iterate through your data subsets do something like:
for(i in suggestion.data){
alert('You selected: '+suggestion.data[i]);
}

Categories

Resources