Datepicker Unavailable dates (data retrieved from database) - php

I'm trying to get dates from my database and put them in an array where it would be stored in json.
MAIN.PHP
$('#datepicker').focus(function(){
$.ajax({
url: 'getDates.php',
data: "artist_name="+$('#name').html(),
dataType: 'json',
success: function(data)
{
}
});
})
getDates.php
$fullname = $_GET['artist_name'];
$result = mysql_query("SELECT .... FROM .... WHERE ... ='$fullname'")
$arraydates = array();
while($details = mysql_fetch_assoc($result)) {
array_push($arraydates, $details['event_date']);
}
echo json_encode($arraydates);
I've managed to put all the dates from the selected artist in the "arraydates".
I found this on google:
var unavailableDates = ["21-8-2013"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
That's fine. But now I'm trying to get the results from the array (within getDates.php) and use them in the "main.php". So basically I want to use the data like above with "unavailableDates" array. (and thus, disable the specific dates within the jquery date picker).
Instead of having "unavailableDates", I have the "arraydates". I don't really know how can I use my array inside the "unavailable" function.
I'm not really good with json, actually it's my first time I used json. So could anyone please help me with that?

you can use jquery:
//...
success: function(data){
var arrayLength=data.length;
for(var i=0;i<arrayLength;i++){
if(unavailable(data[i]){
//your code here
}
}
}
//...

The ajax will return $arraydates in a JSON format. Use parse.JSON(returned value)
for example
success: function(data)
{
var unavailableDates = parse.JSON(data);
//Your code ....
}
Hope that helped.

Related

Display JSON Data in HTML using Laravel 4

Please help me with my problem in displaying JSON data into my view..
my script is:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
$.each(data, function(index, element) {
firstnameID.val(element.first_name);
});
});
});
and my JSON reply is:
{"id":7,"first_name":"John","last_name":"Doe"}
the thing is when i tried to:
alert(element.first_name);
it says UNDEFINED, but when I:
alert(element);
it gives me the value of the last name which is Doe.. my question is how can I then access the other values like the ID and the first name..
EDITED:
this is my route:
Route::get('api/dropdown', function(){
$input = Input::get('option');
$supllier = Supplier::find($input);
returnResponse::json($supllier->select(array('id','first_name','last_name'))
->find($input));
});
Please help me with this one, This is my first time using JSON so im a bit confuse on how this works.
Best Regards
-Melvn
Why are you using each? This should work:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
firstnameID.val(data.first_name);
});
});
Ok, give this a try..
Explicitly state that what you're expecting back from the server is JSON using the dataType option in get().
$('#supplierId').change(function()
{
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data)
{
var firstnameID = $('#firstnameID');
$.each(data, function(index, element)
{
firstnameID.val(element.first_name);
});
},
'json' // <<< this is the dataType
);
});
Now you should be able to access the data using the dot syntax:
console.log("last_name: " + element.last_name);
console.log("first_name: " + element.first_name);
console.log("id: " + element.id);
I would add another few lines, just to check that you're getting back what you expect to see:
console.log("NEW ELEMENT"); // << indicator in the console for your reference
console.log(element); // << the whole "element"

Why won't this ajax.done() work?

