PHP/Jquery auto check data then do insert - php

For example, I have the following data
Name Date
Aplha 10/05/1988
Bravo 10/04/1999
Charlie 10/08/1990
I'm trying to make a auto check data (database) for every minute,
and compare it with the current Date on the computer, if its the same, I can insert message like happy birthday.
Someone can provide reference or solution to this, would be appreciated.
its like notification but in this case it will send message automatic
edited note - nvm i got it..updated script
my js
$(function()
{
setInterval(function() {
$.ajax({
url: "dooBday.php",
success: function (data) {
$("#feedback").html(data);
}
});
}, 1000 * 60);
});
my dooBday function
$tgl=date("d/m");
$tglInt=date("d/m");
$tglInt=preg_replace( '~\D~', '', $tglInt);
$tglInt=intval($tglInt);
// Database Object
$tablename = "Phonebook_New";
$tablename2 = "USER_ID";
$xo=0;
$xx=0;
$VinDB = new VinDB();
// Get Data
$query2 = "SELECT * FROM ".$tablename2." WHERE UserID='".getMultiUserID()."'";
$result2 = $VinDB->query($query2);
if ($VinDB->num_rows($result2) != 0)
{
$line2 = $VinDB->fetch_array($result2);
if($line2["bdaySts"]==1 and strlen(trim($line2["bdayMsg"])) > 0){
// Get Data--------------------------------
$query = "SELECT * FROM ".$tablename." WHERE User_ID='".getMultiUserID()."' AND bdaySent='x'";
$result = $VinDB->query($query);
if ($VinDB->num_rows($result) != 0)
{
while ($line = $VinDB->fetch_array($result))
{
if(!empty($line["Ultah"])){
$tglNew=substr($line["Ultah"], 0, -5);
if($tgl==$tglNew){
$datex = date('Y/m/d');
$timex = date('H:i:s');
$schedule= date($datex . '-' . $timex);
//doo Update Contact Sent--------------------
$sqlquery[$xo]="UPDATE ".$tablename." SET bdaySent='Sent' where User_ID='".getMultiUserID()."' and nomor='".$line["nomor"]."'";
$xo++;
// doo Send Message----------------------------
$inuquery[$xx] = "INSERT INTO Schedule ";
$inuquery[$xx] .= "(message,phone_number,Schedule,Status,User_ID) ";
$inuquery[$xx] .= "VALUES ('".$line2['bdayMsg']."','".$line['PhoneNumber']."','".$schedule."','Processing','";
if (isset($_SESSION['user_id2']))
{
$inuquery[$xx] .= $_SESSION['user_id2']."')";
} else {
$inuquery[$xx] .= "Unknown')";
}
$xx++;
}}
}//end while
}// end if
}
}//end send bday
for($i=0;$i<$xo;$i++){
$result = $VinDB->query($sqlquery[$i]);
$result2 = $VinDB->query($inuquery[$i]);
}

I think you want to wish users. If I am right. You can do it like this.
put this code on your page where you would like to check every minute
setInterval(function() {
$.ajax({
url: "ajx.php",
success: function (data) {
$("#feedback").html(data);
}
});
}, 1000 * 60);
And this will be your ajax.php file
<?php
// Name Date
// Aplha 10/05/1988
// Bravo 10/04/1999
// Charlie 10/08/1990
$alphaDob = '02/04/1988';
$exp = explode('/', $alphaDob);
$userDate = $exp[0];
$userMonth = $exp[1];
$currentDate = date('Y-m-d');
$exp = explode('-', $currentDate);
$currentDate = $exp[2];
$currentMonth = $exp[1];
if($currentMonth == $userMonth && $currentDate == $userDate) {
echo 'Happy Birthday';
}
For good performance use Ajax-Long-Polling function, example can be found here Long-Polling Example

Related

Select the last inserted row Every 1 second

