Update MY SQL DB Table from jQuery - php

Based on the user input's, i calculate some values on my submit action of my form. I have to persist these values in my backend DB. I use PHP for my server side scripting. Please let me know the best practice for doing this. It is a single page application and i use .load("Report.html"); to show the summary page.
Just thinking aloud, can i fetch the row(to be updated) from DB, json_encode, update the json object in jQuery, decode it, then update in DB?
Please help...
My submit button code...
$('form').on('submit', function(event)
{
event.preventDefault();
//CALCULATE SCORE
var noOfCorrectAnswers = 0;
var noOfQuestionsViewed = 0;
$.each(questionsArray, function(i, item)
{
if(item.correctOption == item.selectedAnswer)
{
noOfCorrectAnswers++;
}
if(item.isQuestionViewed == 'YES')
{
noOfQuestionsViewed++;
}
});
alert(noOfQuestionsViewed);
$('#sampleDiv').load("UserReport.html");
});

Run some AJAX passing all of the information you need (which may even be none depending on your use case) from the client-side to your server-side PHP. Your PHP script can fetch things from the database if necessary, make any calculations and/or manipulations and then store the information back in the DB.
If you need to return information to your client-side after updating the database then try returning a JSON object (by just printing the code out in the proper format) from your PHP script before exiting with whatever your JS needs.
Do note that this should be all done asynchronously, so you need to setup your AJAX callback function to handle any information that's returned from your PHP script. If you want to do it synchronously, go for it - but you asked for best practices :P
Looks like you're using jQuery - here's the documentation on AJAX
Raunak Kathuria's answer provides some same code

On form submit make ajax call to set database in the db and access the json
$('form').on('submit', function(event)
{ ...
alert(noOfQuestionsViewed);
$.ajax({
url: "yourphp.php", // php to set the data
type: 'POST',
data: 'yourparams', // all the input selected by users
dataType: json
success: function(json){
//here inside json variable you've the json returned by your PHP
// access json you can loop or just access the property json['sample']
$('#sampleDiv').load("UserReport.html", function () {
// its callback function after html is loaded
$('#someid').html(json['sample'));
});
}
})
You can also use the done callback of ajax
PHP
yourphp.php
Set the values here in db running the desired query and return values using
<?php
// your db ooperations will come here
// fetch the db record
// return the db records in json
$responseVar = array(
'message'=>$message,
'calculatedValue'=>$calculated
);
echo (json_encode($responseVar));
?>

Related

Check database after inserting data and update listview

What I know is how to download and upload data from the database.
But how do I control, whether a data has been uploaded on the database? And if a data has been uploaded, I want to know how to get this data to put this to the listview without reloading the whole database again?
In other words I want to have the new written text in the listview in real time, like a messenger.
Piggybacking off of #CptMisery's answer here, I agree that ajax would be useful for this.
I use this quite often when I'm writing to a database - as a form of callback to ensure data was actually written. First, here's the code you'd execute in JavaScript:
$.ajax({
type: 'POST',
url: 'some_php_page.php',
data: { data:data },
success:function(data){
if ( data == 0 ) {
console.log("item has been updated");
} else {
console.log("item has NOT been updated");
}
}
}); //close ajax
What this does is the ajax call sends the variable data as a POST to your some_php_page.php. You can send multiple items like this: data: { data:data, variable1:variable1, age:age, date:date }. The PHP page does something, (e.g. - writes to the database), and if it's successful, you have PHP echo "0", otherwise you have it echo "1". The ajax success call happens once the some_php_page.php returns a value. The success call reads that value and then does something. This is a relatively simple way to accomplish (I think) what you're looking to do.

Best way to send and process variable sized data

On this page...
http://lab.2toria.com/reflex/index2.php
When the user has dragged and dropped blocks onto the grid, I want to be able to send the positions in some form to a php script that will save them into a table that simply records the coordinates (eg "x1y2", "x1y3", etc) into rows. The fields in my table so far are VERY simple (blockID, blockCoords)
What would be the best way to do this? I'm after your opinion on two things:-
1) Using jQuery ajax, how could I send a string containing the coordinates as a list? Would it be best to create an xml string, or is there another way I've not thought of...and how would I do this
and..
2) Based on the method used to send the data (xml, or whatever), how would I then process the data in the receiving php script to save the data into a table. I know how to save records etc, just wanting to know how best to deal with this situation.
$('element').droppable({
drop:function(event, ui){
$.ajax({
url: '/path/to/my/file.php',
type: 'POST',
data: {'left' : ui.helper.position().left,
'top': ui.helper.position().top},
success: function(data){
//do something with the response from the server
}
});
}
});
And in /path/to/my/file.php
if(isset($_POST['left'])):
$db = new mysqli('connection info here');
$q = $db->prepare('INSERT INTO some_table (left, top) VALUES (?,?)'); //prepare the statement
$q->bind_param('ss', $_POST['left'], $_POST['top']); //safe binding
if(FALSE !== $q->execute()):
return 'Query Executed!';
endif; //execute the statement
return false;
endif;
So in the php file we're simply checking for the existence of the $_POST variable left. We assume top will be available also. We make a mysqli connection, prepare a safe statement, bind the parameters as strings, using the $_POST left/topvalues. Then we check if the execution didn't return false (returns true/false), and if it didn't, we pass a value and exit out of the conditionals all together. If not, the return false will fire by default.
Edit
From your comment, you want to save the actions that the user performs until ready to actually perform the insert, that's easily doable as well.
var dc = 0,
drops = {};
dc will be the dropcount, and drops will be an object.
$('element').droppable({
drop: function(event, ui){
drops[dc] = {'left' : ui.helper.position().left, 'top' : ui.helper.position().top};
dc++;
}
});
In the above, we simply increment through the drops object, storing the information for the left/top values on each drop.
$('.save').click(function(e){
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: {'drops': drops},
success: function(data){
console.log(data);
}
});
});
Here, we have a save button with a class of save, we prevent the default action, then we sent the drops object to the server.
if(isset($_POST['drops'])):
//same process as outlined above, use a helper function to insert the rows
endif;
Now we check for the existence of the $_POST variable 'drops', we'll employ the same tactics as above. I would simply recommend a helper function saveDrops($obj), iterating the returned drops and performing a save for each obj passed in.
1) Yep, use jQuery ajax posting the coords and block id.
2) They will be available to php in the $_POST variable.
See:jQuery Post