I'm writing a "betting" script so-to-speak, and making an automated system.
The bettor will be able to choose to increase the amount or decrease the amount on win or loss.
The PHP script I wrote returns echo json_encode(array('result' => 'win')); or 'loss' for a loss.
Why won't the below code update that value of the amount dependent upon the result?
$(document).ready(function(){
function updateValuesAuto() {
// Grab all the value just incase they're needed.
var multiplier_auto = $('#multiplier_auto').val();
var percentage_auto = $('#percentage_auto').val();
var bet_amount_auto = $('#bet_amount_auto').val();
var profit_amount_auto = $('#profit_amount_auto').val();
multiplier_auto = (100-1)/percentage_auto;
profit_amount_auto = (bet_amount_auto*multiplier_auto)-bet_amount_auto;
$('#multiplier_auto').val(multiplier_auto);
$('#percentage_auto').val(percentage_auto);
$('#bet_amount_auto').val(bet_amount_auto);
$('#profit_amount_auto').val(profit_amount_auto);
}
$('#multiplier_auto').keyup(updateValuesAuto);
$('#percentage_auto').keyup(updateValuesAuto);
$('#bet_amount_auto').keyup(updateValuesAuto);
$('#profit_amount_auto').keyup(updateValuesAuto);
var runI = null;
var $run = $('#start');
var $times = $('#amount_bets');
var $stop = $('#stop');
$run.on('click', function() {
event.preventDefault();
$(this).attr('disabled', true);
$stop.attr('disabled', false);
var ran = 0;
var val = parseInt($times.val(), 10);
if(isNaN(val) || val === 0 ) return false;
runI = setInterval(function() {
if( ran < val ) {
$.ajax({
url: './requests/bet.php',
type: 'POST',
data: { amount: $('#bet_amount_auto').val(), chance: $('#percentage_auto').val(), multiplier: $('#multiplier_auto').val(), profit: $('#profit_amount_auto').val() },
}).done(function(result) {
var result = JSON.parse(result);
if( result === 'win' ) {
$('#bet_amount_auto').val() = $('#bet_amount_auto').val() * $('#wini').val();
}
else if( result === 'loss' ) {
$('#bet_amount_auto').val() = $('#bet_amount_auto').val() * $('#lossi').val();
}
ran++;
});
}
else {
clearInterval(runI);
$run.attr('disabled', false);
}
}, 500);
});
$stop.on('click', function() {
event.preventDefault();
clearInterval(runI);
$run.attr('disabled', false);
});
});
Thanks.
You may want to trim down the code to the specifics of the problem if the answer does not help, but would behoove you to actually look at the data that gets sent back. It will be:
{"result":"win"}
So to access the result in the .done function, you'd need to use result.result.
Additionally, if you are sending JSON back, jQuery may be parsing it automatically and JSON.parse may result in an error. To get jQuery to do this, send the JSON content-type header via PHP:
header("Content-type: application/json");
I believe the problem is === because three equals is a strict operator which means value and type must be equal.
In your case it seems you're trying to make sure that result is type of JSON and equals to STRING
Try double-equals == maybe?
EDIT:
Oh got that now...
Actually, you can't assign value to the result of a function. So,
Change this:
$('#bet_amount_auto').val() = $('#bet_amount_auto').val() * $('#wini').val();
to
$('#bet_amount_auto').val($('#bet_amount_auto').val() * $('#wini').val());
Two things:
1.You cannot set value to functions (You cannot put functions in the left side of an assignment)
2.result is JSON and you need to use result.result
$.ajax({
url: './requests/bet.php',
type: 'POST',
data: { amount: $('#bet_amount_auto').val(), chance: $('#percentage_auto').val(), multiplier: $('#multiplier_auto').val(), profit: $('#profit_amount_auto').val() },
}).done(function(result) {
if( result.result === 'win' ) {
$('#bet_amount_auto').val($('#bet_amount_auto').val() * $('#wini').val()) ;
}
else if( result.result === 'loss' ) {
$('#bet_amount_auto').val($('#bet_amount_auto').val() * $('#lossi').val()) ;
}
ran++;
});

JSON and Highlights on Datepicker

just a quick question about datepicker and json. I have this code:
var dates = {'2013/4/4':'some description' , '2012/6/6':'some other description'};
function date_propogate() {
console.log('in function');
$.getJSON('URL OF JSON', function(data) {
date_items = data.items;
console.log(date_items);
$.each(date_items, function(index, date_item) {
dates.push(date_item.sdate);
});
});
}
$(document).ready(function() {
date_propogate();
$('#datepicker').datepicker({
beforeShowDay: function(date) {
var search = date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + (date.getDate());
if (dates[search]) {
return [true, 'highlight', dates[search] || ''];
}
return [false, '', ''];
}
});
});
The JSON page returns this:
{"items":[{"sdate":"2013-02-25","edate":"2013-02-27","cost":"200","id":"1"}]}
I have two dates which are static which display fine, but the date which is returned by: date_items.sdate is not loading, I am getting an error saying 'no method: push'.
Am I doing this correctly at all or is there a better way? As I'm assuming I can't do it with just php on the page because the js is loading before the php right?
Any help would be hugely appreciated.
You have dates declared as an object using {}, rather than an array using []. You can't call .push() on an object.
dates is an object and an object doesn't have a function called push. Arrays do have these functions.
Anyway, simply do this:
var dates = ['2013/4/4':'some description' , '2012/6/6':'some other description'];
Dates is not an array, so you can't push to it. You would need to define dates as an array
var dates = [{'2013/4/4':'some description'} , {'2012/6/6':'some other description'} ]
The above creates an array of objects.