I have 2 files:
1. chat.php: contain chat messages.
2. loadSingle.php: grab last new message every 1 second.
When I get the last message it was always return and get the last one. I want to get the last message without duplicate every time.
chat.php:
function loadlastmsg(){
var fromIdl = "<?php echo $chat_from_id;?>";
$.ajax({
type:'POST',
url:'loadSingle.php',
data:{fromIdl: fromIdl,},
cache: false,
beforeSend:function(data){
},
success: function(data)
{
$('#mainmsgs').append(data);
}
});
}
setInterval(function(){
loadlastmsg();
}, 1000);
</script>
Load Last Message
loadSingle.php:
<?php
if(isset($_POST["fromIdl"], $_POST["fromIdl"]))
{
$chat_from_ids = $_POST["fromIdl"];
require_once 'config/config.php';
mysqli_set_charset($conn,"utf8mb4");
$chinbox = array();
$result=$conn->query("SELECT * FROM chat WHERE id = (SELECT MAX(id) FROM chat WHERE to_id=$userId AND from_id=$chat_from_ids OR to_id=$chat_from_ids AND from_id=$userId) ORDER BY chat.send_date DESC LIMIT 1");
while ($chinbxsx = mysqli_fetch_assoc($result)) {
$chinbox[] = $chinbxsx;
$from_id = $chinbxsx['from_id'];
$subject = $chinbxsx['subject'];
$message = $chinbxsx['message'];
$get_date = $chinbxsx['send_date'];
$senddate = date_create($chinbxsx['send_date']);
$senddate = date_format($senddate, 'Y/m/d H:i:s');
$from_name = $chinbxsx['from_name'];
if($from_id != $userId){
$from_image = $chinbxsx['from_image'];
$msgclass = 'msgmRec';
}else{
$from_image = $userImage;
$msgclass = 'msgmSend';
}
// if($get_date > $get_date){
echo "<div class='msgm $msgclass'><img class='cmavsm' id='cmavsm' style='background-image: url($from_image);' /><p class='smRec'>$message</p><span class='date_span'>$senddate</span></div>";
// }
}
$conn->close();
}
?>
The mistake is: get the last message every 1 second. every time without stop it. I want to get the last message one time without loop the last message. thanks.
Using Ajax for chat will have poor performance always. You must consider using Web sockets.
See the below link for a sample
https://phppot.com/php/simple-php-chat-using-websocket/
I can't warranty this will be a fixed code, but it will give you the idea of how to discard a message on the client side if already received:
CLIENT SIDE:
<script>
/* Other code ... */
// Global variable for save the latest message ID.
var _latestMessageID = -1;
$(document).ready(function()
{
// Start getting messages...
setInterval(
function() {loadlastmsg();},
1000
);
});
function loadlastmsg()
{
var fromIdl = "<?php echo $chat_from_id;?>";
var formData = {fromIdl: fromIdl};
$.ajax({
type:'POST',
url:'loadSingle.php',
data: $.param(formData),
cache: false,
success: function(data)
{
if (data && data["ID"] > _latestMessageID)
{
$('#mainmsgs').append(data["message"]);
_latestMessageID = data["ID"];
}
}
});
}
</script>
SERVER SIDE:
<?php
require_once 'config/config.php';
if(isset($_POST["fromIdl"]) && $_POST["fromIdl"])
{
$chat_from_ids = $_POST["fromIdl"];
mysqli_set_charset($conn,"utf8mb4");
$chinbox = array();
$result=$conn->query(
"SELECT *
FROM chat
WHERE id = (SELECT MAX(id)
FROM chat
WHERE (to_id=$userId AND from_id=$chat_from_ids)
OR (to_id=$chat_from_ids AND from_id=$userId))
ORDER BY chat.send_date DESC LIMIT 1"
);
// Since the query has LIMIT of 1 this should only loop one time.
while ($chinbxsx = mysqli_fetch_assoc($result))
{
$chinbox[] = $chinbxsx;
$from_id = $chinbxsx['from_id'];
$subject = $chinbxsx['subject'];
$message = $chinbxsx['message'];
$get_date = $chinbxsx['send_date'];
$senddate = date_create($chinbxsx['send_date']);
$senddate = date_format($senddate, 'Y/m/d H:i:s');
$from_name = $chinbxsx['from_name'];
if ($from_id != $userId)
{
$from_image = $chinbxsx['from_image'];
$msgclass = 'msgmRec';
}
else
{
$from_image = $userImage;
$msgclass = 'msgmSend';
}
$msgID = $chinbxsx['id'];
}
$returnArray = array();
$returnArray["ID"] = $msgID;
$returnArray["message"] = "<div class='msgm $msgclass'><img class='cmavsm' id='cmavsm' style='background-image: url($from_image);' /><p class='smRec'>$message</p><span class='date_span'>$senddate</span></div>";
echo json_encode($result);
$conn->close();
}
?>

Organize data based on timestamp with AJAX autoload

