Updating total number on website with jQuery / Javascript? - javascript

This below is displaying Total racers on my website but its not updating live. I need to referesh the page to grab the new number from the database, so what's the simple way of updating it live with jquery/javascript without refreshing the page? Thanks a lot for taking the time to check my question and possibly answer.
<div id="stats">
<div id="racers">
<span><?=number_format($racers, 0, ' ', ' ')?></span>
RACERS
</div>
</div>

Jquery Ajax:
$.post('page.php', {
postVariable : value
}, function(data) {
//do something with data retrieved from php script
});
You set 'page.php' to a script that gets the data you want and echoes it.
You then retrieve what was echoed in the callback function(data);
So data will be the variable containing the value you need. You put this script in a
javascript function and call it when you need to make a request for information on the back-end.
If you have questions let me know. If you need more information on the ajax request you can find it here as well: api.jquery.com/jquery.post/

What you need to do this is the following:
1. Have an action in a controller that outputs the total number of racers
For example:
class Data extends CI_Controller {
public function GetTotalRacers() {
// This is dummy data. You need to replace this code with the correct
// number of racers retrieved from the database
echo 14;
}
}
Take note of where this action is. I'm assuming codeigniter will make the path something like /Data/GetTotalRacers in this case (that depends on how your route rules are configured).
2. Use JavaScript to ask the server for the data and display the result on the page
I recommend you have a method that runs every X number of seconds to refresh the total number of racers. To achieve this, you can use setInterval. Within the setInterval's function have an ajax call to your action. Finally, display the value that's returned from the server:
setInterval(function() {
$.ajax({
// Replace the url value with the correct url to access your action
url: '/Data/GetTotalRacers',
cache: false
})
.done(function( totalRacers ) {
$("#racers span").text(totalRacers);
});
}, 60000); // ex. Update every 60000ms
Note: I've never used codeigniter, but hopefully this description will help set you on the right path.

Related

How to submit value to database with jquery?

so basically i want to make a webpage to detect how many times user clicked on it and send that value to database. I know i should use ajax but just can't figure out how to use it.
var count = 0;
$("body").click(function() {
$("#track").text("you clicked " + count + " times");
count++;
});
$.ajax({
url: "index.html",
cache: false,
success: function(html){
$("#results").append(count);
}
});
Assuming the following things. You:
have AMP Stack installed with PHP & MySQL.
have a working DataBase in MySQL (most commonly used with PHP).
are running the web server and looking at HTTP version and not file version in Chrome.
I would go by this method:
On load, I'll get the current count from DataBase using a PHP backend.
In the PHP backend, I'll write a code to query MySQL and get the current value.
Use a single file, say count.php as a file to get and set the counts.
Using GET method, the file responds with the count.
Use an AJAX code and get the count data.
Using jQuery with the AJAX's response, update the DOM with the current count.
Once you load the page and update the value, set the event listener on click.
Update the current count in the UI by adding one more.
Use the same code as you have to update the UI to increment the count.
Fire a POST request using AJAX to the count.php and send the new value.
In the count.php, write an UPDATE query to update the count.
Send a success message.
When you reload the page or look at the database, the count will be preserved.

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.

Using ajax to get javascript value in another page

