How to submit value to database with jquery? - javascript

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.

Related

Ajax Call to refresh web page

Update: I am using an apache server on the back-end and vanilla JS and jquery on the front-end.
Currently i have a web page that is displaying a variety of data that i am pulling from my back-end server.
How it works: I have a php script that is scraping directory names and displaying them in a dropdown. I have a refresh function set in my html for the web page that refreshes the page every 30 seconds.
The problem: I don't like the constant refresh, especially if there is nothing to update.
Is there a way to use ajax to pool my back-end server and check if new data has been entered in the directory and then update my dropdown?
Many thanks!
Use .data
window.setInterval(function() {
$.getJSON('/foo', { }, function(result) {
//Get the old data stored in the body using jquery data
var old_data = $('body').data('my_data');
//If objects are not the same, update cell
if ( ! equal_objects(result, old_data) )
update_cell();
//Store the new data
$('body').data('my_data',result);
});
}, 30000);
OBS: equal_objects is a function you should implement to compare 2 objects since JavaScript doesn't provide this functionality. See this post for details: Object comparison in JavaScript

How do I sync an AJAX call to a php file with posting data through a form to the same file?

My problem is update.php only gets the posted form data (post_edit). The variables posted earlier through AJAX don't go through
Notice: Undefined index: id_to_edit in ...\update.php on line 5
Notice: Undefined index: column_to_edit in ...\update.php on line 6
What I'm trying to do:
I have a callback function that traces the mouse's position on the table's body. This is done to detect the column and the id of the cell that the user wants to edit - id integer and column string are posted to a php file through AJAX and used in an SQL query using both values (for coordinates) on top of the data the user wants to update (posted through a form, more on this later).
Editing is done this way: when a user mouses over a cell a form is created inside, and filling in that form should post the data to update the corresponding entry in the SQL table (which is found by using the coordinates from the callback function). Mousing out removes the form.
To paraphrase a bit
How do I post the coordinates and the form data to a php file so that all these values can be used in an SQL query? If what I've been doing is fundamentally broken, is there another way?
$(function(){
$("td")
.hoverIntent(
function(e){
var id_of_edit = $(e.target).siblings('th').text();
var $clicked_column_i = $(e.target).index() + 1;
var column_of_edit = $("#tableheader").children("th:nth-child(" + $clicked_column_i + ")").text();
$.ajax({
type: 'POST',
dataType: 'text',
url: 'update.php',
data: {
'id_of_edit': id_of_edit,
'column_of_edit': column_of_edit
},
});
var $edit_button = $('<form action="update.php" method="post"><input type="text" name="post_edit"/></form>');
$(e.target).append($edit_button);
console.log(e.target.innerText + " was clicked");
console.log(id_of_edit + " is the ID");
console.log(column_of_edit + " is the column name");
//just to check the tracer function is working correctly
},
function(e){
$id_of_edit = $(e.target).siblings('th').text();
$clicked_column_i = $(e.target).index() + 1;
$column_of_edit = $("#tableheader").children("th:nth-child(" + $clicked_column_i + ")").text();
$(e.target).children('form').remove();
});
});
update.php:
<?php
include 'config.php';
echo $_POST['id_to_edit'];
echo $_POST['column_to_edit'];
echo $_POST['post_edit'];
$stmt = $pdo->prepare('UPDATE food SET :column = :edit WHERE id = :id');
$stmt->execute([
'id' => $_POST['id_to_edit'],
'column' => $_POST['column_to_edit'],
'edit' => $_POST['post_edit']
]);
?>
An ajax request and a form submission via standard postback are two separate HTTP requests. Your "update.php" script will execute twice - once for each separate request, and each request will have separate sets of POST variables, according to what you sent on that request. The variables do not persist between requests - just because you sent them to the same endpoint script does not matter.
To summarise: HTTP requests are stateless - they exist in isolation and any given request knows nothing about previous or future requests. Each one causes the named PHP script to run from start to finish, as if it had never run before, and might never run again. It remembers nothing about the past, and knows nothing about the future, unless you do something about it explicitly.
If you want values to persist between requests you have to store them yourself - in a DB, Session, cookies, whatever (it's up to you) - and then retrieve them later when you need them.
Having said that, looking at your server code it's not clear why you would want two separate requests anyway - you are doing a single UPDATE statement in the SQL, so it would make more sense to use one HTTP request to transmit all the data to the server, and then execute the script which runs the UPDATE. Unless there's some reason in the UI why this can't be done, in which case then you need to persist the values somewhere in between requests. From your description, you could potentially capture the cell/column ID into a hidden field inside the form you generate, rather than sending them immediately to the server via ajax. The hidden field values would then be posted to the server together with the user-generated values when the main form is submitted.
Also, if you really are using the mouse's position to determine the cell, this sounds very unreliable - browser windows can be resized to anything. Surely putting an ID inside the HTML markup of the cell (e.g. as a data- attribute) which you can then read when the cell is clicked / moused-over would be much more reliable?

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.

Updating total number on website with jQuery / 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.

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.

Categories