select <tr> when checkbox is check ajax query - php

I have a bit of a complex query. I'm looking to remove other options when the checkbox is checked on the selected item when the AJAX query results are returned. The reason for this is because currently I have to enter the entire matching result so the result is narrowed down to one item. Otherwise the user would have to put a check on the item they selected and then scroll down about half the page to click the submit button to add the item they selected on a different table.
Here is my code so far;
trigger.js
// SKU search AJAX START //
$(document).ready(function() {
$(".tablesearch").hide();
// Search
function search() {
var query_value = $('input#barcode').val();
if(query_value !== ''){
$.ajax({
type: "POST",
url: "ajax/inventory.php",
data: { query: query_value },
cache: false,
success: function(html){
$("table#resultTable tbody").html(html);
}
});
}return false;
}
$("input#barcode").on("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$(".tablesearch").fadeOut(300);
}else{
$(".tablesearch").fadeIn(300);
$(this).data('timer', setTimeout(search, 100));
};
});
});
// SKU search AJAX END //
db-ajax.php
<?php
// Credentials
$dbhost = "localhost";
$dbname = "cms";
$dbuser = "root";
$dbpass = "pass";
// Connection
global $test_db;
$ajax_db = new mysqli();
$ajax_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$ajax_db->set_charset("utf8");
// Check Connection
if ($ajax_db->connect_errno) {
printf("Connect failed: %s\n", $ajax_db->connect_error);
exit();
}
?>
inventory.php
<?php
require_once "db-ajax.php";
// Output HTML formats
$html = "<tr>";
$html .= "<td>skuString</td>";
$html .= "<td>catString</td>";
$html .= "<td>descString</td>";
$html .= "<td>stockString</td>";
$html .= "<td>priceString</td>";
$html .= "<td><input class='checkBoxes' type='checkbox' name='checkBoxArray[]' value='skuIdString'></td>";
$html .= "</tr>";
// Get the Search
$search_string = preg_replace("/[^,-\/\sA-Za-z0-9_]/", " ", $_POST['query']);
$search_string = $ajax_db->real_escape_string($search_string);
// Check if length is more than 1 character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT s_id, sku_number, category, description, price, in_stock ';
$query .= 'FROM parts_stock AS a JOIN items AS b ON a.stock_id = b.s_id ';
$query .= 'WHERE sku_number LIKE "%'.$search_string.'%" OR category LIKE "%'.$search_string.'%"';
// Do the search
$result = $ajax_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check for results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Output strings and highlight the matches
$d_sku = preg_replace("/".$search_string."/i", "<b>".$search_string."</b>", $result['sku_number']);
$d_cat = $result['category'];
$d_desc = $result['description'];
$d_stock = $result['in_stock'];
$d_price = $result['price'];
$s_id = $result['s_id'];
// Replace the items into above HTML
$o = str_replace('skuString', $d_sku, $html);
$o = str_replace('catString', $d_cat, $o);
$o = str_replace('descString', $d_desc, $o);
$o = str_replace('stockString', $d_stock, $o);
$o = str_replace('priceString', $d_price, $o);
$o = str_replace('skuIdString', $s_id, $o);
// Output it
echo($o);
}
}else{
// Replace for no results
$o = str_replace('skuString', '<span class="label label-danger">No SKUs Found</span>', $html);
$o = str_replace('catString', '', $o);
$o = str_replace('descString', '', $o);
$o = str_replace('stockString', '', $o);
$o = str_replace('priceString', '', $o);
$o = str_replace('skuIdString', '', $o);
// Output
echo($o);
}
}
?>

Related

PHP/Jquery auto check data then do insert

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

Get and store id from database to different table based on user search input