I have a button that counts clicks and i want that final value to get stored in my database but I'm having a hard time getting that value.
I have one page where i have the counter and i tried using ajax to get it to the other page, here's the code.
var clicks = 0;
function hello(){
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
$.ajax({
url: 'conta.php',
data: {'score' : clicks},
type: 'POST'
});
And in conta.php:
echo $_POST['score'];
The problem is when the timer runs out and it goes to conta.php there is an Undefined index: score error.
Would really welcome suggestions if possible.
$_POST['score'] is the value you posted to the URL in the response to that POST request.
If you want to get the data in a different request then you'll need to store it somewhere (such as a database) and then read it from wherever you stored it when you get the request that you want to use to display it.

Javascript code running fine until put into a function

I have taken some source code from here to submit a form using AJAX. The form is basically taking some information from a user and putting it into a database via PHP. The code I have works, but given that what I am working on has many forms all doing the same thing, I - obviously - want to make sure my code is lean and mean. So, making sure that each of my form field names have the same as my database with some matching IDs for various parts of the form for user feedback, have changed it to the following:
<script type="text/javascript">
$(document).ready(function() {
// process the form
$('#formId').submit(function(event) { // for the specified form:
// completeForm('#formId'); // WHERE I CALL THE FUNCTION
// FUNCTION STARTS HERE WHEN IT IS ONE
var formData = {}; formId = '#formId';
$(formId + ' input, ' + formId + ' select, ' + formId + ' textarea').each(
function(index){ // for each item (input, select, textarea in the specified form
var input = $(this);
// First, clear any existing formatting that has been added by previous form inputs
$('#' + input.attr('id') + '-group').removeClass('has-info has-error has-success bg-error bg-info bg-success');
// Next, add data to the array of data to pass to the PHP script
Array.prototype.push.call(formData, input.val());
}
); // End of loop through each item.
// Now the data is collected, call the requested PHP script via AJAX.
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : $(this).attr('action'), // '/processing/general_settings_processing.php', // the url where we want to POST
data : formData, // our data object
dataType : 'html' // 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// Return success and error messages to the user
// Code to come once the basics have been sorted out!
});
// FUNCTION WOULD END HERE WHEN IT IS ONE.
event.preventDefault();
});
});
</script>
The code as above works absolutely fine; the relevant PHP file is called and - although I have no processing done in this particular file yet - does its stuff (I have it echoing the $_POST array to a file and returning to view in the console log atm).
However, when I try and make it a function, it doesn't - the console log simply echoes out the source code for this document instead of the PHP array that it supposed to be doing. The function is placed above the $(document).ready line; specified as function completeForm(formID) { . . . } , contains the section of code as noted in the comments and called in the commented out line as shown. So, logically (to me) it should work.
The ultimate idea is to have the function to do this in a file that can be called by all the forms that call it, while the code to call the function is in the relevant part of the page. Some pages will have more than one form using it. (I mention that should even if what I am doing here works, it wouldn't when I come to reuse the code!)
(I'm relatively new to JS and JQuery, although have a fairly good grasp of some programming techniques, mainly these days just in PHP.)
The issue you are having with making that a function is you forget to include the "thisBinding". As a result, when you tried to use the form's action target in your ajax call with this code:
url : $(this).attr('action')
it does not find an "action" attribute - basically the issue is that this is actually window and as a result there is no action attribute. Simply bind this to your function call and your code will work as written.
completeForm.call(this,'#formId');
.call MDN

Periodically autosave form

How to implement a periodical save of a form in the background? Same kinda thing that gmail does.
setInterval(function(){
var form = $('#my-form-id');
var method = form.attr('method').toLowerCase(); // "get" or "post"
var action = form.attr('action'); // url to submit to
$[method](action, form.serialize(), function(data){
// Do something with the server response data
// Or at least let the user know it saved
});
},10000); // do it every 10 seconds
If you don't want to use the method of the form, but always want to use 'post', then use:
$.post(action, form.serialize(), ... );
And, if you want to supply your own action for the autosave that is different from the action for the actual save:
$.post("/autosave/comments", form.serialize(), ... );
You would need a timed loop on the client side that would save the form every x seconds/minutes. A crude way of doing this would be to have a setTimeout javascript function that collects the form's field values and updates the model via an update (PUT in Rails' case) AJAX request.
Example
Here's a crude way of doing it (i.e. there might be a better way):
// repeat every 10 seconds
var repeatTime = 10 * 1000;
function updateModel(){
// get field values (using jQuery, etc.)
// make ajax request using these field values
//(make sure put parameters match model attribute names)
console.log('updated');
setTimeout(updateModel, repeatTime); // start call over again
}
setTimeout(updateModel, repeatTime);
I included the console.log so that you can test this out in Firebug right now and see that the updateModel executes every 10 seconds. I would recommend using jQuery to generate the PUT AJAX requests.
Why not do this purely on the client, using a local database (or whatever)? That should reduce complexity, server load and bandwidth usage.
Permanent or per-session storage -- whatever's appropriate -- and you can save after every keystroke: no need for setTimeout().
Sisyphus.js: Gmail-like client-side drafts and bit more. Plugin developed to save html forms data to LocalStorage to restore them after browser crashes, tabs closings and other disasters.
http://sisyphus-js.herokuapp.com
Smashing Magazine article: http://coding.smashingmagazine.com/2011/12/05/sisyphus-js-client-side-drafts-and-more/
Version that works without jquery:
function urlencodeFormData(fd) {
var s = '';
function encode(s) { return encodeURIComponent(s).replace(/%20/g,'+'); }
for (var pair of fd.entries()) {
if(typeof pair[1]=='string') {
s += (s?'&':'') + encode(pair[0])+'='+encode(pair[1]);
}
}
return s;
}
setInterval(function() {
var form = document.getElementById('my-form-id');
var request = new XMLHttpRequest();
request.open(form.method, form.action);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
request.send(urlencodeFormData(new FormData(form)));
}, 10000);
If you need to do something with the server response see this post: https://blog.garstasio.com/you-dont-need-jquery/ajax/#posting

Categories