Im using this answer right here: https://stackoverflow.com/a/30513954/4892914
And it works well on SELECT * FROM MOCK_DATA ORDER BY date DESC. But i would like to add the function to "autoload" the content. But I'm having a hard time to implement this.
I actually tried following this tutorial: http://www.smarttutorials.net/infinite-scroll-using-jquery-ajax-php-and-mysql/
Im trying to fetch the data in json format, from my controller:
public function ajaxtest(){
$this->View->renderJSON(array(
'mockup' => UserModel::ajax(Request::post('start'), Request::post('limit'))
));
The Request::post('start') and Request::post('limit') is just added plain HTML in the index.php
<form>
<input type="hidden" id="first" value="0">
<input type="hidden" id="limit" value="4">
</form>
And the Model query looks like this:
public static function ajax($start = 0, $limit = 4){
$database = DatabaseFactory::getFactory()->getConnection();
$sql = 'SELECT * FROM MOCK_DATA ORDER BY date DESC LIMIT :start, :limit';
$query = $database->prepare($sql);
$query->bindValue(':start', intval($start), PDO::PARAM_INT);
$query->bindValue(':limit', intval($limit), PDO::PARAM_INT);
$query->execute();
if($query->rowCount() < 0){
return false;
}
return json_encode($query->fetchAll());
}
I i have tried returning the query with json_encode but still getting error No more data to show.
$decoded = json_decode($this->mockup);
//CREATE AN ARRAY OF THE REPLACEMENTS YOU WANT
$aArray = array();
$aArray[date('Y-m-d')] = 'Today - Idag';
$aArray[date('Y-m-d', mktime(0, 0, 0, date('n'), date('j') - 1, date('Y')))] = 'Yesterday - Igår';
$aArray[date('Y-m-d', mktime(0, 0, 0, date('n'), date('j') - 2, date('Y')))] = 'Day before Yesterday - Förrgår';
$aArray['2013-12-25'] = 'Christmas 2013';
//INITIALIZE SOME VARIABLES
$cLastHeader = '';
$cCurrHeader = '';
//THIS WOULD BE YOUR QUERY RESULTS LOOP
//foreach ($rows AS $nNull => $cDate) {
foreach ($decoded AS $key => $value) {
$cLookup = substr($value->date, 0, 10); //TRIM OUT THE TIME FROM CURRENT RECORD
//IS DATE IN ARRAY? IF NOT, FORMAT
if (isset($aArray[$cLookup])) {
$cCurrHeader = $aArray[$cLookup];
} else {
$cCurrHeader = $cLookup; //WOULD SHOW 'YYYY-MM-DD'
$cCurrHeader = date('F Y', strtotime($cLookup)); //WOULD SHOW 'MONTH YYYY'
}
//HAS HEADER CHANGED? IF SO PRINT
if ($cCurrHeader != $cLastHeader) {
$cLastHeader = $cCurrHeader;
print($cCurrHeader . "\n");
}
//PRINT RECORD
// print("\t" . $cDate . "<br>");
echo '<h4>'. $value->date . ' <small>'.$value->email.'</small></h4>';
echo '<div class="content">'.$value->text .'</div><br>';
}
Here is the AJAX code
flag = true;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()){
first = $('#first').val();
limit = $('#limit').val();
no_data = true;
if(flag && no_data){
flag = false;
$('#loader').show();
$.ajax({
url : 'http://localhost:8888/dashboard/ajaxtest',
dataType: "json",
method: 'post',
data: {
start : first,
limit : limit
},
success: function( data ) {
flag = true;
$('#loader').hide();
if(data.count > 0 ){
first = parseInt($('#first').val());
limit = parseInt($('#limit').val());
$('#first').val( first+limit );
$('#timeline-conatiner').append('<h4>'+date+' <small>'+email+'</small></h4>');
$.each(data.content, function(key, value ){
html = '<div class="content">';
html += '<p>'+value.text+'</p>';
html += '</div>';
$('#timeline-conatiner').append( html );
});
year--;
}else{
// alert('No more data to show');
no_data = false;
$('#timeline-conatiner').append('No more data to show');
}
},
error: function( data ){
flag = true;
$('#loader').hide();
no_data = false;
// alert('Something went wrong, Please contact admin');
$('#timeline-conatiner').append('Something went wrong, Please contact admin');
}
});
}
}
});
How can i troubleshoot this?

How should I execute my php code using AJAX?

