Call PHP file in JavaScript Function for Updating MYSQL Table? - php

I want to integrate a Java script Slot Machine game into my script.
You can see demo here ; http://odhyan.com/slot/
And also git hub is here ; https://github.com/odhyan/slot you can see all JS files here.
I created a Point Coloumn in User Table that people can play the game with this Point.
I think this JS Function in slot.js checking if user won the game or lose.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
} else {
res = "You Lose";
}
$('#result').html(res);
}
So i want to add +100 Point if user won the bet.
I made this PHP codes Uptading points For userid "1".
<?php
mysql_connect ("localhost","username","password") or die (mysql_error());
mysql_select_db('slot_machine');
$pointsql = mysql_query("SELECT * FROM user WHERE userid = 1");
while ($row = mysql_fetch_array($pointsql))
{
$row['point'] +=100;
$addpoint = mysql_query("UPDATE user SET point = '{$row['point']}' WHERE userid = 1");
}
?>
So how can i call or excute this PHP Codes in JavaScript function if user Win?

You'll need to trigger a network request from your javascript code to execute your php script server side. Using jQuery's $.ajax() function is an extremely common way to do this abstracting away various browser differences.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
} else {
res = "You Lose";
}
$('#result').html(res);
}

You can use jQuery's $.post() function to trigger an asynchronous request to your PHP file.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
// Here's the line you need.
$.post('score.php', {userid: 1}, function(data) {
alert("Score saved.");
});
} else {
res = "You Lose";
}
$('#result').html(res);
}
This will send POST data to score.php, or whichever file you want to send the data to. The PHP file can then access the userid sent to it by checking the value of $_POST['userid'].
As mentioned in the documentation, $.post() is a shortcut for jQuery's $.ajax() function that is simplified and has some of its options pre-set. The third argument in $.post() is a callback function, and the variable data will contain whatever is echoed out or printed from score.php by the time it's done executing. So, you could use alert(data) instead, to see what score.php printed out. This is useful for troubleshooting and error handling.

try this
$(document).ready(function(){
setInterval(function() {
$.get("databaseUpdated.php");//or what ever your php file name is with corrct path
return false;
}, 1000);
});
hope this will help you use it in your function
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
// if
setInterval(function() {
$.get("databaseUpdated.php");//or what ever your php file name is with corrct path
return false;
}, 1000);
} else {
res = "You Lose";
}
$('#result').html(res);
}

Related

How To Return Data from PHP to Use in jQuery(ajax)?

I have to process a Simple log-in File. In Many Web Tutorials I have read that for any Ajax requests in jquery the callback function is function(data) and the data is returned by the server side script.
Well, my server side script is PHP. I wish to know how can I return data from PHP which will be stored in jquery's data and I can use conditional loops to process them.
Here is my jquery Code:
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, processLI );
function processLI(data) {
if (data == 'success'){
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
}
I am using simple return statement in my php file, which does not seem to work at all. here is the login.php file. I just posted the part necessary here.
$statement = $connection->prepare("SELECT * FROM users WHERE username = '$username'");
$statement->execute(array());
$result = $statement->fetch(PDO::FETCH_ASSOC);
if ($result['password'] == $safepass) {
setcookie("Login", true);
echo 'success';
}
else
echo "Failure";
Try doing it like this, by placing the function as the parameter, and not by calling the function.
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, function(data){
if (data == 'success') {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
});
Use the echo statement to output data, if the login is successful echo 'success';
This is an answer about how to debug AJAX requests. First, use Chrome (or Safari, or Firefox with Firebug plugin installed), then open up the developer tools from the settings menu. In the network panel, you can see the request/response. It may not be a direct answer, but please - try to use the Chrome developer tools with the "Net Panel" to see request/response/cookies/headers.
This will save you the trouble of having to guess, it will show you the response verbatim. Then you can solve it next time ;) and the time after
Have you been able to see the request/response? If not, I suggest a simple
alert(JSON.stringify(data))
...from your callback function if you have issues using the Chrome debugger.
Try giving the dataType for post as 'html'
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.ajax({
url : 'login.php?'+querystring,
cache : false,
success : function(data) {
if(data == "success") {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
} else if(data == "failure") {
alert("Login Failed");
}
};
});
});

jQuery $.post Callback Function (data) is Undefined

I submit a form using jQuery to a php file on my server.
Everything works... (the php file gets the right post variables, makes a database entry etc.)
But on the response, sometimes 'data' goes wacky.
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
if ( data.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
}, "json");
});
php script returns (on success)
$response['status'] = 1;
$response['message'] = 'worked';
echo json_encode($response);
exit();
I'm getting a whole lot of crap, and not enough awesome sauce.
Does anyone have an idea why sometimes 'data.status' is undefined, and sometimes it isn't?
Try it like this>
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
var obj = jQuery.parseJSON(data);
if ( obj.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
});
});
How does exit() behave with regards to output buffering? Does it flush the output buffer?
try this one:
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize())
.success(function(){
alert('awesome sauce');
}).error(function(){
alert('crap');
});
});

