Element.text is not a function - php

I know this has been asked plenty of times before and I already went through a bunch of posts as well as googled for the answer but I just can't figure it out... here's my php
$connect = mysql_connect("localhost", $usuario, $password) or die(mysql_error());
$select_db = mysql_select_db($dbname) or die(mysql_error());
//query the database
$query = mysql_query("SELECT css_id, body FROM content");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$body[$x] = array("cssID" => $row["css_id"], "inlineContent" => $row["body"]);
}
//echo JSON to page
$response = $_GET["jsoncallback"] . "(" . json_encode($body) . ")";
echo $response;
my HTML:
<body>
<h2 class="inlineEdit" id="titulo">Editando</h2>
<div id="response"></div>
<ul>
<li class="inlineEdit" id="linea">Lorem Ipsum....</li>
</ul>
</body>
and finally my jQuery:
$(function () {
var domID = [];
$(".inlineEdit").each(function(){
domID.push(this.id);
});
$.getJSON("assets/php/load.php?jsoncallback=?", checkArray);
function checkArray(data){
for (var x = 0; x < data.length; x++){//loop through all items in the JSON array
for(var j = 0; j < domID.length; j++){//loop through the DOM id's array
if(domID[j] === data[x].cssID){
var Element = "$('#" + domID[j] + "')";
Element.text(data[x].inlineContent);
}
}
}
}
});
I've checked this using firebug and I know for sure that Element equals $('#linea') and data[x].inlineContent contains the correct data but I keep getting the same:
Element.text is not a function
message...

Should be:
var Element = $("#" + domID[j]);
else Element is a string.

var Element = "$('#" + domID[j] + "')";
assigns a string to variable Element which don't have a text function. Also a syntax error. Thanks #o.k.w for pointing this out.
var Element = $('#' + domID[j] );
assigns jQuery object to variable Element

Related

PHP Google Charts causes for loop to loop weirdly