I've written the conditions down in JavaScript and if it's a down arrow then I want to update the database whereas currently it's not falling into the javascript condition and updating the database at server level. Any help will be appreciated.
Code:
<script language="javascript">
$(document).ready(function() {
totalgames=<?= $totalgames ?>;
//scoress = 0;
previous_s=0;
for(xx=totalgames; xx>=1; xx--){
score_ele = 'scores'+xx;
tdid_ele = 'tdid'+xx;
var tdd = document.getElementById(tdid_ele);
var scoress = document.getElementById(score_ele);
if(previous_s == 0){
tdd.innerHTML = "<img src='images/bullet.png'/>";
}else{
if(parseFloat(previous_s) > parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/arrow_up.png'/>";
}else if(parseFloat(previous_s) < parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/arrow_down.png'/>";
<?php
//Selecting from table teams
$sql_sel_amnt = "Select * from teams where t_name='".$t_name."'";
$result_sel = $db1->getResult($sql_sel_amnt);
$row_sel = mysql_fetch_assoc($result_sel);
//Selecting from table profitnloss
$sql_pnl = "Select * from profitnloss where t_name='".$t_name."' and username='".$abc."'";
$result_pnl = $db1->getResult($sql_pnl);
$row_pnl = mysql_fetch_assoc($result_pnl);
$transact_money = $row_pnl['pnl_amount'];
$pnl_results = $row_pnl['pnl'];
$profit = 0;
$loss = 0;
$transact_money = explode("|", $transact_money);
$pnl_results = explode("|", $pnl_results);
for($i=0; $i<count($transact_money); $i++){
if($pnl_results[$i]=='P'){
$profit = $profit + $transact_money[$i];
}else{
$loss = $loss + $transact_money[$i];
}//end if
}//end for..
$money_results_total = $profit - $loss;
$pnl_date = date("d-m-Y H:i:s");
$pnl_amount = $row_sel['c_amount'];//total amount lost
$t_amount = $money_results_total + $row_pnl['t_amount'] + $pnl_amount;
$noofplayers = mysql_num_rows($result_sel)-1;//total no of players
$company_share = 17;//charity percentage
$company_share_amnt = $company_share*$pnl_amount/100;
$pnl_amount_remaining = $pnl_amount - $company_share_amnt;
$charity = substr($row_sel['charity'], 0, 2);//charity percentage
$charity_amount = $charity*$pnl_amount_remaining/100;
$sharing_amount = $pnl_amount-$charity_amount-$company_share_amnt;
$pnl_profit = round($sharing_amount/$noofplayers, 2);
echo "noofplayers=> ".$noofplayers.", company_share=> ".$company_share.", company_share_amnt=> ".$company_share_amnt.", charity=> ".$charity."%, charity_amount=> ".$charity_amount.", sharing_amount=> ".$sharing_amount.", pnl_profit=> ".$pnl_profit;
$sql_updt_loss = "UPDATE profitnloss SET game_date = '".$serial_date."', pnl_date = CONCAT(pnl_date, '$pnl_date|'), pnl_amount = CONCAT(pnl_amount, '$pnl_amount|'), pnl = CONCAT(pnl, 'Loss|'), t_amount='".$t_amount."' where username='".$abc."' and t_name='".$t_name."'";
//echo $updt_pnl;
//$result_loss = $db1->getResult($sql_updt_loss);
$sql_updt_profit = "UPDATE profitnloss SET pnl_date = CONCAT(pnl_date, '$pnl_date|'), pnl_amount = CONCAT(pnl_amount, '$pnl_profit|'), pnl = CONCAT(pnl, 'Profit|') where username not like'".$abc."' and t_name='".$t_name."'";
//echo $updt_pnl;
//$result_profit = $db1->getResult($sql_updt_profit);
?>
}else if(parseFloat(previous_s) == parseFloat(scoress.value)){
tdd.innerHTML = "<img src='images/bullet.png'/>";
}//end if
}//end if 0..
previous_s = document.getElementById(score_ele).value;
}//end for
})//emd document ready..
</script>
The way you should execute you PHP-code using ajax is by moving the server side code to a separate file which you call apon in the ajax-request, the url.
One example is using jQuery.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
This documentation is located here
You send the information needed to execute the PHP-code in the data. These are then accessed by $_POST or $_GET depending on which type you chose.
If you're not intending to use jQuery, you can look here: Getting Started with AJAX - Updating Form via PHP.
Here are some good practices using ajax

Returning a complex series of commands via ajax (or perhaps restructuring it once returned through ajax)

