array from php to js with ajax - php

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;
});

Related

Jquery datatables functions not working

I would like to ask a question and I need a little help from you guys.
I would like to use jquery Datatable plugin in my project but something going wrong.
The table is displayed properly, but none of the datatable functions working.
Here is my code:
function get_answer(get_date, get_id) {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var date = get_date;
var id = get_id;
var data = {
'action': 'get_answers_ajax',
'date': date,
'id': id
};
var table_structure = '<table id="result-' + id + '" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#tabs-' + id).append(table_structure);
jQuery.post(ajaxurl, data, function (response) {
if (response) {
var obj = JSON.parse(response);
var heads = [];
var results = [];
jQuery.each(obj, function (key, res) {
if (jQuery.inArray(res.label, heads) == '-1')
{
heads.push(res.label);
}
results.push(res.value);
});
var head = jQuery('#tabs-' + id + ' .result_head tr');
head.empty();
jQuery.each(heads, function (key, value) {
head.append('<th>' + value + '</th>');
});
var body = jQuery('#tabs-' + id + ' .result_body');
body.empty();
if (results.length > 0) {
body.append('<tr role="row" class="odd">'); // Open tr
var count_heads = heads.length;
var count_answ = 0;
jQuery.each(results, function (key, value) {
if (value.substring(0, 4) == 'http') {
body.find('tr').last().append('<td><img src="' + value + '" alt="none" width="200px" height="200px" /></td>');
} else {
body.find('tr').last().append('<td>' + value + '</td>');
}
count_answ++;
if ((count_answ % count_heads) == 0) {
body.find('tr').last().find('td').last().after('</tr>');
body.find('tr').last().after('<tr role="row" class="even">');
}
});
body.find('tr').last().after('</tr>'); // Close tr
}
}
});
jQuery('#result-' + id).dataTable(
{
"ordering": true,
"searching": true
}
);
The heads and the reults array looks like this:
Heads => ["Eredmény", "Felhasználó", "Dátum"]
Results => ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"]
My PHP function which one gives back the data is this:
function get_answers() {
global $wpdb;
$date = $_POST['date'];
$form_id = $_POST['id'];
$date_pice = explode(' - ', $date);
$question = array();
$answer = array();
$sql_answers = "SELECT lead.date_created, detail.field_number, detail.value, detail.form_id, meta.display_meta FROM wp_rg_lead_detail AS detail INNER JOIN wp_rg_lead AS lead ON detail.lead_id = lead.id INNER JOIN wp_rg_form_meta AS meta ON detail.form_id = meta.form_id WHERE lead.date_created BETWEEN '{$date_pice[0]}' AND '{$date_pice[1]}' AND detail.form_id = '{$form_id}' ";
$answers = $wpdb->get_results($sql_answers);
foreach ($answers as $ans_info) {
$meta = self::bsp_unserialize($ans_info->display_meta);
foreach ($meta[fields] as $fields) {
if ($fields["id"] == $ans_info->field_number) {
$question["kerdes"] = $fields["label"];
$answer["valasz"] = $ans_info->value;
}
}
$toJSON[] = array("label" => $question["kerdes"], "value" => $answer["valasz"]);
}
echo json_encode($toJSON);
die();
}
So, the table shows all of the data in it, but If i would like to search or ordering or paginating nothings works.
Any hint about it?
Thx a lot
I could solve the problem.
I just modifed the append method, and now I making a html string with the ready html element and I jut append that at the end of the process.
jQuery(document).ready(function () {
var table_structure = '<table id="result" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#table').append(table_structure);
var heads = ["Result", "User", "Date"];
var results = ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"];
jQuery('.result_head tr').empty();
jQuery.each(heads, function (key, value) {
jQuery('.result_head tr').append('<th>' + value + '</th>');
});
var body = jQuery('.result_body');
body.empty();
if (results.length > 0) {
var count_heads = heads.length;
var count_answ = 0;
var html = "";
jQuery.each(results, function (key, value) {
if ((count_answ % count_heads) === 0) {
html += '<tr>';
}
if (value.substring(0, 4) == 'http') {
html += '<td><img src="' + value + '" alt="none" width="200px" height="200px"/></td>';
} else {
html += '<td>' + value + '</td>';
}
count_answ++;
if ((count_answ % count_heads) === 0) {
html += '</tr>';
body.append(html);
html = '';
}
});
}
jQuery('#result').dataTable(
{
"ordering": true,
"searching": true
}
);
});

