Updating webpage with real-time database value using AJAX+PHP response - javascript

I’m creating a Javascript game and I’m currently trying to write some code that will show the player’s “Gold Balance” in real time on a html webpage.
The Gold amount is contained in my SQL database, so I’m using setInterval with a Javascript function that contains an AJAX call which calls a PHP script that grabs the current balance amount for the player and sends it back as “response”.
I’m able to have this amount appear as a Javascript alert, however I need to have the response appear as text on the webpage inside a <div> instead.
This is my current code:
<script>
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
alert(response);
}});
};
</script>
I have this in my html source code, I would like to place the function in a separate file and call it from there, but when I tried this I wasn't able to send the response back to the html page correctly.
I was wondering if anyone knows how to have this response appear as text on the page inside <div> </div>?
Also, I was wondering if this method will really update the div in real time (ie, will it auto-refresh the div part of the webpage, showing an up to date value (every 5000 milliseconds)?
Thanks in advance!

Since you are using jQuery, you can use text() to alter the contents of an existing div (which id is "yourDiv"):
setInterval("checkGold()",5000);
function checkGold()
{
$.ajax({
url: 'scripts/checkGold.php',
data: "",
dataType: 'json',
success: function(response){
$('div#yourDiv').text(response);
}
});
};

You have two questions here, so I will try to address both
1) How to append to the DOM using jQuery, instead of an alert:
in the success callback function, instead of alerting the response, you can simply call
$('body').append("<div>"+response+"</div>")
2) "Real time" Gold Balance
You should use websockets. Racthet is a good websocket PHP library to help you with this: http://socketo.me/

Related

Save HTML DOM to file on server

