i am writing a online tictactoe game and i have a function in javascript that check that if some where clicked in the screen is not X or O then mark it with X or O and then update the database where is clicked. here is my javascript code in play.php page (this is in ) where check that with isEmpty function . path is the variable that detect which cells in tictactoe is clicked(from 1 to 9) :
....
if (isEmpty(xBoard, oBoard, bit)) {
path.push(y*3+x+1);
alert(path);
markBit(bit, playerXO);
$.ajax({
type: "POST",
url: "gameProcess.php",
data: {
'ID' : path
},
dataType: "json",
success: function(){
alert('success');
},
});
....
i use ajax to update something in database with PHP (gameProcess.php) and send 'ID' value to write in a table of mysql Database.here is my gameProcess.php code:
<?php
function post($key) {
if (isset($_POST[$key]))
return $_POST[$key];
return false;
}
// setup the database connect
$cxn = mysql_connect('localhost', 'root', 'Mazda1428');
if (!$cxn)
exit;
mysql_select_db('irgc', $cxn);
// check if we can get hold of the form field
if (!post('ID'))
exit;
// let make sure we escape the data
$val = mysql_real_escape_string(post('ID'), $cxn);
// lets setup our insert query
$sql = "UPDATE game SET sequence=".$val." WHERE id = 2;";
// lets run our query
$result = mysql_query($sql, $cxn);
// setup our response "object"
$resp = new stdClass();
$resp->success = false;
if($result) {
$resp->success = true;
}
print json_encode($resp);
?>
but when i open the browser and go in play.php and click in tictactoe game the first time is OK. but after that no thing will add in DB (but still i see the alert('success')).
finally,sorry for bad english.
disable cache and try again.
$.ajax({
type: "POST",
cache: false,
url: "gameProcess.php",
data: {
'ID' : path
},
dataType: "json",
success: function(){
alert('success');
},
});
Perhaps you should add a random URL address parameter
Related
i am having trouble in concating the value of my two ID's from database to generate a new ID and use it to save again in Database. I am using codeigniter and i want something a good technique/way to concat for better result or maybe faster.
Also i am having a problem, whenever there is a value in my database, i cannot increment my ID by having +1. I got an output of 1-undefine-1
Here is my ajax:
function getcheckupID() {
var init = 0;
var value = $('#clinicID').html();
$.ajax ({
url: siteurl+"myclinic/getcheckID",
type: "GET",
dataType: "JSON",
success: function(data) {
if(data.length>0) {
$('#checkID').text(value+"-"+data[0]['clinic_id']+1);
$("#checkID").css('visibility','visible');
}
else {
$('#checkID').text(value+"-"+init);
$("#checkID").css('visibility','visible');
}
}
})
}
function get_clinicID() {
$("#clinicID").empty();
$.ajax({
url: siteurl+"myclinic/get_clinicID",
type: "GET",
dataType: "JSON",
success: function(data) {
$('#clinicID').text(data[0]['clinic_id']);
}
});
}
i check the records in my DB using this if(data.length>0) then if i got record, i go get the data and +1 it. I got a value of undefined, but if it goes to else, it outputs bad, because whenever i refresh it. sometimes it only outputs - 0, where i want is 1-0. Then refresh it again. How can i concat safely ? Is it an issue in ajax ?. making slow ?
Here is my controller for it :
public function getcheckID() {
$checkID = $this->clinic_model->checkupID();
echo json_encode($checkID);
}
My Model :
public function checkupID() {
$query = $this->db->query('SELECT tbl_check_up.check_up_id FROM tbl_check_up');
return $query->result();
}
I have three php files.
main.php - to use stored Ajax response.
filter.php - to send Ajax request and get response
insert.php - to store Ajax response for using in main.php
Primary purpose of doing all these thing is to use client side values using PHP code because server and client can't exchange variable values each other.
The response should be stored in php variable in main.php.
main.php:
?>
<script>
$.ajax({
type: "POST",
url: "filter.php",
data: { id1: name, id2:"employees"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "insert.php",
data: { id1: res },
success:function(data){
alert(data);
}
});
});
<script>
<?php
$ajaxResponse = ???? <need to get value of data over here>
filter.php:
// Return employee names
if ($_POST['id1'] == "name" && $_POST['id2'] == "employees") {
$conn = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT " .$_POST['id1']. " FROM 1_employees";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$rows[] = $row['name'];
}
}
echo json_encode($rows);
mysqli_close($conn);
exit (0);
}
insert.php:
if ($_POST) {
if ($_POST['id1'] !== "") {
echo $_POST['id1'];
}
}
So how can I get ajax response value in main.php at $ajaxResponse = ?????
You can't use it that way.
Why:
javascript/jQuery is a scripting language which runs in browser when DOM is fully loaded and elements are available to make selectors.
While php is serverside language which runs on server way before page load.
So in short you can't assign a ajax response to a php variable.
one thing you can do to have a hidden input and put the response value in it and you can get that value to use it.
success:function(data){
alert(data);
$('#hiddenInputId').val(data); // set the response data to the hidden input and use it.
}
You can create a div where you want to display the response contents
in your case it is after <script> tag
And use innerHTML to display the contents
Use this code
<script>
$.ajax({
type: "POST",
url: "filter.php",
data: { id1: name, id2:"employees"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "insert.php",
data: { id1: res },
success:function(data){
$("#responseContent").html(data);
}
});
});
<script>
<div id="responseContent"></div>
Let me know if it is helpful
Here is the answer:
Get names in main.php using below way:
-------- filter.php ----------
session_start(); //at the top
$_SESSION['names'] = json_encode($rows);
-------- main.php ----------
session_start();
$issued_to = explode(",", $names);
session_unset();
session_destroy();
The answer is to simply use Javascript to store the response from Ajax into a hidden variable and make use of that for further action. That solved my query and I'm sure many will actually need this too!
I have been searching for hours and haven't found any solutions for my problem.
This is my jQuery/Ajax code:
$(document).ready(function() {
$(".submit_btn").click(function () {
var name = $("input#name").val();
var dataString = 'query='+$("#query").val()+'&facebook='+facebook+'&twitter='+twitter;
$.ajax({
type: "POST",
url: "selectDataSets.php",
dataType: "json",
data: dataString,
success: function(data) {
alert ("hello");
}
});
return false;
});
});
Now my selectDataSets.php code:
<?
include_once 'config.php';
if ((isset($_POST['facebook'])||isset($_POST['twitter']))&&isset($_POST['query'])) {
$elements=0;
$dataSet=array();
$tt=array();
$fb=array();
mysql_connect($config['database_url'], $config['database_user'], $config['database_password']) or die(mysql_error());
$queries = explode(";", $_POST['query']);
foreach ($queries as $query){
if(isset($_POST['facebook']) && $_POST['facebook'] == true){
mysql_select_db("facebook") or die(mysql_error());
$mysql_query = "SELECT * FROM page WHERE lower(name) LIKE '%".mysql_real_escape_string(strtolower($query))."%'";
// Perform Query
$result = mysql_query($mysql_query);
while ($row = mysql_fetch_assoc($result)) {
$set = array(
"name" => str_replace("-","",$row['name']),
"likes" => $row['likes'],
"about" => $row['talkAbout'],
"source" => "Facebook (Page)",
"id" => $row["id"],
"query" => $query
);
$fb[$elements]=$set;
$elements++;
}
mysql_free_result($result);
}
}
mysql_close();
echo json_encode($fb);
}
With dataType: "json", the alert("Hello") does not work, as well as nothing that I add inside the success callback. Although when I remove dataType: "json", the alert works, but the variable data is not recognized as JSON (as I keep getting undefined when I try to do data[0].name), even though I have checked and data is on the format [ { "name: ... } ], which I guess is correct JSON. I don't know what else to do, as I have a similar (almost the same) code on another php file that works perfectly with the dataType: "json".
Thanks in advance!
Can you see the actual output of the PHP script/AJAX call using Chrome's network window?
Make sure there are no MySQL errors and stuff. The reason you get no error when you don't put dataType: "json" is because the JSON parser is not attempting to read your malformed JSON. For some reason, your example JSON is good but whatever AJAX is receiving is not good. From the network window, select your AJAX call and look at the response tab. This will show you the real output.
So far I have something like this:
//HTML
<body onload=getRoomTemp();>
//JS
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
datatype: "text";
data: {
temp: temp
}
}).done(function () { $('#getRoomTemp').append(text); });
}
//PHP
<?php
if (isset($_POST['temp'])) {
require('database.php');
$query = ("SELECT temp FROM tempWHERE tempID=1");
$res = mysql_query($query) or die("ERROR ".__LINE__.": ".mysql_error());
while ($ar = mysql_fetch_array($res)) {
$temperatureIn = $ar['temp'];
echo $temperatureIn;
}
}
?>
So, when my HTML body loads, I would like to make query and show query result in div called "getRoomTemp" with AJAX. Later, I will need the same technique to insert data in MySQL (single number value) on button click.
I can't find the problem with my current code, tried different dataType for ajax but no success. Please help..
You have 2 undefined identifiers temp and text, try
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
dataType: "text",
data: {
temp: 'temp'
}
}).done(function (text) { $('#getRoomTemp').append(text); });
}
Hi i have this simple code:
var datastring="123";
$.ajax({
url: 'actualizarimagen.php',
type: 'post',
dataType: 'text',
data: datastring,
cache: false,
success: function(response){
$('.msg1').html(response);
},
error: function(response){
$('.msg1').html(response);
}
});
And in actualizarimagen.php:
$desc_larga = print('<pre>') & print_R($_POST) & print('</pre>');
$insertSQL = sprintf("INSERT INTO prueba (texto) VALUES ($desc_larga)");
I get the success message, but in the database always saves 1. I tried changing everything, the dataType, the success, error, complete functions but it doesn't work. I was searching but any answers couldn't help me.
Thanks.
Edit: Added response
Your datastring should contain data encoded as application/x-www-form-urlencoded
e.g.: var datastring="foo=123";
It is better not to pass a string to jQuery at all. Pass it an object and let it handle the encoding for you.
e.g.: data: { "foo": "123" }
data
Object, String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
You are just sending up 123 to the server.
It should be something like
var datastring="myField=123";
or
var datastring = {"myField" : 123 };
and with the PHP you would read it
$_POST["myField"]
to send the data, there are format to be followed.
Like
var datastring="var1=123&var2=abcd";
or
var datastring=[{name:'var1',value:123},{name:'var2',value:'abcd'}];
The second format (array of object name value) is like <input type="text" name="var1" value="123"> where html input element has name and value to be posted.
Then, you can get the value by :
$_POST['var1']
or
$_POST['var2']
An example to achieve this easily could be:
JS:
var datastring="123";
$.post('actualizarimagen.php', { datastring:datastring }, function(data){
if(data != 0){
$('.msg1').html('correcto');
} else {
$('.msg1').html('error');
}
});
In your actualizarimagen.php:
if($_POST() && isset($_POST['datastring'])){
/* Connect to DB */
$link = mysql_connect('server', 'user', 'pwd');
if (!$link) {
// No connection
print(0);
exit();
}
$db = mysql_select_db('db', $link);
if (!$db) {
// DB selection error
print(0);
exit();
}
/* Sanitize the value */
$datastring = mysql_real_escape_string($_POST['datastring']);
// I don't understand here what you tried to do with $dec_larga but this is what I thought
$desc_larga = "<pre>".$datastring."</pre>";
/* Insert to DB */
$sql = "INSERT INTO prueba (texto) VALUES ('$desc_larga')";
if(mysql_query($sql,$link)){
// Everything is Ok at this point
print(1);
} else {
// Error happened in your SQL query
print(0);
}
}
In the ajax call:
data: my_var : datastring,
in the php:
$desc_larga = '<pre>'.$_POST['my_var'].'</pre>';
try replacing
type: "post",
with
type: "POST",
and your datastring should be like this :
single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
as explained here:
http://api.jquery.com/serialize/
var datastring = "123";
$.ajax({
url: 'actualizarimagen.php',
type: 'post',
dataType: 'text',
data: {data : datastring},
cache: false
}).always(function(response) {
$('.msg1').html(response);
});
And in actualizarimagen.php:
$desc_larga = '<pre>'.$_POST['data'].'</pre>';
$query = '"INSERT INTO prueba (texto) VALUES ('.$desc_larga.')"';