I currently have a function that looks like this:
function getEvents($weekNumStart, $weekNumEnd){
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (!$mysqli) {
die('There was a problem connecting to the database.');
}
else {
if ($weekNumEnd == '') {
$weekNumEnd = $weekNumStart;
}
$Group = $_SESSION['Group'];
$query = $mysqli->prepare("SELECT EventID, DAYOFWEEK(Start) AS wday, Events.Start, HOUR(Start) AS sHour, HOUR(End) AS eHour, Events.End, Events.Group, Events.Unit, Type, Room, Lecturer, Cancelled, StartName FROM Events, Week WHERE StartName >= '$weekNumStart' AND StartName <= '$weekNumEnd' AND Events.Start >= StartWeek AND Events.Start <=EndWeek AND (Events.Group = '$Group' OR Events.Group = '');");
$query->execute();
$query->bind_result($eventID, $dayofweek, $startDateTime, $startHour, $endHour, $endDateTime, $group, $unit, $type, $room, $lecturer, $cancelled, $weekName);
$data_arr = array();
while ($query->fetch()){
$data_arr[] = array(
$eventID, $dayofweek, $startDateTime, $startHour, $endHour, $endDateTime, $group, $unit, $type, $room, $lecturer, $cancelled, $weekName
);
}
return $data_arr; //
}
$mysqli->close();
}
This function works how I want it to. I currently manipulate it like this:
if (!isset($weekNumEnd)){
$weekNumEnd = '';
}
$data = getEvents($weekNumStart, $weekNumEnd);
foreach($data as $day) {
for($i=0;$i<7;$i++){
for($j=9;$j<=18;$j++){
if ($day[1] == $i && $day[3] == $j){
$unit = $day[7];
$type = $day[8];
$room = $day[9];
if ($i == 2){
?>
<script>
var mon<?=$j?>unit = '<?=$unit?>';
var mon<?=$j?>type = '<?=$type?>';
var mon<?=$j?>room = '<?=$room?>';
$('#mon-<?=$j?>').append(
"<p>"+mon<?=$j?>unit+"<br>"+mon<?=$j?>type+"<br>"+mon<?=$j?>room+"</p>"
);
</script>
<?php
if (($day[4] - $day[3]) > 1) {
for($q=($day[3]+1);$q<$day[4];$q++){
?>
<script>
var mon<?=$q?>unit = '<?=$unit?>';
var mon<?=$q?>type = '<?=$type?>';
var mon<?=$q?>room = '<?=$room?>';
$('#mon-<?=$q?>').append(
"<p>"+mon<?=$q?>unit+"<br>"+mon<?=$q?>type+"<br>"+mon<?=$q?>room+"</p>"
);
</script>
<?php
}
}
}
The problem is. I obviously cannot run it in real time to constantly update the events list whenever the week or whatever is changed.
So to fix it, I decided to try using Ajax. So far I have this:
function getEvents() {
var data = 'Events=Yes';
$.ajax({
type: "POST",
url: "functions/updateWeek.php",
data: data,
cache: false,
dataType: 'json',
success: function(html) {
alert(html.returned_val);
}
});
}
And I have this to return:
if($_POST['Events'] == "Yes"){
$weekNumStart = $_SESSION['startWeek'];
$weekNumEnd = $_SESSION['endWeek'];
$data = getEvents($weekNumStart, $weekNumEnd);
echo json_encode(array('returned_val' => $data));
}
And this...sort of works. at least that is to say it returns the data in one ugly great chunk.
The thing is I can no longer manipulate it as I did before as above:
data = getEvents($weekNumStart, $weekNumEnd);
foreach($data as $day) {
for($i=0;$i<7;$i++){
for($j=9;$j<=18;$j++){
if ($day[1] == $i && $day[3] == $j){
$unit = $day[7];
$type = $day[8];
$room = $day[9];
if ($i == 2){
?>
<script>
var mon<?=$j?>unit = '<?=$unit?>';
var mon<?=$j?>type = '<?=$type?>';
var mon<?=$j?>room = '<?=$room?>';
$('#mon-<?=$j?>').append(
"<p>"+mon<?=$j?>unit+"<br>"+mon<?=$j?>type+"<br>"+mon<?=$j?>room+"</p>"
);
</script>
That is to say - I don't know how to re-manipulate it when I've called the information back through ajax. Would I rewrite all of the above in an entirely javascript fashion? Is there a more logical way of doing this that I do not know/understand? Or is there a way I can just make that code work (complete with php and javascript) in that different window, and have it send it all back, correct through ajax, to automatically work on the page without having to rewrite it once the info is pulled back through ajax?
First of all, it's enough to use json_encode($data) and you'll get the array from AJAX.
Second, check it with Firebug, as you should get structured data, not big chunk.
alert() just tries to print everything as single string, that's all
for( var i = 0; i < html.length; i++ )
// do something with html[i]

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.

Categories