I have multiple dynamic textboxes where users input license plate no. I'm trying to retrieve the id corresponding to the license plate # inputted by the user from the database but I'm unable to get it. I want to store the license plate #'s id that's already in the database to a different table and not the license plate no itself, but It always returns null.
Thanks in advance.
search.js
function firetruckAddingTextBoxes() {
var NumOfText = $("#NumOfTextBoxes2").val();
$('.NewlyCreatedSelectBoxes2').empty();
var txtBox = "";
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="firetruck[]" class="search" placeholder="License Plate No" required/><br>';
}
$('.NewlyCreatedSelectBoxes2').append(txtBox);
$(".NewlyCreatedSelectBoxes2").on("keyup", ".search", function () {
var search_term = $(this).val();
$('#search_results2').html('Searching database...');
if (search_term !== '') {
$.post('php/firetruck_search.php', { search_term: search_term }, function (data) {
$('#search_results2').html(data);
});
} else {
$('#search_results2').html('Not Found');
}
});
return false;
}
search.php
<?php
require('connectdb.php');
if(isset($_POST['search_term']))
{
$search_term = mysql_real_escape_string(htmlentities($_POST['search_term']));
if(!empty($search_term))
{
$search = mysql_query("SELECT `fireTruckID`, `licensePlateNo` FROM `firetruckinfo` WHERE `licensePlateNo` LIKE '%$search_term%'");
$result_count = mysql_num_rows($search);
$suffix = ($result_count != 1) ? 's' : '';
echo '<p>Your search for ', $search_term, ' returned ', $result_count, ' result', $suffix, '</p>';
while($results_row = mysql_fetch_assoc($search))
{
echo '<p>', $results_row['licensePlateNo'], '</p>';
}
}
}
?>
occurrence.php
$firetrucks = $_POST['firetruck'];
foreach($firetrucks as $firetruck):
$vehicleID = mysql_query("SELECT `fireTruckID` FROM `firetruckinfo` WHERE `licensePlateNo`='$firetruck'");
$row2 = mysql_fetch_assoc($vehicleID);
$query3 = "INSERT INTO `truckonscene`(`FireTruckInfo_fireTruckID`, `IncidenceOfFire_incidentID`)
VALUES(
'".mysql_real_escape_string($row2['fireTruckID'])."',
'".mysql_real_escape_string($incidentid)."')";
mysql_query($query3) or die(mysql_error());
endforeach;

Div onClick With JSON Call Doesn't Work

I have a search function that calls a php file onkeyup. Now in JQuery i have a onClick function that when you click a div from that same JSON call it alerts something, maybe it will be easier to understand from my code below:
<?php
$Connect = new mysqli("localhost", "root", "", "Data");
$Val = $_POST['Val'];
if($Val)
{
$Search = 'SELECT * FROM Users WHERE ';
$Term = explode(" ", $Val);
foreach($Term as $Key)
{
$I = 0;
$I++;
if($I == 1)
{
$Search .= 'Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
else
{
$Search .= 'OR Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
}
if($Result = $Connect->query($Search))
{
while($Row = $Result->fetch_assoc())
{
$User = $Row['Username'];
$USearch['S'][] = '<div class="Result"><label class="TText" style="cursor:pointer;">' . $User . '</label></div>';
}
}
}
echo json_encode($USearch);
?>
Now, as you can see, once the user types into a box a div shows up showing all LIKE records of Users, once the div is clicked on nothing happens.
$('.Result').click(function()
{
alert('Hi');
});
When the ajax call return a state of success you can use for example the jquery bind method. (see here for more info http://api.jquery.com/bind/ )
function myAjaxFunct(val){
$.ajax(
{
type: "POST",
url: myPhpFile.php,
datatype: "jsonp",
data: {val: val},
success: function (result) {
$("#jsonResultDisplay").text(result);
$('.Result').bind('click', function() {
alert('hi');
});
}
});
}
You are dynamically creating element that is why it doesn't work.
Use on()method.
Check an example:
http://jsfiddle.net/pZQ8T/

mysql php js live search

I'm currently doing a live search form based on Jquery/ajax/php, but it dosent seems to work.
Can you guys se a problem in my code? :)
function getStates(value) {
$.post("search.php",{ partialState: value }, function(data) {
$("#results").html(data);
});
}
<input type="text" onkeyup="getStates(this.value)" />
<div id="results"></div>
Search.php:
$partialStates = $_POST['partialState'];
$states = mysql_query("SELECT institution_name FROM sb_institutions WHERE institution_name LIKE '%$partialStates%'");
while($stateArray = mysql_fetch_array($states)) {
echo "<div>" . $state['institution_name'] . "</div>";
}
Thanks! :)
Your Code looks ok.
The best way to troubleshoot ajax is to use Firefox with Firebug extension.
That way you can see :
if the function is being fired
if the $_POST values are good : url + parameters
what the server sends as a response
if you have errors in your js
All this will be in the console tab of firebug.
after installing firebug right click on the page and choose debug with firebug.
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
})
;
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}
Please also see this http://crewow.com/AutoSuggest_Search_Tutorial.php
Live Search Tutorial is a PHP Ajax Based Tutorial which containts following pages and Folders.

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