jQuery AJAX Request Doesn't Work on Page Load, However, It Does Work from Debug Console

Turning off asynchronous requests in jQuery fixed the issue.
I have the following Javascript & AJAX request (using jQuery) in my page:
"use strict";
var hsArea, counter, hotspots, count;
counter = 4;
count = 0;
hotspots = {};
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
});
}
function displayHotspot(type, id, number) {
$.ajax({
url: '/alpha/engine/hotspots/gethotspot.php',
dataType: 'json',
data: {'type' : type, 'id' : id},
success: function(json) {
console.log(json);
var hotspot, extract;
extract = json.content;
extract = extract.replace(/<(?:.|\n)*?>/gm, '');
extract = extract.substring(0, 97);
extract = extract + "...";
json.content = extract;
hotspot = document.createElement("div");
hsArea.append(hotspot);
hotspot.setAttribute('class','hotspot');
hotspot.setAttribute('id','hotspot' + number);
$(hotspot).css('position', 'absolute');
$(hotspot).css('top', number * 100 + 100);
$(hotspot).css('left', number * 100 + 110);
hotspot.innerHTML = "<h1>"+ json.title + "</h1><p>" + json.content + "</p>";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
}
function listHotspots() {
for(count = 0; count < counter; count++) {
(function(count) {
displayHotspot('scribble',hotspots[count], count);
count = count + 1;
})(count);
}
}
function loadHotspots() {
fetchHotspotList();
listHotspots();
}
$(document).ready(function() {
hsArea = $("#hotspotArea");
fetchHotspotList();
listHotspots();
});
(Sorry the formatting is a bit off!) - Now, the $(document).ready() function assigns the hsArea variable as it should, however, a combination of fetchHotspotList() and listHotspots() returns:
Uncaught TypeError: Cannot call method 'replace' of null
However, if in the Google Chrome Javascript console, I run:
loadHotspots();
it fetches the data from the AJAX request and displays it properly on the page. At first I thought the problem was that I Wasn't using the $(document).ready() handler, but adding it hasn't fixed it. Neither has using an onload handler inside of the body tag.
Any help would be greatly appreciated.
Regards,
Ben.
It's probably due to the fact that your listHotSpots function is called before fetchHotSpots returns (since it's an async call).
You're better off chaining the execution of listHotSpots to the completion of fetchHotSpots, like so:
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
listHotSpots();
});
}
You may be better off modifying listHotSpots to take the json data returned from your AJAX call. Hope this helps!

JSON returned as individual string and not objects

I am using Codeigniter and trying to use the jQuery autocomplete with it. I am also using #Phil Sturgeon client rest library for Codeigniter because I am getting the autocomplete data from netflix. I am return correct JSON and I can access the first element with
response(data.autocomplete.autocomplete_item[0].title.short);
but when I loop through the results
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
it acts like a string. Lets say the result is "Swingers", it will return:
Object.value = s
Object.value = w
Object.value = i
and so on.
the js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append(""+item.title+"").appendTo(ul);
};
the controller:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
the json return
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
any ideas?
thanks.
there are some console logs with the return
the url
in, as you've noticed, doesn't do what you'd like with arrays. Use $.each
As far as I know, for (property in object) means that you want to access each of its properties rather than accessing them via the index. If you want to access them via the index, you probably want to use the standard for loop.
for (i = 0; i <= 10; i++) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
or if you still want to use your code, try this:
for (i in data.autocomplete.autocomplete_item) {
response(i.title.short);
}
I haven't test them yet but I think you have the idea.
ok I figured out the correct format that I need to send to the autocomplete response method:
the view
$("#movies").autocomplete({
minLength: 2,
source: function(request, response) {
$.post("<?php echo base_url();?>welcome/search", {q: request.term},
function(data){
//console.log(data);
response(data);
}, 'json');
}
});
the controller:
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// Pull in an array
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'),'json');
$json = array();
foreach($netflix_query->autocomplete->autocomplete_item as $item){
$temp = array("label" => $item->title->short);
array_push($json,$temp);
}
echo json_encode($json);
what was needed was to send back to the view an array of objects. Thank you guys for all your answers and help!!

Categories