jquery update html with returned mysql data after POST

I have a jquery/php voting system I'm working on. Once a user clicks a vote button a jquery modal pops open and they must confirm their vote by clicking "Confirm". This will send an ajax request to update the database and what not. After clicking confirm the modal will close. I would like to be able to update the number of votes dynamically on the page. I can easily grab that data from the mySQL table. My question is how does this get sent back for me to then update the html page dynamically?
Currently the page does nothing, so to the user it doesn't look like they've voted. Ideally I'd want to update the total number of votes and also inject an image that shows what they voted for.
function vote(el, id) {
$.ajax({
type: 'POST',
url: '/path/morepath/',
dataType: 'json',
data: {
'action': 'castVote',
'vote': id
},
success: function (data) {}
});
$.modal.close();
}
On the server side, respond to the POST request with a JSON object containing the number of votes and possibly the image path.
Then inside the AJAX callback, data will be that object. Then you can use jQuery to select an element in the DOM and call .text() or .html() on it to update the content.
If you're passing poorly formed data back from PHP, you can make it a bit better by giving it some structure and then making it json for javascript's ease-of-use:
$sqlResult = ...;
$responseArray = array();
$responseArray['result'] = true; //or false if it failed
$responseArray['data'] = $sqlResult;
print json_encode($responseArray);
Before you can really expect the page to respond properly to an ajax response, you must be sure your response data is being parsed correctly.
Inside of your success function, try console.log'ing your response to see what it looks like
console.log(data);
if there is something you can reference in the return data that is reliable, do a check for it:
success: function(data) {
if(data.result == 'true') {
$('someElement.someClass').someFunction();
}
}
You can change the value or html content of the voting number using a few different options such as:
...
success: function(data)
{
var $newTotal = ...//get total from data
$('voteCountContainer').html($newTotal); // or you can also use .val() if it's an input
}
...
Hope that helped,
Dan

display html select (from PHP) via jquery?

So I have a PHP backend that pulls some data from SQL, let's just say its a list of user ID numbers.
I want to be able to display that list in an html select, via jquery, after a button click.
In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery. Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.
How would you do it?
a fill-in-the-blanks code example follows:
idea 1:
function button_click() {
$.ajax({
url: "PHP_backend.php", // this does the sql query and returns the results
type: 'POST',
data: 'returnquery',
success: function(result) {
//????? put the result array or whatever into a submit, perhaps with a foreach or something similar..??
}
}); // end ajax
}
Or idea 2:
$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}
function button_click() {
/// create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed
if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.

Reading from a MYSQL table every 5 seconds and dynamically displaying results on a PHP page without refreshing

I'm looking to display data from a table in a mysql database using PHP, however, I want the data to automatically update itself and retrieve current values every 5 seconds.. WITHOUT having to refresh the page. Is this possible? Maybe with JQuery/ AJAX? If so, please explain how it can be done / point me to a resource where I can find such information
Thanks
If you use window.setInterval() and jQuery's .load() you should be able to do what you want. The PHP script should return the HTML that needs to replace the previous one.
Javascript:
function refreshData()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#container').load('path/to/script.php');
}
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
A really basic example:
function poll(){
$.ajax({
type: "GET",
url: "your/php/script/",
success: function(data){
// do something with data
}
});
};
setInterval(poll, 5000);
jQuery is a good option. Here are the docs for ajax.
You will want to make this call with setInterval
Something like this might get your started.
setIntervla(updateFromDb,5000);
function updateFromDb(){
$.ajax({
url: "getUpdates.php",
success: function(){
$(this).addClass("done");
}
});
};
What you are describing is exactly the type of the AJAX is used for, AJAX allows for asynchronous requests to be made to your server.
For learning I would suggest using a framework like Jquery and look into the AJAX api.
Basicly you will need a PHP script that query the database and responds the results the way you want them. A suggestion would be to JSON encode them.
In JavaScript on the client you will need to you things like:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "yourpage.php",
success: function(data){
//HANDLE DATA
// use JSON.parse(data); if your JSON encoding your data
}
});
},5000)
Just go to the documentation of jQuery:
http://api.jquery.com/category/ajax/
Use the command "jQuery.get()" or better "jQuery.getJson()" to make a http request to the server. Use JSON to get a better communication between server and client. Return from server side a json string and convert this on the client to an javascript object. (the function jQuery.getJson already do this for you) so you can easily access the key and values in the data array.
Just an example:
SERVER Part with PHP:
<?
$data = array('key'=>'value');
return json_encode($data, true);
CLIENT Part:
$.getJSON('myurl.php', function(data) {
// THIS ONE IS CALLED with your PHP data
alert(data.key);
});
$(function(){
window.setInterval(function(){
$.post("filename.php",{'field1':field1,'field2':field2,'field3':field3},function(data){
//callbackfunction(data)
})
},30000);//millisecs
});
And have your php file do all your sql

Categories