Using Ajax to generate an alert box after checking whether some data are stored in database [duplicate]

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

calling php function in jquery

I have one file json.js and one php function in php file .in json.js i want to check value returned by php function if value returned by function is 0 jquery should perform :$(':input').prop('disabled', true); otherwise nothing –
function loadJson (table, id) {
$.get("json-object.php", {'table': table, 'id':id}, function (data) {
console.log(data);
$.each(data, function (k, v) {
if ($('input[name="'+k+'"]').is('input[type="text"]')) {
$('input[name="'+k+'"]').val(v);
}
if($('select[name="'+k+'"]').val(v)){
get_input_value(k,v);
}
if ($('input[name="'+k+'"]').is('input[type="checkbox"]')) {
get_input_value(k,v);
}
console.log(k+' ==> '+v);
// Here I want to check condition of php function if value returned by fucntion is 0 it should perform :$(':input').prop('disabled', true); otherwise nothing //
});
}, 'json');
}
My php function:
function ronly($id) {
//$id=$_POST['noces'];
$sql = "SELECT COUNT(noces) FROM alterdetail WHERE noces = '$id'";
$sql.=';';
//echo "QUERY <br/>";
//echo $sql;
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
if($row['COUNT(noces)'] > 0)
{ echo "you can not alter data";
return 0;
}
else
{
echo " data new ";
return 1;
}
}
You can't, as Javascript is client-side executed, and PHP is server-side executed ...
A "solution" would be to assign a Javascript variable into the PHP file that you'll read into the Javascript file, as variable are global.
Use jQuery if possible.
$('#result').load('ajax/test.php', function() {
alert('Function called');
});
Or try JQuery forms. Use a form to submit any data, and it'll give you the response as a text or JSon object.
http://jquery.malsup.com/form/#ajaxSubmit
Here is an example for you:
$('#anyForm').ajaxForm({
url: "process.php?proc=7",
dataType: 'html',
success: function(responseText) {
if(responseText == "0") {
$(':input').prop('disabled', true);
}
}
});

Jquery and ajax, my function for username checking?

I have written this ajax request for username checking...
function check_username() {
var username = $("#username").val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: $('#username').val(),
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#' + id).after(response).fadeIn(1000);
}
It all works fine just a couple of questions,
Can this code be improved in any way, this is the first ever one I have wrote so I wouldn't know.
Is there a way to make this a function for all my ajax requests rather than just username checking, so it can be used for email checking and such too. I am not sure on how to make a function like that would I have to pass variables on my onblur event which is attached to my form, at the minute it looks like this.
Is there a way to stop the ajax from running if the same error is there as previous, ie, string length should be over 3, so someone inputs AJ, and the error message 'must be over 3 characters' comes up, it the user then triggers the onblur event again, with the value of AJ, or CG, then the same error comes up, triggering a script that is useless and using memory.
Is there a way to make the ajax request with every character the user enters?
My ajax php is as follows...
<?php
require('dbc.php');
if (isset($_REQUEST['username'])) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
?>
To answer 1 & 2. I would turn it into a plugin and do something along these lines.
$.fn.checkValid = function(options)
{
var response = function(response) {
var setClass = '';
var $span = $(this).data('checkValidTip');
if ($span)
{
$span.remove();
}
if (response === undefined) return;
setClass = (response.valid ? 'valid' : 'invalid');
var $span = $('<span>' + response.msg + '</span>');
$(this)
.data('checkValidTip', $span)
.after($span);
$span.hide()
.fadeIn(1000)[0]
.className = setClass;
};
var ajaxOptions = {
type: 'GET',
url: 'ajax.php',
success: response,
dataType: 'json'
};
this.each(function() {
var that = this;
var ajaxRequest = ajaxOptions;
ajaxRequest.data = {};
ajaxRequest.data[options.key] = this.value;
ajaxRequest.context = that
$.ajax(ajaxRequest);
});
};
Usage
$('#username, #email').blur(function() {
$(this).checkValid({ key: this.id });
});
PHP changes
You should make your PHP function return a JSON, instead of HTML i.e.
<?php
// Do your sql statements here, decide if input is valid or not
$arr = array('valid' => $is_valid,
'msg' => $error_or_good_msg
);
echo json_encode($arr);
/* For example will output:
{
"valid": "false",
"msg": "<b>Error: Must be at least 2 characters</b>"
}
Which can be read directly as response.valid
or response.msg from within response() function
*/
To answer question 3: short answer is no. For this to work, you should have basic validation in JS. The best option would be to use a plugin that uses objects for validation parameters, that way you can output your validation requirements dynamically from your database, from within PHP using json_encode i.e. your output format would be:
var validations = {
username: {
min_chars: 4,
max_chars: 10,
valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
},
email: {
regex: /./ //your magic regex here
}
};
jsFiddle
http://jsfiddle.net/sqZfp/2/
To answer 4, just change the event as above from .blur to .keyup should do the trick.

Categories