Convert data to Json in CodeIgniter with AJAX

I am struggling to convert json code in CodeIgniter, i wanna make pagination.
I am using ajax and want to controle data convert to json and send it to view. I can someone explain me how to do that.
Code in controler, instead foreach part i am trying to make Json, and send it to view
function ajax(){
$rpp= $_POST['rpp'];
$last = $_POST['last'];
$pn = $_POST['pn'];
if($pn<1){
$pn=1;
}
elseif($pn>$last){
$pn =$last;
}
$l = ($pn - 1) * $rpp;
$this->db->limit($l, $rpp);
$row = $this->db->get('pages');
$dataString='';
foreach($row->result() as $r){
$id = $r->id;
$info = $r->info;
$dataString .= $id.'|'.$info.'||';
}
echo json_encode($dataString);
}
}
view part
function request_page(pn)
{
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
$.ajax({
type: "POST",
url: "<?php echo site_url('search/ajax')?>",
data: { 'rpp' : rpp , 'last' : last, 'pn' : pn},
dataType: "text",
success: function(msg){
// alert(msg)
;
var dataArray = msg.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "ID: "+itemArray[0]+" - Testimonial from <b>"+itemArray[1]+"</b><hr>";
}
results_box.innerHTML = html_output;
}
});
var paginationCtrls = "";
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
its easy
you should have a view to encode the data to json. Its just this:
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
In the controller you just have to load this view with an array as parameter (i think that stdClass is also valid):
$data['json'] = array("foo" => "bar", "bar" => "foo");
$this->load->view('your_json_view', $data);

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'

Passing data back from php to ajax

How can I pass data from a php of then rows back to ajax ?
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$result = mysql_query($query);
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[]=$rec['pic_location'];
$name[]=$rec['name'];
$age[]=$rec['age'];
$gender[]=$rec['gender'];
}
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Ajax
$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");
$.ajax({
url: "viewnew.php",
dataType: "json",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first image url: " + arr[0][0] + ", second image url: " + arr[0][1]); // This code isnt working
alert("first image Name: " + arr[1][0] + ", second image name: " + arr[1][1]);
$(".theImage").attr("src", arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
});
});
</script>
My question is how can I display the values here ? The Alert message is giving me "Undefined" ?
You can do something along these lines.
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$res = mysql_query($query);
$pictures = array();
while ($row = mysql_fetch_array($res)) {
$picture = array(
"pic_location" => $row['pic_location'],
"name" => $row['name'],
"age" => $row['age'],
"gender" => $row['gender']
);
$pictures[] = $picture;
}
echo json_encode($pictures);
JS
...
$.ajax({
...
dataType: "json",
...
success: function(pictures){
$.each(pictures, function(idx, picture){
// picture.pic_location
// picture.name
// picture.age
// picture.gender
});
}
});
...
You can't put multiple echo statements for the AJAX response:
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Join your arrays and send a single response:
$arr = $url + $name + $age + $gender;
echo json_encode($arr);
You can easily do this using a single Array:
$pics = array();
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pics[$rec['id']]['url'] = $rec['pic_location'];
$pics[$rec['id']]['name']=$rec['name'];
$pics[$rec['id']]['age']=$rec['age'];
$pics[$rec['id']]['gender']=$rec['gender'];
}
echo json_encode($pics);

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