JSON/PHP script and callbacks [duplicate] - php

This is my JSONP file:
<?php
header('Content-type: application/javascript;');
header("access-control-allow-origin: *");
header("Access-Control-Allow-Methods: GET");
//db connection detils
$host = "localhost";
$user = "test";
$password = "test";
$database = "myradiostation1";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT *, DATE_FORMAT(start, '%d/%m/%Y %H:%i:%s') AS start,
DATE_FORMAT(end, '%d/%m/%Y %H:%i:%s') AS end FROM radiostation1");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$shows[$x] = array("id" => $row["id"], "startminutes" => $row["startminutes"], "start" => $row["start"], "endminutes" => $row["endminutes"],"end" => $row["end"],"mediumname" => $row["mediumname"], "longname" => $row["longname"], "description" => $row["description"],"short_id" => $row["short_id"],"promomessage" => $row["promomessage"],"email" => $row["email"],"phonenumber" => $row["phonenumber"],"textnumber" => $row["textnumber"],"textprefix" => $row["textprefix"],"showimage" => $row["showimage"],"longdescription" => $row["longdescription"],"facebooklink" => $row["facebooklink"],"otherlink" => $row["otherlink"],"websitelink" => $row["websitelink"],"keywords" => $row["keywords"] );
}
//echo JSON to page
$response = $_GET["callback"] . "(" . json_encode($shows) . ");";
echo $response;
?>
It does work, up to a point, but getting the {"success":true,"error":"","data":{"schedule": as seen at this site before my json_encode is where I am.
However, I cannot get it to display any data in my table, although it DOES produce code on-screen when I view it at http://www.myradio1.localhost/onairschedule.php.
The actual code is stored at http://www.myradiostations.localhost/schedule.php
and the callback function works OK, one example being http://www.myradiostations.localhost/schedule.php?callback=?&name=Northern+FM and http://www.myradiostations.localhost/schedule.php?callback=?&name=Southern+FM but what do I need to do to make it change like in these examples:
this example and this example, and to generate an error message like this if no such file exists.
I'm halfway there, just need some advice on fixing my code!
Basically, what I'm trying to do... get a JSONP to work in my HTML table which will vary the content depending on the URL in my javascript file on my page, which is:
var doFades = true;
var LocalhostRadioStations = {
Schedule : {}
};
$(document).ready(function(){
LocalhostRadioStations.Schedule.days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
LocalhostRadioStations.Schedule.Show = function () {
_s = null;
_startDate = null;
_endDate = null;
this.days = LocalhostRadioStations.Schedule.days;
_selector = '';
this.setShow = function(s) {
this._s = s;
this._startDate = new Date( parseInt(s.startminutes, 10) * 1000);
this._endDate = new Date(parseInt(s.endminutes, 10) * 1000 );
};
this.getEndDate = function(){
return this._endDate;
}
this.getStartDate = function(){
return this._startDate;
}
this._getShowDay = function (){
return this.days[this.getStartDate().getDay()];
};
this._getShowUnitsTaken = function(){
// if it's the same day
return this._getEndUnits() - this._getStartUnits();
};
this._getEndUnits = function(){
if(this.getEndDate().getHours() == 0)
{
//console.log(this._s.longname +' ends at midnight');
return 48;
}
return this.getEndDate().getMinutes() !== 0 ? (this.getEndDate().getHours() * 2) : (this.getEndDate().getHours() * 2);
};
this._getStartUnits = function(){
if(this.getStartDate().getHours() == 0)
{
return 0;
}
return this.getStartDate().getMinutes() !== 0 ? (this.getStartDate().getHours() * 2) : (this.getStartDate().getHours() * 2);
};
this.getCellPositions = function() {
return {
'start' : this.getStartDate(),
'end' : this.getEndDate(),
'colIndex' : this.getStartDate().getDay() + 2,
'startUnits' : this._getStartUnits(),
'endUnits' : this._getEndUnits(),
'unitsTaken' : this._getShowUnitsTaken()
}
};
this.pad = function(number){
return number < 10 ? '0'+number : number;
};
// return the table cell html.
this.toHtml = function () {
var d = new Date();
var units = this._getStartUnits();
var rowspan = this._getShowUnitsTaken();
var desc = this._s.description;
var name = this._s.longname;
var starttime = this.pad(this.getStartDate().getHours()) + ':' + this.pad(this.getStartDate().getMinutes());
var endtime = this.pad(this.getEndDate().getHours()) + ':' + this.pad(this.getEndDate().getMinutes());
var site = this._s.websitelink;
var cls = this.isActive() ? 'current-program' : '';
var isToday = this.getStartDate().getDay() === d.getDay() ? 'active-program' : '';
var html = '<td class="schedule-show ' + isToday + ' ' + cls + '" rowspan="' + rowspan + '" data-start="' + this.getStartDate() + '" data-end="' + this.getEndDate() + '">';
html += '<div>';
html += '' + name + '';
html += '</div>';
if(doFades)
{
html += '<div class="schedule_details clearfix" style="display:none;">';
html += '<img width="105px" height="105px" alt="' + desc + '" src="' + this._s.showimage + '">';
html += '<strong>' + name + '</strong>';
html += '<p>' + desc + '</p>';
html += '<span>' + starttime + ' - ' + endtime +'</span>';
html += '</div>';
}
html += '</td>';
return html;
};
this.setTableSelector = function(sel){
this._selector = sel;
};
// check if we should add the active class.
this.isActive = function(){
var t = new Date();
return t >= this.getStartDate() && t <= this.getEndDate();
};
};
LocalhostRadioStations.Schedule.ScheduleGen = function(){
return {
insertShow : function(show) {
var p = show.getCellPositions();
$('tr#units-' + p.startUnits).append(show.toHtml());
},
init : function (stationName){
var self = this;
// load the schedule.
$.getJSON('http://www.myradiostations.localhost/schedule.php?callback=?&name=', {
name: 'Northern FM'
}, function(json){
// loop each show and append to our giant table.
// this is well sick.
if(json.success === false)
{
$('.content-inner table').remove();
$('<div>errors</div>').appendTo('.content-inner');
}
else
{
var currentDay = '';
var day = 0;
// highlight the current time..
var d = new Date();
var weekStart = new Date();
weekStart.setDate(d.getDate()-6-(d.getDay()||7));
$.each(json.data.schedule, function(i, broadcast){
var dStart = new Date( parseInt(broadcast.startminutes, 10) * 1000);
var dEnd = new Date(parseInt(broadcast.endminutes, 10) * 1000 );
/*// transform to a show object defined above, if the show spans 2 days we create two show objects.
// IF THE SHOW STARTS/ENDS AT MIDNIGHT, DON'T SPLIT IT.
if(dStart.getHours() !== 0 && dEnd.getHours() !== 0 && dStart.getDate() != dEnd.getDate())
{
var showOne = new LocalhostRadioStations.Schedule.Show();
showOne.setShow(broadcast);
// set to midnight
showOne.getEndDate().setHours(0);
showOne.getEndDate().setMinutes(dStart.getMinutes());
// append first half of show.
self.insertShow(showOne);
// handle second half.
var showTwo = new LocalhostRadioStations.Schedule.Show();
showTwo.setShow(broadcast);
showTwo.getStartDate().setDate(showTwo.getStartDate().getDate() + 1);
showTwo.getStartDate().setHours(0);
showTwo.getStartDate().setMinutes(dEnd.getMinutes());
//console.log('2nd Half Start: ' + showTwo.getStartDate());
//console.log('2nd Half End: ' + showTwo.getEndDate());
self.insertShow(showTwo);
}
else
{*/
var show = new LocalhostRadioStations.Schedule.Show();
show.setShow(broadcast);
show.setTableSelector('table#schedule');
// add the show to the table. Thankfully the order these come out the API means they get added
// in the right place. So don't change the schedule builder code!
self.insertShow(show);
//}
});
var days = LocalhostRadioStations.Schedule.days;
// apply the current day / time classes
$('th:contains('+ days[d.getDay()]+')').addClass('active');
$('td.time').each(function(i, cell){
// get the value, convert to int.
var hours = $(cell).html().split(':')[0];
// compare the hours with now, add class if matched.
if(parseInt(hours, 10) === d.getHours())
{
$(cell).addClass('current_time');
}
});
}
if(doFades)
{
// apply events to show info fade in / out.
$('td.schedule-show').hover(function(){
$(this).find('.schedule_details').fadeIn('fast');
}, function(){
$(this).find('.schedule_details').fadeOut('fast');
});
}
});
}
};
}();
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
});
It should change the schedule according to the JSONP, but what do I do to fix it?
Basically, I am trying to make my own localhost version of http://radioplayer.bauerradio.com/schedule.php?callback=&name=Rock+FM and its JSON / JSONP (I am not sure exactly what type the original is, but then again the site is experimental and on a .localhost domain) for testing purposes where the content is taken from the database, and changes according to station name, e.g. http://radioplayer.bauerradio.com/schedule.php?callback=&name=Metro+Radio and http://radioplayer.bauerradio.com/schedule.php?callback=&name=Forth+One etc.
Edit: The full code for my page can be seen at http://pastebin.com/ENhR6Q9j

I'm not sure exactly what's missing, but from the code you gave so far, I made a jsfiddle:
Demo
I modified some things to make it work (mostly appending stuff), because I don't know your original HTML file. But I also made some changes based on what you say you wanted. First of all I modified your $.getJSON call to be something like:
$.getJSON('http://radioplayer.bauerradio.com/schedule.php?callback=?', {
name: stationName //stationName is from the argument passed
}, function(json){...})
Which should give back the station based on what is passed to
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
To make it more interesting, I also added a bit of code that reads from the url. In this case if you go to the page with a domain.htm/page?Northern FM it will read the text after the ? and put it in twittiName.
var twittiName="Rock FM"; //default station
if(window.location.search){
twittiName=window.location.search.substring(1) //or window.location.hash
}
Tried to look for other stations that might be on your publics site, but so far I could only test with "?Rock+FM". But does mean you can show the errors, which your code can handle as it is.
?Rock+FM
?Random Name
So it seems that your code mostly works but do comment if I have missed anything.

Related

JSONP and GET with callbacks - help needed correcting errors

This is my JSONP file:
<?php
header('Content-type: application/javascript;');
header("access-control-allow-origin: *");
header("Access-Control-Allow-Methods: GET");
//db connection detils
$host = "localhost";
$user = "test";
$password = "test";
$database = "myradiostation1";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT *, DATE_FORMAT(start, '%d/%m/%Y %H:%i:%s') AS start,
DATE_FORMAT(end, '%d/%m/%Y %H:%i:%s') AS end FROM radiostation1");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$shows[$x] = array("id" => $row["id"], "startminutes" => $row["startminutes"], "start" => $row["start"], "endminutes" => $row["endminutes"],"end" => $row["end"],"mediumname" => $row["mediumname"], "longname" => $row["longname"], "description" => $row["description"],"short_id" => $row["short_id"],"promomessage" => $row["promomessage"],"email" => $row["email"],"phonenumber" => $row["phonenumber"],"textnumber" => $row["textnumber"],"textprefix" => $row["textprefix"],"showimage" => $row["showimage"],"longdescription" => $row["longdescription"],"facebooklink" => $row["facebooklink"],"otherlink" => $row["otherlink"],"websitelink" => $row["websitelink"],"keywords" => $row["keywords"] );
}
//echo JSON to page
$response = $_GET["callback"] . "(" . json_encode($shows) . ");";
echo $response;
?>
It does work, up to a point, but getting the {"success":true,"error":"","data":{"schedule": as seen at this site before my json_encode is where I am.
However, I cannot get it to display any data in my table, although it DOES produce code on-screen when I view it at http://www.myradio1.localhost/onairschedule.php.
The actual code is stored at http://www.myradiostations.localhost/schedule.php
and the callback function works OK, one example being http://www.myradiostations.localhost/schedule.php?callback=?&name=Northern+FM and http://www.myradiostations.localhost/schedule.php?callback=?&name=Southern+FM but what do I need to do to make it change like in these examples:
this example and this example, and to generate an error message like this if no such file exists.
I'm halfway there, just need some advice on fixing my code!
Basically, what I'm trying to do... get a JSONP to work in my HTML table which will vary the content depending on the URL in my javascript file on my page, which is:
var doFades = true;
var LocalhostRadioStations = {
Schedule : {}
};
$(document).ready(function(){
LocalhostRadioStations.Schedule.days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
LocalhostRadioStations.Schedule.Show = function () {
_s = null;
_startDate = null;
_endDate = null;
this.days = LocalhostRadioStations.Schedule.days;
_selector = '';
this.setShow = function(s) {
this._s = s;
this._startDate = new Date( parseInt(s.startminutes, 10) * 1000);
this._endDate = new Date(parseInt(s.endminutes, 10) * 1000 );
};
this.getEndDate = function(){
return this._endDate;
}
this.getStartDate = function(){
return this._startDate;
}
this._getShowDay = function (){
return this.days[this.getStartDate().getDay()];
};
this._getShowUnitsTaken = function(){
// if it's the same day
return this._getEndUnits() - this._getStartUnits();
};
this._getEndUnits = function(){
if(this.getEndDate().getHours() == 0)
{
//console.log(this._s.longname +' ends at midnight');
return 48;
}
return this.getEndDate().getMinutes() !== 0 ? (this.getEndDate().getHours() * 2) : (this.getEndDate().getHours() * 2);
};
this._getStartUnits = function(){
if(this.getStartDate().getHours() == 0)
{
return 0;
}
return this.getStartDate().getMinutes() !== 0 ? (this.getStartDate().getHours() * 2) : (this.getStartDate().getHours() * 2);
};
this.getCellPositions = function() {
return {
'start' : this.getStartDate(),
'end' : this.getEndDate(),
'colIndex' : this.getStartDate().getDay() + 2,
'startUnits' : this._getStartUnits(),
'endUnits' : this._getEndUnits(),
'unitsTaken' : this._getShowUnitsTaken()
}
};
this.pad = function(number){
return number < 10 ? '0'+number : number;
};
// return the table cell html.
this.toHtml = function () {
var d = new Date();
var units = this._getStartUnits();
var rowspan = this._getShowUnitsTaken();
var desc = this._s.description;
var name = this._s.longname;
var starttime = this.pad(this.getStartDate().getHours()) + ':' + this.pad(this.getStartDate().getMinutes());
var endtime = this.pad(this.getEndDate().getHours()) + ':' + this.pad(this.getEndDate().getMinutes());
var site = this._s.websitelink;
var cls = this.isActive() ? 'current-program' : '';
var isToday = this.getStartDate().getDay() === d.getDay() ? 'active-program' : '';
var html = '<td class="schedule-show ' + isToday + ' ' + cls + '" rowspan="' + rowspan + '" data-start="' + this.getStartDate() + '" data-end="' + this.getEndDate() + '">';
html += '<div>';
html += '' + name + '';
html += '</div>';
if(doFades)
{
html += '<div class="schedule_details clearfix" style="display:none;">';
html += '<img width="105px" height="105px" alt="' + desc + '" src="' + this._s.showimage + '">';
html += '<strong>' + name + '</strong>';
html += '<p>' + desc + '</p>';
html += '<span>' + starttime + ' - ' + endtime +'</span>';
html += '</div>';
}
html += '</td>';
return html;
};
this.setTableSelector = function(sel){
this._selector = sel;
};
// check if we should add the active class.
this.isActive = function(){
var t = new Date();
return t >= this.getStartDate() && t <= this.getEndDate();
};
};
LocalhostRadioStations.Schedule.ScheduleGen = function(){
return {
insertShow : function(show) {
var p = show.getCellPositions();
$('tr#units-' + p.startUnits).append(show.toHtml());
},
init : function (stationName){
var self = this;
// load the schedule.
$.getJSON('http://www.myradiostations.localhost/schedule.php?callback=?&name=', {
name: 'Northern FM'
}, function(json){
// loop each show and append to our giant table.
// this is well sick.
if(json.success === false)
{
$('.content-inner table').remove();
$('<div>errors</div>').appendTo('.content-inner');
}
else
{
var currentDay = '';
var day = 0;
// highlight the current time..
var d = new Date();
var weekStart = new Date();
weekStart.setDate(d.getDate()-6-(d.getDay()||7));
$.each(json.data.schedule, function(i, broadcast){
var dStart = new Date( parseInt(broadcast.startminutes, 10) * 1000);
var dEnd = new Date(parseInt(broadcast.endminutes, 10) * 1000 );
/*// transform to a show object defined above, if the show spans 2 days we create two show objects.
// IF THE SHOW STARTS/ENDS AT MIDNIGHT, DON'T SPLIT IT.
if(dStart.getHours() !== 0 && dEnd.getHours() !== 0 && dStart.getDate() != dEnd.getDate())
{
var showOne = new LocalhostRadioStations.Schedule.Show();
showOne.setShow(broadcast);
// set to midnight
showOne.getEndDate().setHours(0);
showOne.getEndDate().setMinutes(dStart.getMinutes());
// append first half of show.
self.insertShow(showOne);
// handle second half.
var showTwo = new LocalhostRadioStations.Schedule.Show();
showTwo.setShow(broadcast);
showTwo.getStartDate().setDate(showTwo.getStartDate().getDate() + 1);
showTwo.getStartDate().setHours(0);
showTwo.getStartDate().setMinutes(dEnd.getMinutes());
//console.log('2nd Half Start: ' + showTwo.getStartDate());
//console.log('2nd Half End: ' + showTwo.getEndDate());
self.insertShow(showTwo);
}
else
{*/
var show = new LocalhostRadioStations.Schedule.Show();
show.setShow(broadcast);
show.setTableSelector('table#schedule');
// add the show to the table. Thankfully the order these come out the API means they get added
// in the right place. So don't change the schedule builder code!
self.insertShow(show);
//}
});
var days = LocalhostRadioStations.Schedule.days;
// apply the current day / time classes
$('th:contains('+ days[d.getDay()]+')').addClass('active');
$('td.time').each(function(i, cell){
// get the value, convert to int.
var hours = $(cell).html().split(':')[0];
// compare the hours with now, add class if matched.
if(parseInt(hours, 10) === d.getHours())
{
$(cell).addClass('current_time');
}
});
}
if(doFades)
{
// apply events to show info fade in / out.
$('td.schedule-show').hover(function(){
$(this).find('.schedule_details').fadeIn('fast');
}, function(){
$(this).find('.schedule_details').fadeOut('fast');
});
}
});
}
};
}();
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
});
It should change the schedule according to the JSONP, but what do I do to fix it?
Basically, I am trying to make my own localhost version of http://radioplayer.bauerradio.com/schedule.php?callback=&name=Rock+FM and its JSON / JSONP (I am not sure exactly what type the original is, but then again the site is experimental and on a .localhost domain) for testing purposes where the content is taken from the database, and changes according to station name, e.g. http://radioplayer.bauerradio.com/schedule.php?callback=&name=Metro+Radio and http://radioplayer.bauerradio.com/schedule.php?callback=&name=Forth+One etc.
Edit: The full code for my page can be seen at http://pastebin.com/ENhR6Q9j
I'm not sure exactly what's missing, but from the code you gave so far, I made a jsfiddle:
Demo
I modified some things to make it work (mostly appending stuff), because I don't know your original HTML file. But I also made some changes based on what you say you wanted. First of all I modified your $.getJSON call to be something like:
$.getJSON('http://radioplayer.bauerradio.com/schedule.php?callback=?', {
name: stationName //stationName is from the argument passed
}, function(json){...})
Which should give back the station based on what is passed to
LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);
To make it more interesting, I also added a bit of code that reads from the url. In this case if you go to the page with a domain.htm/page?Northern FM it will read the text after the ? and put it in twittiName.
var twittiName="Rock FM"; //default station
if(window.location.search){
twittiName=window.location.search.substring(1) //or window.location.hash
}
Tried to look for other stations that might be on your publics site, but so far I could only test with "?Rock+FM". But does mean you can show the errors, which your code can handle as it is.
?Rock+FM
?Random Name
So it seems that your code mostly works but do comment if I have missed anything.

JQuery Post Not Passing Data Values to Php File

I am using the jQuery function $.post to pass some values to a php file, which then uses those values to refer to a mySQL database and parse out the resulting value in the post success function. However for some reason when I try and grab the data in the php file using the $_POST tag I am getting the notice that the indexes are undefined. Here is my js code:
var curX = 2;
var curY = 6;
function move(moveX, moveY) {
var position = {
x: curX + moveX,
y: curY + moveY
}
$.post('php/tilecheck.php', position, function(data) {
//console.log(data);
curX += moveX;
curY += moveY;
var n = data.split("\"");
boundary(n[3], n[1]);
boundary(n[7], n[5]);
boundary(n[11], n[9]);
boundary(n[15], n[13]);
/*boundary(data.left,'left');
boundary(data.right, 'right');
boundary(data.top, 'top');
boundary(data.bottom, 'bottom');*/
})
}
function boundary(value, pos) {
if(value == 1){
$("#a" + pos).css('display', 'none');
}
else {
$("#a" + pos).css('display', '');
}
}
And the php file it refers to:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
include('db-info.php');
$x = $_POST['x'];
$y = $_POST['y'];
if(!empty($_POST)) {
$q = "SELECT * FROM tiles WHERE xpos = ".($x - 1)." AND ypos = $y LIMIT 1";
$lefttile = mysql_fetch_assoc(mysql_query($q));
$q = "SELECT * FROM tiles WHERE xpos = ".($x + 1)." AND ypos = $y LIMIT 1";
$righttile = mysql_fetch_assoc(mysql_query($q));
$q = "SELECT * FROM tiles WHERE xpos = $x AND ypos = ".($y - 1)." LIMIT 1";
$toptile = mysql_fetch_assoc(mysql_query($q));
$q = "SELECT * FROM tiles WHERE xpos = $x AND ypos = ".($y + 1)." LIMIT 1";
$bottomtile = mysql_fetch_assoc(mysql_query($q));
$json = array(
"left" => $lefttile['bound'], "right" => $righttile['bound'],
"top" => $toptile['bound'], "bottom" => $bottomtile['bound']
);
$output = json_encode($json);
echo $output;
}
else
echo "No value";
?>
Whats weird is even though the values are undefined in the php, it still outputs the correct data in an array, which is confirmed by the console log. However, to access those values in the array I have to use the fixed call to the function boundary(), while the commented out code doesn't work. Please let me know if you have any ideas or questions. Thank you.
One try from me .. You have JSON responde.. so you can use it.
!! There is need to be added one check before the LOOP, to see if the responde is successfull or not how ever this is my idea ..
$.ajax({
url: 'php/tilecheck.php',
data: position,
type: 'POST',
dataType: 'json',
success: function(data) {
$.each(data, function(key,value){
if(value == 1){
$("#a" + key).css('display', 'none');
}
else {
$("#a" + key).css('display', '');
}
});
}
});
Check what you get from jQuery in PHP :
print_r($_POST);
and check the proper naming of 'x' and 'y'

json encoded php variable into javascript

I'm retrieving data from MySql with php like this =>
while ($birthday_row = $birthday_r->fetch_row()){
$birthday_array[] = array(
'title' => $birthday_row[0],
'start' => $birthday_row[1] . "-" . $birthday_row[2]
);
}
JavaScript:
var json_obj_birthday = <?php if (isset($birthday_array)){echo json_encode($birthday_array);} ?>;
var json_obj_birthday_len = json_obj_birthday.length;
var d = new Date();
var event = [];
for (var i=0;i<json_obj_birthday_len;i++){ // adding manually year
json_obj_birthday[i].start = d.getFullYear() + "-" + json_obj_birthday[i].start;
event = {
'title' : json_obj_birthday[i].title,
'start' : json_obj_birthday[i].start
};
}
In above JavaScript code into event array is stored only for first data , it only stores for json_obj_birthday[0], how can I store all information into event array ? thanks
PS. I want that array event be json encoded with full information
UPDATE
now I've tried like this
var events = <?php if (isset($birthday_array)){echo json_encode($birthday_array);} ?>;
var d = new Date();
for (var i = 0; i < events.length; i++){
events[i].start = d.getFullYear() + "-" + events[i].start;
}
and doesn't get desire result as well
Second Update
I need what I'm trying to do because want to pass this event variable into jQuery full calendar, here is script =>
jQuery("#calendar").fullCalendar({ // initialize full calendar
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
events: [
event
] // here was my fault , I must to have `events: event,`
});
After tying your code guys , information into calendar doesn't inserted , That's what I mean doesn't work
PS. If someone interested more deeply what I am doing and why , pls take a look at my previous question too add birthday events into jQuery full calendar each year
Why not assign the json directly to events, then correct the start entries?
var events = <?php echo isset($birthday_array) ? json_encode($birthday_array) : "[]" ?>;
var d = new Date();
for (var i = 0; i < events.length; i++){
events[i].start = d.getFullYear() + "-" + events[i].start;
}
Note that I added a clause to the PHP so that if $birthday_array is not set, javascript recieves an empty array, rather than a syntax error.
Your code doesn't work because the line event = { ... } replaces the array stored in event with a single javascript object.
PHP:
while ($birthday_row = $birthday_r->fetch_row()){
$birthday_array[] = array(
'title' => $birthday_row[0],
'start' => $birthday_row[1] . "-" . $birthday_row[2]
);
}
JavaScript:
var json_obj_birthday = <?php if (isset($birthday_array)){echo json_encode($birthday_array);} ?>;
var json_obj_birthday_len = json_obj_birthday.length;
var d = new Date();
var event = [];
for (var i=0;i<json_obj_birthday_len;i++){ // adding manually year
json_obj_birthday[i].start = d.getFullYear() + "-" + json_obj_birthday[i].start;
event.push({
'title' : json_obj_birthday[i].title,
'start' : json_obj_birthday[i].start
});
}
I think your whole approach here is wrong. Here's how I would do it (additionally, it won't show up warnings/notices):
<?php
$birthday_array = array();
while ($birthday_row = $birthday_r->fetch_row()){
$birthday_array[] = array(
'title' => $birthday_row[0],
'start' => $birthday_row[1] . "-" . $birthday_row[2],
);
}
?><script type="text/javascript">
var json_obj_birthday = <?php echo json_encode($birthday_array); ?>;
var json_obj_birthday_len = json_obj_birthday.length;
var d = new Date();
var event = [];
for (var i=0; i < json_obj_birthday_len; i++){ // adding manually year
json_obj_birthday[i].start = d.getFullYear() + "-" + json_obj_birthday[i].start;
event.push({
'title' : json_obj_birthday[i].title,
'start' : json_obj_birthday[i].start
});
}
</script>
My advice here is; always declare variables ... never just append/increment/etc to imaginary variables.
Finally, while there's nothing wrong with offloading some processing to client-side javascript, you might want to consider putting it inside the PHP / server-side. Just a small note, not really critical.
var json_obj_birthday = <?php if (isset($birthday_array)){echo json_encode($birthday_array);} ?>;
var json_obj_birthday_len = json_obj_birthday.length;
var d = new Date();
var event = [];
for (var i=0;i<json_obj_birthday_len;i++){ // adding manually year
json_obj_birthday[i].start = d.getFullYear() + "-" + json_obj_birthday[i].start;
var event2 = {
'title' : json_obj_birthday[i].title,
'start' : json_obj_birthday[i].start
};
event.push(event2);
}
try this in javascript

How to use inArray and make awesome TicTacToe (Noughts and Crosses) with jQuery

I made a TicTacToe Game! Just for fun. It works and all, but can't tell once someone has won. I used .inArray to look for winning solutions on the current board. The idea is once a winning combination of squares is on the board, an alert will pop up ("You won Bruh"). Maybe the inArray is comparing the win arrays to the chosen elements opposed to the elements of the win arrays to the chosen elements? I'm stumped. Check out the jsfiddle if you're interested and leave a response if you've figured it out. Thanks. http://jsfiddle.net/QH6W9/7/
//UPDATE
I ended up using a magic square and checking if combinations of 3 added to 15 and implemented self teaching and basic AI using possible combinations and a MySQL db. I used a second script to let the computer play itself and build up the database. It's not the most perfect code but see for yourself..
//---//--//--//--//--//--//---//--//--//--//--//---//
// TIC-TAC-TOE: //
//Good Old game. This version is meant to be a self//
//teaching system as a means to utilise and master //
//exchange between web-page, server and database. //
//---//--//--//--//--//--//---//--//--//--//--//---//
// Author: Dylan Madisetti
// Date: I don't remember?
$(document).ready(function(){
var magiclist = [8,3,4,1,5,9,6,7,2]; //for humans
var squares = [8,3,4,1,5,9,6,7,2]; //Le Magic Square\\
var xs = []; //------------//
var os = []; // 8 | 3 | 4 //
var x = 0; //----+---+---//
var o = 0; // 1 | 5 | 9 //
var gameover = -1; //----+---+---//
var FirstMoves = []; // 6 | 7 | 2 //
var SecondMoves = []; //------------//
var ThirdMoves = []; //All Diagonals,rows and Columns add to 15\\
var moves = [];
var i = 0;
win = false;
end = false;
// I have a radio button for whether the human plays as x or o
if(document.getElementById('human').checked) {
humanmove("x",x,xs,moves,squares,gameover,i,magiclist,"o",o,os); //human move
}else{
ajaxmove("x",x,xs,moves,squares,gameover,i,magiclist,"o",o,os); //computer move
x++;
i++;
humanmove("o",o,os,moves,squares,gameover,i,magiclist,"x",x,xs); //human move
};
});
//---//--//--//--//--//--//--//--//--//--//--//---//
// AjaxMove Desc. Checks if can win or block if it//
//can't, Sends data to MYSQLtest which in turn //
//queries xos database and returns best move is //
//then used. //
//---//--//--//--//--//--//--//--//--//--//--//---//
function ajaxmove(status,counter,turn,moves,squares,gameover,i,magiclist,otherturn){
bestmove = 0;
if (turn.length >= 2){ //goes through each possibility
FirstMoves = turn.slice(0);
while (FirstMoves.length > 1){
FirstX = FirstMoves[0];
SecondMoves = FirstMoves.slice(1);
ThirdMoves = squares.slice(0);
$.each (SecondMoves,function(){
if (ThirdMoves.length > 0){
SecondX = this;
$.each (ThirdMoves,function(){
ThirdX = this;
if (FirstX + SecondX + ThirdX == 15){
bestmove = this;
};
});
ThirdMoves = ThirdMoves.slice(1);
};
});
FirstMoves = FirstMoves.slice(1);
}
};
if ((bestmove == 0) && (otherturn.length >= 2)){
FirstMoves = otherturn.slice(0);
while (FirstMoves.length > 1){
FirstX = FirstMoves[0];
SecondMoves = FirstMoves.slice(1);
ThirdMoves = squares.slice(0);
$.each (SecondMoves,function(){
if (ThirdMoves.length > 0){
SecondX = this;
$.each (ThirdMoves,function(){
ThirdX = this;
if (FirstX + SecondX + ThirdX == 15){
bestmove = this;
};
});
ThirdMoves = ThirdMoves.slice(1);
};
});
FirstMoves = FirstMoves.slice(1);
}
};
if (bestmove == 0){
$.ajax({type:'POST',
async: false,
url:'/XOsAI/MYSQLtest.php',
data:{
status: status,
moves: moves,
remaining: squares,
gameover: gameover
},
success:
function(data){
bestmove = data;
}
});
};
bestmove = Number(bestmove);
index = squares.indexOf(bestmove);
turn[counter] = bestmove;
select = magiclist.indexOf(bestmove);
$('.square').eq(select).addClass(status);
$('.square').eq(select).addClass('clicked');
squares.splice(index,1);
moves[i] = turn[counter];
gamecheck(turn,squares,moves); //game check (see below)
if (win) {
alert ("You Lose!");
while (i <= 9){
i++;
moves[i] = "'" + status + "'";
};
$.ajax({type:'POST',
async: false,
url:'/XOsAI/MYSQLtest.php',
data:{
status: status,
moves: moves,
remaining: squares,
gameover: gameover
}
});
};
};
//---//--//--//--//--//--//--//--//--//--//--//---//
// HumanMove Desc. Allows human to make a move and//
//checks if they have won.Updates Database if so. //
//Also Triggers computer move. //
//---//--//--//--//--//--//--//--//--//--//--//---//
function humanmove(status,counter,turn,
moves,squares,gameover,
i,magiclist,otherstatus,
othercounter,otherturn){
$(".XOs").on('click', '.square:not(.clicked)', function() {
if (gameover == -1){
if (!$(this).hasClass("clicked")) {
$(this).addClass('clicked');
$(this).addClass(status);
data = magiclist[$('.square').index(this)];
turn[counter] = data;
index = squares.indexOf(data);
squares.splice(index,1);
moves[i] = turn[counter];
gamecheck(turn,squares,moves); //game check (see below)
if (!(end)){
if (win) {
alert ("You Win!");
gameover = 1;
while (i <= 9){
i++;
moves[i] = "'" + status + "'";
};
$.ajax({type:'POST',
async: false,
url:'/XOsAI/MYSQLtest.php',
data:{
status: status,
moves: moves,
remaining: squares,
gameover: gameover
}
});
$('.squares').addClass('clicked');
};
counter++;
i++;
if (gameover == -1){
ajaxmove(otherstatus,othercounter,otherturn,moves,squares,gameover,i,magiclist,turn); //computer move
othercounter++;
i++;
if (win) {gameover = 1;};
};
};
};
};
});
};
//---//--//--//--//--//--//--//--//--//--//--//---//
// GameCheck Desc. Runs through each possibility.//
//As data locations of divs are arranged in magic //
//square, checks if any three add to 15. Checks //
//for cat game as well. //
//---//--//--//--//--//--//--//--//--//--//--//---//
function gamecheck(turn,squares,moves){
if (turn.length >= 3){
FirstMoves = turn.slice(0);
while (FirstMoves.length >= 3){
FirstX = FirstMoves[0];
SecondMoves = FirstMoves.slice(1);
ThirdMoves = SecondMoves.slice(1);
$.each (SecondMoves,function(){
if (ThirdMoves.length > 0){
SecondX = this;
$.each (ThirdMoves,function(){
ThirdX = this;
if (FirstX + SecondX + ThirdX == 15){
win = true;
};
});
ThirdMoves = ThirdMoves.slice(1);
};
});
FirstMoves = FirstMoves.slice(1);
}
};
if (!(squares.length > 0) && win == false) { //if any remain
alert ("You Draw!");
gameover = 1;
moves[9] = "'c'";
$.ajax({type:'POST', //ajax to tell server Cat Game
async: false,
url:'/XOsAI/MYSQLtest.php',
data:{
status: "c",
moves: moves,
remaining: squares,
gameover: gameover
}
});
end = true;
};
};
and the php if anyone is interested
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
$con = mysqli_connect($host,$user,$pass,$databaseName);
$dbs = mysqli_select_db($con,$databaseName);
//--------------------------------------------------------------------------
// 2) Query database for bestmove or insert data if gameover
//--------------------------------------------------------------------------
$gameover = 0;
$col = 0;
$status = $_POST['status'];
$moves = $_POST['moves'];
$gameover = $_POST['gameover'];
$remaining = $_POST['remaining'];
$bestresult = 0;
if ($gameover < 0){
$required = (count($remaining) * 50); //seemed large enough to make a smart move
if (count($moves) > 0){
foreach ($moves as $move){
$columns[$col].=' AND ';
$columns[$col].= '`';
$columns[$col].= ($col + 1);
$columns[$col].= '`=';
$columns[$col].= $move;
$col++;
};
$moves = implode(' ',$columns);
};
$sql = '
SELECT *
FROM xos
WHERE status=\'';
$sql .= $status;
$sql .= '\' ';
if (count($moves) > 0){
$sql .= $moves ;
};
$results = mysqli_query($con,$sql); //fetch result
$results = $results->num_rows;
echo $con->error;
if ($results > $required){
if (count($moves) == 0){
$col = 1;
};
$reset = $sql;
foreach ($remaining as $bestmove){
$sql .=' AND ';
$sql .= '`';
$sql .= $col;
$sql .= '`=';
$sql .= $bestmove;
$sql .= ' ';
$results = mysqli_query($con,$sql);
$results = $results->num_rows;
if ($con->error){
echo $con->error ."\n";
echo $sql .":";
echo $results ."\n \n";
}
if ($results >= $bestresult){
$bestresult = $results;
$bestplay = $bestmove;
};
$sql = $reset;
};
}else{
$sql = '
SELECT *
FROM xos
WHERE status=\'c\'';
if (count($moves) > 0){
$sql .=' AND ';
$sql .= $moves ;
};
$results = mysqli_query($con,$sql); //fetch result
$results = $results->num_rows;
if ($results > $required){
if (count($moves) == 0){
$col = 1;
};
$reset = $sql;
foreach ($remaining as $bestmove){
$sql .=' AND ';
$sql .= '`';
$sql .= $col;
$sql .= '`=';
$sql .= $bestmove;
$sql .= ' ';
$results = mysqli_query($con,$sql);
$results = $results->num_rows;
if ($con->error){
echo $con->error ."\n";
echo $sql .":";
echo $results ."\n \n";
}
if ($results >= $bestresult){
$bestresult = $results;
$bestplay = $bestmove;
};
$sql = $reset;
};
}else{
$max = count($remaining) - 1;
$bestplay = rand(0,$max);
$bestplay= $remaining[$bestplay];
};
};echo $bestplay;
}else{
$sql = "INSERT INTO `xos`(`1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `Status`) VALUES (";
for ($i = 0; $i <= 8; $i++) {
$sql .= $moves[$i];
$sql .= ",";
};
$sql .= "";
$sql .= $moves[9];
$sql .= ")";
if ($con->query($sql) === false){
echo $con->error;
echo $sql;
};
};
At first glance, it looks like in
$(wins).each(function(){
var maybe = $.inArray(this,xs); //if Xs match combos win
...
}
you're checking if the array xs is found in the currently checked winning combination instead of just comparing this to xs (both 1-dimensional arrays). [Tried $.inArray(wins, xs) but it won't work.]
Could this be it?
UPDATE: this version works: http://jsfiddle.net/QH6W9/9/
I fixed your code to retrieve the ids of the X'ed fields with this:
var xs = $(".x").map(function(i, el) {
return parseInt($(el).attr('id'))
}).get(); // get ids as array
And also the detection of the win situation:
$(wins).each(function() {
var found = true;
for(var i =0; i<this.length; i++) {
found &= ($.inArray(this[i], xs) > -1);
}
if (!found) return;
alert("You Won Bruh");
var all = $(".square");
$(all).addclass('clicked'); //stops more turns
return;
});
You have a couple of issues.
First, you are putting all of the locations of .x into an array, and then seeing if that array is in the wins array.
Unfortunately, $.inArray() will only return an index if the items are the same item, not if they have matching values.
$.inArray([4,5,6], [[1,2,3], [4,5,6]]) // returns -1
var ary1 = [1,2,3];
var ary2 = [4,5,6];
$.inArray(ary2, [ary1, ary2]); // returns 1
$.inArray(ary2, [ary1, [4,5,6]]); // returns -1
Secondly, if you are at a state in the game where you have more than 3 X's, you will never match a winning position:
X O _
X X O
X O _
In this case xs will equal [1,4,5,7]. This is a winning position, but will not match any of your arrays.
There are a number of other ways to go about this. The easiest, given your wins array, is to iterate through each and check if the div at each location in the array is an X. If so, stop and declare a win.
Demo: http://jsfiddle.net/jtbowden/4BDwt/1/
Note, I cleaned up some other code in this example.
Removed the redundant clickable class, and use
.square:not(.clicked).
Replaced .click() with .on().
Removed the .square IDs and just use the div order in XOs as the location, using .eq() with the array position. IDs shouldn't start with numbers, and it is better to store data in a jQuery data attribute, like <div data-location="1">, and retrieve it with .data('location'). But, in this case, it wasn't needed as the div order tells us where it is.
Replaced $(array).each(function(){}) with $.each(array, function(){}). This is the correct way to iterate over a normal array that is not jQuery objects.
You had two problems in your program:
First, you had the following:
parseInt(number);
xs[i] = number;
xs[i] was still getting a string because parseInt() does not modify its parameter. Instead, it returns the numeric value. So I changed that code to the more compact:
xs[i] = parseInt(number);
Secondly, in your $(wins).each() loop, you were using $.inArray(), but you already have the individual array, so you really wanted to do an array subset comparison there. Since Javascript/jQuery has no built-in array subset function, I just compared each element in the array:
$(wins).each(function(){
console.log( 'template: ' + this );
var allIn = true;
for( var i=0; i<this.length; i++ ) {
console.log( this[i] );
if( $.inArray( this[i], xs ) == -1 ) allIn = false;
}
if ( allIn ){
alert("You Won Bruh");
And now it works. I only did it for X's, not for O's...I'll leave that up to you! You can see my jsfiddle solution here:
http://jsfiddle.net/HxGZE/2/
EDIT: my solution now works. See the jsfiddle for proof.

array from php to js with ajax

i have this code on the server side:
<?php
header('Content-Type: text/html; charset=utf-8');
require "../general.variables.php";
require "../functions_validation.php";
require "../functions_general.php";
require "../../db_con.php";
$keyword = mysql_real_escape_string($_POST["keyword"]);
$query = mysql_query("
SELECT user_id, user_fullname, user_area, user_city, user_quarter, user_tmb
FROM `migo_users`
WHERE (
user_fullname LIKE '%".$keyword."%' AND user_id NOT IN (".$superAdmins2string.")
)
ORDER BY tmb_set DESC, user_fname ASC
LIMIT 7;
");
$i = 0;
while ($userInfo = mysql_fetch_array($query)) {
$area_name = mysql_fetch_array(mysql_query("
SELECT area_name
FROM `migo_areas`
WHERE
area_id='".$userInfo['user_area']."';
"));
$city_name = mysql_fetch_array(mysql_query("
SELECT city_name
FROM `migo_cities`
WHERE
city_id='".$userInfo['user_city']."';
"));
if ($userInfo['user_quarter'] != 0) {
$quarter_name = mysql_fetch_array(mysql_query("
SELECT quarter_name
FROM `migo_quarters`
WHERE
quarter_id='".$userInfo['user_quarter']."';
"));
}
else {
$quarter_name['quarter_name'] = "";
}
$rsl[$i]['user_id'] = $userInfo['user_id'];
$rsl[$i]['user_fullname'] = $userInfo['user_fullname'];
$rsl[$i]['user_area_name'] = $area_name['area_name'];
$rsl[$i]['user_city_name'] = $city_name['city_name'];
$rsl[$i]['user_quarter_name'] = $quarter_name['quarter_name'];
$rsl[$i]['user_tmb'] = $userInfo['user_tmb'];
$i++;
}
echo json_encode($rsl);
mysql_close();
?>
and this code on the client side:
$.ajax({
type : 'POST',
url : 'php/general.ajax/header_search.php',
//async : false,
//cache : false,
dataType : 'json',
data: {
keyword : sb_keyword
},
success : function(data) {
var hs_hits = 0;
var hs_row_nr = 1;
var hs_results = "<div class='sb_spacing'></div><div id='sb_rows_cont'>";
if (data != null) {
$.each(data, function(index, arr) {
hs_hits++;
if (arr['user_quarter_name'] != "") {
var quarter_text = " - " + arr['user_quarter_name'];
}
else {
var quarter_text = "";
}
hs_results = hs_results + "<a class='search_links' href=profile.php?id=" + arr['user_id'] + "><div class='sbr_row' row_nr='" + hs_row_nr + "'><div class='sbr_imgFrame'><img src='images/user_48x48/" + arr['user_tmb'] + "' alt=''></div><div class='sbr_name'>" + arr['user_fullname'].replace(regexp_hs_user_fullname, '<span>$&</span>') + "</div><div class='sbr_area'>" + arr['user_area_name'] + "</div><div class='sbr_area'>" + arr['user_city_name'] + quarter_text + "</div></div></a>";
hs_row_nr++;
});
}
if (hs_hits > 0) {
hs_results = hs_results + "</div><div class='sb_spacing'></div><a class='search_links' href='search.php?name=" + sb_keyword + "'><div id='sbr_botttom'>Se flere resultater for <span class='gay'>" + sb_keyword + "</span></div></a>";
$("#sb_results").html(hs_results).show();
searchSet = 1;
total_rows = hs_hits;
$("#sb_rows_cont > a:first .sbr_row").addClass('sbr_row_act');
on_a = $("#sb_rows_cont > a:first");
first_a = on_a;
last_a = $("#sb_rows_cont > a:last");
sb_url = $(on_a).attr('href');
search_navigator_init();
}
else {
$("#sb_results").hide();
searchSet = 0;
}
},
error : function() {
alert("ajax error");
}
});
one problem tho, if the query gives 0 results, and the each function tries to run on the client side my js code stops working..
so i was wondering what i could do here.
how can i retrieve the amount of hits from the server side, before i run the each loop?
You're instantiating $rsl in the middle of a loop (implicitly), but you aren't entering the loop unless you have at least one entry.
Instantiate $rsl up above your while loop:
...
$i = 0;
$rsl = array();
while ($userInfo = mysql_fetch_array($query)) {
...
And now when you encode it, it is an empty array instead of null. This will also save your HTTP error_log, and generally be happier. : )
I would try json_encode() your PHP array to allow JavaScript to eval it as a native JS object.
echo json_encode($some_array);
Just a note, json_encode() is only available for PHP versions 5.2 and higher.
$.getJSON('ajax.php',{form data}, functon(data){
if(data == '') return;
});

Categories