Check database after inserting data and update listview - php

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.

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

Show each response of php file using ajax

I use ajax type for send data to php file and get response and show. In my php file i have
while($i<14){ echo $i.'<br />'; $i++;}
that return 14 replay.
So, my webpage when call data with ajax method, after some secounds, show all 14 results. But i want get live response from my ajax file.
So i want my webpage show :
1
...
and then
1
2
....
etc
This is my Ajax code that return all response together in shower div.
I want get live responses. for any responses that sent from php file
function update_table(uptype){
$("#shower").html("Loading...");
var dataString = 'type=' + uptype;
$.ajax({
type: "POST",
url: "motor.php",
data: dataString,
cache: false,
success: function(html) {
$("#shower").html(html);
}
});
return false;
}
What you are asking is not possible with your current setup.
Think of an ajax-call to a PHP-script is like visiting a website like www.example.com/yourscript.php
PHP will then server-side render a code which is sent to your web-browser. This is a one call and one answer operation. PHP will not dynamically add elements to the website. Neither will it then be able to dynamically send answers to your ajax-call. What you have to do to solve this is storing the progress of the PHP script somewhere, and do several calls to get a update on the status.

Update MY SQL DB Table from jQuery

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));
?>

Sending Data From A PHP Script Back To A JQuery AJAX Request

I am creating a web application and have the following problem.
In my application the user is working within a single page, they draw on a canvas. There is a single button called "Save". This takes the users ID and whatever they have created in the canvas and sends it to a database. This all works fine. The save function resemebles this:
$.ajax({
url: "/database/write.php",
type: "POST",
data: {
docName: name,
docData: document_Data,
docMode: "new"
},
success: function(html) {
alert("Successfully Saved NEW document");
set_Mode();
},
});
The above AJAX request does send the three values to the PHP script which then successfully creates a new document in the database, what i need to do now is change the application mode from saving a new document to editing the previously saved document. This means that when a user saves again, they will write to the same row, overwriting the previous version of the document.
When i send the data to the write.php it does write the data to the DB and the queries the database for that inserted document and retrieves its unique document ID. with that ID the application can the select that document and overwrite it. To retrieve the document ID from the query, i use the following code in write.php
write.php
$_SESSION['DOCUMENT_ID'] = $DOCUMENT_ID;
This $DOCUMENT_ID is the document ID retrieved from the SELECT query. The script then finishes and transfers control back to the main application page.
Back on the application page i try to retreive the value but it doesnt seem to work. I can retrieve $_SESSION values that were set when the user first accesses the application (id) but now values set by the write.php (DOCUMENT_ID) page. For example, below shows the function called after the AJAX request has been successful:
function set_Mode()
{
var PHPvar_01 = <?php echo($_SESSION['id']); ?>;
alert(PHPvar_01); //WORKS FINE
var PHPvar_02 = <?php echo($_SESSION['DOCUMENT_ID']); ?>;
alert(PHPvar_02); //DOES NOT WORK.
};
How should i go about sending data retrieved from the PHP query script to the application, because $_SESSION does not seem to work here.
Thanks for any feedback.
at the end of write.php :
echo json_encode(array('id'=>$_SESSION['id'], 'DOCUMENT_ID'=>$_SESSION['DOCUMENT_ID']));
in your ajax call :
success: function(data) {
data = eval('('+data+')');
alert("Successfully Saved NEW document");
set_Mode(data.id, data.DOCUMENT_ID);
},
this should do the tricks !
In your write.php, you should echo the $DOCUMENT_ID at the end of the page, and then your success function will receive that in the html argument. Then you should call set_Mode with the html variable that was passed into the success function.
You can't call set_Mode until after the page is loaded, and after you know the document ID. You are writing the document ID into the set_Mode function before you know it, in the initial page load.
Well, your PHP code gets executed only once upon the initial loading of the page. The server detects a request to your site, loads the PHP document internally, parses it and delivers it to the client.
Therefore, when the AJAX call returns, the entire PHP script is not executed again, because the user didn't request the whole page but only sent a single request to your write.php.
Your write.php script must return the $DOCUMENT_ID in some way, e.g. echo it directly, then the success handler in the jQuery AJAX call can access it via the handler's parameter (see jQuery documentation).
You can't access variables on the server when the page is already loaded in the users browsers, other than with ajax.
You need to send something back, and in PHP all you have to do is echo something, and capture it in the success function of your Ajax call.
at the end of /database/write.php, do
echo $_SESSION['DOCUMENT_ID'];
and in JS
$.ajax({
url: "/database/write.php",
type: "POST",
data: {
docName: name,
docData: document_Data,
docMode: "new"
},
success: function(data) {
alert("Successfully Saved NEW document");
set_Mode();
if (data == 'something') {
//do something with the returned DOCUMENT_ID stored in the data variable
}
},
});

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

Categories