I have an html5 web page that allows users to drag-n-drop objects between divs. After a user has moved objects around, I would like to save the current DOM to a file on my web server.
I know I can get the current HTML DOM using javascript but of course, I cannot save to a file on my server using javascript. So I thought about passing the html to a PHP page to do the "save" function, but I cannot figure out how to get the html passed to a PHP page. I've tried sending it as an argument in the URL with URI encoding, but the PHP page is not properly getting the entire string from the URL.
Should this approach work? If so, what am I missing to get the html string passed correctly to a PHP page? Or should I be using some other method?
ajax is the way to go here. If you are not familiar with ajax, please google it and learn it well. Any modern web app needs to have ajax integration in some way.
Here is how you can use javascript to communicate with the server.
Please Note I'm using JQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".draggableDivs").mouseup(function(event){
var documentStructure = ''; // whatever js you use to get document structure
var d = {"document_structure": documentStructure};
$.ajax({
url: "test.php", //Your url both relative and fixed path will work
type: "POST", // you need post not get because you are sending a lot of data
data: d,
success: function(response) {
alert('saved');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
on the server you would then do your php and save the data.
After you are done you can just respond with a json object if needed, if not just exit
you can use the approach like
after the drag and drop with javascript, show a button to save the dom.
on click event on the button, take the current dom in a variable.
use ajax to transfer your current dom to a php file(ajax file).
in the ajax file , save it into database.

How to write a div with jquery or javascript?

I was looking a solution to write one table, which comes from query to a DB in PHP, to a DIV, using Jquery. I'm not looking for the append's method, which I know works, but with append every time I press the button, which executes the query, the table is append to the document. The idea is not to load every time the page, but using the Jquery option, to send the post and get data back. Thank you.
UPDATE
<script>
var values = {var1: 2, var2:"Hello"};
$.get("phpfile.php", values, function(data) {
$('#id').append(data);
});
Suppose that script is call from a "onclick()"; I don't want the append each time the data, but just write in a div.
If I get you right, you just want to "update" the contents of a single div instead of reloading the whole page and this update contains a html table?!
For this purpose you could use the .html() function of jQuery: jQuery html()
In addition you should check .ajax() function of jQuery for all options/parameters: jQuery ajax()
A sample code could look like this:
$.ajax(
{
url: "yourfile.php",
cache: false,
success: function(htmldata){
$("#IdOfYourDiv").html(htmldata);
},
error: function(jqXHR, status, errorThrown){
alert("something went wrong");
}
}
);
This would load data returned for example via an echo of the php file yourfile.php, load it in the temporary variable htmldata and write/update the html contents of YourDivID with the newly returned data.
1 - on button pressed, do ajax get request (see https://stackoverflow.com/a/5942381/1163786)
2 - server receives request
3 - server sends back json response or html fragement
4a - json arrives and you start looping over these elements to build your desired html structure, then insert into the dom
4b - html fragment arrives and you simply insert it at the desired position into the dom
It's your decision, if you return a JSON respones or a HTML response.
For 4a and 4b read:
Best way to add DOM elements with jQuery
Best Practice For Creating HTML (PHP Or Jquery)?
Every piece of these steps is already explained on StackOverflow.

Return result to a PHP variable from AJAX in a jQuery function

So this is the hardest thing I've ever tried to do, I cannot find any answers after 1 day of searching. Note that I am using some custom jQuery API and will explain what it does.
The setup is a php page that contains a jQuery function. That jQuery function calls the API to return a result based on a row I clicked (it is jQgrid, basically looks like an online excel sheet). That works fine, but the objective is to get that result OUT of the jQuery function and store it in a PHP variable. I am just clueless......
Main PHP Page:
$getUnitID = <<<getUnitID //This is the jQuery function. It is stored in a php variable for use in other functions of the API
function(rowid, selected)
{
var selr= null;
if(rowid != null){
selr = jQuery('#grid').jqGrid('getGridParam','selrow'); //This will give ma a number result based on the row I selected. Works fine.
$.ajax({ // I believe I need to use AJAX so here is my attempt
type: "POST",
url: "getId.php", //This is another PHP page for the reuslt. See below
dataType: "json",
data: {selr:selr},
success: function(data) {
alert (data); // This will successfully show me the row number I chose as an alert. But I don't want an alert, I want it stored as a php variable in my main document to use elsewhere.
}
});
}
}
getUnitID; //End of the function
$grid->setGridEvent('onSelectRow',$getUnitID); //Just an event that calls the function upon clicking the row
$rowResult = ??????? //I need this variable to store the result of that AJAX call or that function call
getId.php
<?php
$rId = $_POST["selr"];
echo $rId;
?>
Essentially, I have no idea why I am using AJAX, because my result is still stuck inside the main jQuery function. How in God's name do I get it OUTSIDE that function?!?!?!?!?!?!?! Do I need to $_GET the 'selr' that I POSTed to getId.php ? If so, how?
Thank you, I love you all.
By the time you get that AJAX request sent out and response received, PHP has already gone to sleep. You cant give the data back to your same page's PHP code. Your jQuery starts executing on client computer long after PHP has already finished its work on your server.
It doesn't matter whether your JavaScript function is stored in a PHP variable. PHP will not get its output back. Only way you can do so is to launch another new request to that code and send value to it. but on the same very request on the same very page, its a no no.
Example of how you can send that data to another PHP page
//Your existing jQuery
success: function(data) {
// alert (data);
var result=data;
$.ajax({
type: "POST",
url: "anotherpage.php",
data: { data: result }
});
}

How can I use jQuery to run MySQL queries?

Is it possible to run a MySQL query using jQuery? I'm trying to emulate the functionality of voting on SE sites.
The vote counter on SE automatically updates without the need to reload the page (which is what I currently have, a hidden form that re-submits to the current page but runs a small block on PHP that updates the score of a question in the database). I'm assuming that is being done using Javascript/jQuery seeing as it is dynamic.
How can I do this? Is there a library which makes it easy and simple (like PHP)?
You can use ajax to call a server page (PHP / ASP /ASP.NET/JSP ) and in that server page you can execute a query.
http://api.jquery.com/jQuery.ajax/
HTML
<input type='button' id='btnVote' value='Vote' />
Javascript
This code will be excuted when user clicks on the button with the id "btnVote". The below script is making use of the "ajax" function written in the jquery library.It will send a request to the page mentioned as the value of "url" property (ajaxserverpage.aspx). In this example, i am sending a querystring value 5 for the key called "answer".
$("#btnVote").click(function(){
$.ajax({
url: "ajaxserverpage.aspx?answer=5",
success: function(data){
alert(data)
}
});
});
and in your aspx page, you can read the querystring (in this example, answer=5) and
build a query and execute it againist a database. You can return data back by writing a Response.Write (in asp & asp.net )/ echo in PHP. Whatever you are returning will be coming back to the variable data. If your query execution was successful, you may return a message like "Vote captured" or whatever appropriate for your application. If there was an error caught in your try-catch block, Return a message for that.
Make sure you properly sanitize the input before building your query. I usually group my functionalities and put those into a single file. Ex : MY Ajax page which handles user related stuff will have methods for ValidateUser, RegisterUser etc...
EDIT : As per your comment,
jQuery support post also. Here is the format
$.post(url, function(data) {
alert("Do whatever you want if the call completed successfully")
);
which is equivalent to
$.ajax({
type: 'POST',
url: url,
success: function(data)
{
alert("Do whatever you want if the call completed successfully")
}
});
This should be a good reading : http://en.wikipedia.org/wiki/Same_origin_policy
It's just a few lines in your favorite language.
Javascript
$.post('script.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
PHP (simplified)
$id = intval($_POST['id']);
mysql_query("UPDATE votes SET num = num + 1 WHERE id = $id");
There are many different ways to accomplish this.

how to use JSON for an error class

Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")

Categories