I am facing an issue where the for loop loops properly to display a table in php when Google Charts is not used and when Google Charts is implemented on the page, the table only loops twice. I know this because I've echoed the count($arr) and echo the word LOOPED. My count shows 9 but it will only loop twice.
The google chart I am using is the pie chart and when this pie chart becomes really huge, where there are many slices, this would occur. What's weird is the Google Chart isn't inside this for loop.
for ($i = 1; $i < count($arr); $i++){
print_r(count($arr));
echo "LOOPED";
$splitwords = explode("ON", ($arr[$i]));
<td>$splitwords[0]</td>
<td>$splitwords[1]</td>"; }
This is the function being called.
function retrievepieCharts(minnumber,hournumber,daynumber){
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawminuteChart);
google.charts.setOnLoadCallback(drawhourChart);
google.charts.setOnLoadCallback(drawdayChart);
function drawminuteChart() {
var data = google.visualization.arrayToDataTable([
['Timing', 'Times'],
<?php
for ($i = 0; $i < count($minuteArray); $i++) {
$firstArraywithin10mins = $minuteArray[$i];
$firstDATEtoRetrieve = $firstArraywithin10mins[0];
$firstTimingtoRetrieve1 = $firstArraywithin10mins[1];
$firstTimingtoRetrieve = $firstDATEtoRetrieve . " ". $firstTimingtoRetrieve1;
$totalCountwithin10mins = count($firstArraywithin10mins)-1;
echo "['$firstTimingtoRetrieve', $totalCountwithin10mins],";
}
echo" ]);";
?>
var mintitle = "Logon Fails > 5 within " + minnumber + " minute(s)";
var hourtitle = "Logon Fails > 5 within " + hournumber + " hour(s)";
var daytitle = "Logon Fails > 5 within " + daynumber + " day(s)";
var options = {backgroundColor: 'transparent',chartArea:
{left:0,top:90,width:"90%",height:"90%"}
,height: 450
,width: 450,
title: 'Logon Fails > 5 within '+ minnumber +' minutes (Likely to be automated brute force)'
};
var minutechart = new google.visualization.PieChart(document.getElementById('piechart'));
minutechart.draw(data, options);
function selectminuteHandler() {
var selectedItem = minutechart.getSelection()[0];
if (selectedItem) {
var topping = data.getValue(selectedItem.row, 0);
var date = new Date(topping).toLocaleDateString("en-US");
var options = { hour12: false };
var time = new Date(topping).toLocaleTimeString('en-US', options);
var rows = document.querySelectorAll('#csv_table tr');
$allRows = $('#csv_table tr');
$allData = $('#csv_table td');
row1 = $allRows.filter(function(){
return $.trim($(this).find('td').eq(1).text()) == date;
});
row2 = $allData.filter(function(){
return $.trim($(this).find('td').eq(1).text()) == time;
});
index = $allRows.index(row1);
var table = document.getElementById("csv_table");
row = table.rows[index];
for (var i = 0, row11; row11 = table.rows[i]; i++) {
for (var j = 0, col; col = row11.cells[j]; j++) {
row11.cells[j].style.backgroundColor = "";
}}
rows.forEach(row => row.classList.remove('active'))
for (var j = 0, col; col = row.cells[j]; j++) {
var timeintable = row.cells[j].innerHTML.slice(12,20);
var target = new Date("1970-01-01 " + time);
var target2 = new Date("1970-01-01 " + timeintable);
timedifferences = target - target2;
var minuteVal = timedifferences / 60000;
if (minuteVal< 0){
minuteVal = minuteVal * -1;
}
if (minuteVal < minnumber){
row.cells[j].style.backgroundColor = "yellow";
document.getElementById('msg_div').innerHTML = hourtitle;
rows[index].scrollIntoView({
behavior: 'smooth',
block: 'center'
});
}
else{
row.cells[j].style.backgroundColor = "";
}
}
}
}
google.visualization.events.addListener(minutechart, 'select', selectminuteHandler);
}
This is the part where the function is being called. The $minData and $hourData is retrieved when the user clicks on the submit button through a form.
if (isset($minData) and isset($hourData)){
echo "<script type='text/javascript'>retrievepieCharts('$minData', '$hourData', '$dayData');
</script>"
;
}
This is the form which takes in the $minData and $hourData. I've tried changing the $minData and $hourData values and every time I changed it, the table loops differently. I've also tried to remove the submit button to see if that was causing the issue but the result is the same without the submit.
<form id="differencesnumber" method="POST">
<label for="mindiff">Minutes Differences</label>&nbsp&nbsp
<input type="number" id="mindiff" name="mindiff" style="width:50px;" min="0"
oninput="validity.valid||(value='');"required>
<br>
<label for="hourdiff">Hours Differences</label>&nbsp&nbsp
<input type="number" id="hourdiff" name="hourdiff" style="width:50px;" min="0" oninput="validity.valid||(value='');"required>
<br>
<input type="submit" value="Get PieCharts">
</form>
The codes are over 1000 lines and if anyone needs the entire code, do inform me.
Anyone knows what is the bug? I've been trying to debug this for days but to no avail.

Get values of a php in AS3

I've managed to get a value from a sql table in my AS3 code, but I don't understand why I can't get a second value.
In my php file I've got :
// create SQL
$sql = "SELECT * FROM dt_base where username = '$username'";
// execute SQL query and get result
$sql_result = mysql_query($sql, $connection) or die ("Couldn't execute query.");
// get number of rows in $result.
$num = mysql_numrows($sql_result);
$phpConfirm = "";
$phpConfirmSecond = "";
$counter = 0;
while ($row = mysql_fetch_array($sql_result)) {
$up= $row["up"];
$down= $row["down"];
if ($counter == 0) {
$phpConfirm .= $up;
$phpConfirmSecond .= $down;
} else {
// Use a item limiter "|" to seperate the records
$phpConfirm .= "|" . $up;
$phpConfirmSecond .= "|" . $down;
}
$counter++;
}
?>
And in my AS3 code :
function loadComplete(evt:Event):void {
//Display the value with variable name "totalItem"
total_txt.text = evt.target.data.totalItem
//Get the value (string) with variable name "phpConfirm"
var myResult:String = evt.target.data.phpConfirm;
trace(evt.target.data.phpConfirm);
var myResultSecond:String = evt.target.data.phpConfirmSecond;
trace(evt.target.data.phpConfirmSecond);
//Split the string into an Array
var myArray:Array = myResult.split("|");
var myArraySecond:Array = myResultSecond.split("|");
var finalString = "";
var finalStringSecond = "";
var i:int;
for (i = 0; i < myArray.length; i++) {
finalString = finalString + myArray[i] + "<br>";
finalStringSecond = finalStringSecond + myArraySecond[i] + "<br>";
}
output_txt.htmlText = finalString;
output_txtSecond.htmlText = finalStringSecond;
}
trace(evt.target.data.phpConfirm) results with the value of "up", so it's working.
But trace(evt.target.data.phpConfirmSecond) results with "undefined" instead of the value of "down".
Any idea why ?
EDIT
I've add that to my php file.
echo "phpConfirm=" . $phpConfirm . "&phpConfirmSecond=" . $phpConfirmSecond;
and I've change the line $username = "John"; in order to test it in the web browser.
The result is :
phpConfirm=6h20&phpConfirmSecond=14h32
So phpConfirmSecond has a value.
But my AS3 code produce an error when I had the PhpConfirmSecond in my php file.
Here's the error :
TypeError: Error #2007: Le paramètre text ne doit pas être nul.
at flash.text::TextField/set text()
at as3_php_mysql_01_fla::MainTimeline/loadComplete()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
If I erase every trace of PhpConfirmSecond of my php file, my AS3 code works and find the value PhpConfirm.
Found the problem. It was the line
//Display the value with variable name "totalItem"
total_txt.text = evt.target.data.totalItem
that was causing all the problem...
Thank you for your help.

.getJSON function, append to PHP url, return data from PHP file

I found many examples of this getting data from a mysql query. What I want to pass back to jQuery function is parsed html content in JSON format. What I want to do is separate PHP code from my initial load of the page. I'm doing this in jQuery Mobile. I know, my description is bad, it's hard to phrase.
I get article names and links from my database and output listview in index.html. When the user clicks on an article, I'm passing the link in the URL, getting it in jQuery and trying to call a PHP file which Parses that URL. Here's ALL the code:
index.html:
<body>
<div data-role="page" id="mainNews">
<div data-role="content">
<ul id="fnews" data-role="listview"></ul>
</div>
</div>
<script src="js/getmainnews.js"></script>
</body>
getmainnews.js:
var serviceURL = "http://localhost/basket/services/";
var news;
$('#mainNews').bind('pageinit', function(event) {
getNews();
});
function getNews() {
$.getJSON(serviceURL + 'getmainnews.php', function(data) {
$('#fnews li').remove();
mainnews = data.items;
$.each(mainnews, function(index, mnews) {
$('#fnews').append('<li data-icon="false"><a style="white-space:normal;" href="newstext.html?url=http://www.basket-planet.com' + mnews.link + '">' + mnews.article + '</a></li>');
});
$('#fnews').listview('refresh');
});
}
getmainnews.php:
<?php
include 'connect_to_mysql.php';
mysql_query("SET NAMES UTF8");
$sql = mysql_query("SELECT * FROM basket_news");
$mainnews = array();
while ($r = mysql_fetch_assoc($sql)){
$mainnews[] = $r;
}
echo '{"items":'. json_encode($mainnews).'}';
?>
Everything loads fine but the next page comes up empty. Here's the next 3 files...Sorry that this is such a long topic.
newstext.html:
<body>
<div data-role="page" id="newstext">
<div data-role="content">
<div id="textcontent"></div>
</div>
</div>
</body>
newstext.js:
var serviceURL = "http://localhost/basket/services/";
$('#newstext').bind('pageshow', function(event) {
var url = getUrlVars()["url"];
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText);
});
function displayNewsText(data){
var newstext = data.item;
$('#textcontent').append(newstext);
}
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
And finally getnewstext.php:
<?php
include_once ('simple_html_dom.php');
$url = $_GET['url'];
$html = file_get_html(''.$url.'');
$article = $html->find('div[class=newsItem]');
$a = str_get_html(implode("\n", (array)$article));
#$a->find('div[style*=float]', 0)->outertext = '';
#$a->find('h3', 0)->outertext = '';
#$a->find('div[id=comments]', 0)->outertext = '';
#$a->find('script', 0)->outertext = '';
#$a->find('a[href*=register]', 0)->outertext = '';
#$a->find('div', 4)->outertext = '';
#$a->find('div', 6)->outertext = '';
echo '{"item":'. json_encode($a) .'}';
?>
So those are the 6 files. On the newstext.html, the URL contains the URL which I need to pass to my PHP file. I'm sure the problem is in the last three files. What am I doing wrong here? Thanks in advance!
Update: Console error fixed, but still no output on the page.
Update2: From searching around, I saw somewhere that json_encode only accepts arrays. My $a in last PHP script is content from a page containing all kinds of html tags. How can I turn this into an array? To make one key/value with the value being all that html content?
The error getUrlVars is not defined newstext.js:3 says it all. You are calling a function that is not defined anywhere. I did a quick search and you probably want this:
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}

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.

Problem with $.getJSON in jquery

My Jquery code
function nalozi() {
var id_skupine = $('#skupina option:selected').val();
$('#artikel option').remove();
//$('#artikel').append('<option value="'+id_skupine+'">'+id_skupine+'</option>');
$.getJSON('artikli.php', {id_skupine:$('#skupina').val()}, function(data) {
$.each(data, function(index,item) {
$("#artikel").append("<option value=" + item.id + ">" + item.ime_artikla + "</option>");
});
});
}
$(document).ready(function() {
nalozi();
$('#skupina').change(function() {
nalozi();
});
});
AND PHP CODE
<?php
if(isset($_GET['id_skupine']))
{
$id_skupine = $_GET['id_skupine'];
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
$velikost = mysql_num_rows($poizvedba);
for ($i=0;$i<$velikost;$i++)
{
$elements[]=mysql_fetch_assoc($poizvedba);
}
}
echo json_encode($elements);
?>
I don't get the values back.
Update:
You should never put variable before sanitalizing/validating/type-converting into your sql queries. If your the value you expect in query string is a number, you need to properly type-cast it like this:
$id_skupine = (int) $_GET['id_skupine'];
And if it is a string, the least you can do is to use mysql_real_escape_string function:
$str = mysql_real_escape_string($_GET['str']);
Shouldn't you be grabbing the records from db like this:
if(isset($_GET['id_skupine']))
{
$id_skupine = $_GET['id_skupine'];
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
$velikost = mysql_num_rows($poizvedba);
while($row = mysql_fetch_assoc($poizvedba)){
$elements[] = $row['ime_artikla'];
}
}
echo json_encode($elements);
Might be your query is not returning anything
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
Remove single quote from '$id_skupine'
Try
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '".$id_skupine."'");

Categories