Can I include a php sql update within my javascript? - javascript

I am trying to use a combination of javascript and php to update a column within a sql database when a form gets submitted. The name of the sql database is "answers," the name of the column within the database is "FunctionsConsistency," and the form's id is "easytohard." I'm not sure, however, if it's possible to include the php (noted below by the asterisks) within this javascript code.
<script type='text/javascript'>
$(document).ready(function () {
$('#easytohard').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
******THIS IS THE PHP CODE*********
$stmt = $db->prepare("UPDATE answers SET FunctionsConsistency = 1
WHERE id = ? AND FunctionsConsistency = 0") or die($db->error);
$stmt->bind_param("i", $id);
$stmt->execute();
******************
},
});
});
});
</script>
Thanks!

You can't mix Javascript and PHP like that.
Php should be executed on the server side while javascript meant to be executed on the client side.
You can put the Php file on your server, and just send the request to it using ajax or whatever.
Something like:
<script type='text/javascript'>
$(document).ready(function () {
$('#easytohard').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $('http://path/to/your/php/file/on/server'),
type: "POST",
data: {id: 'your desired id here'},
success: function (data) {
// if it reach this line, it means script on the php file is executed
},
});
});
});
</script>
And your php file should be on your server (path: http://path/to/your/php/file/on/server), containing proper includes to work.
<?php
$stmt = $db->prepare("UPDATE answers SET FunctionsConsistency = 1
WHERE id = ? AND FunctionsConsistency = 0") or die($db->error);
$stmt->bind_param("i", $_POST['id']);
$stmt->execute();
Notice you can access to post parameters using $_POST in php.
There are still a few things you should consider, for example when the requests don't reach to server or what if server fail to execute php file ..., but you got the idea.
Also, take a look at this and this. Hope this helps.

Related

AJAX Sends data to PHP file, but PHP can't get data from $_POST

I am making a page on a website in PHP where a user fills out 3 fields and hits submit. The submit button should call my AJAX function to send the data to a database connection PHP file. I can confirm the data is sent from AJAX (via an alert) and the function returns a Success. This must mean my database query file is not interpreting the data correctly. Please help me understand where I went wrong.
Code from php page where the form is:
<script type="text/javascript">
function storeInvoice() {
//var c_name = document.getElementById('c_name');
//var c_license = document.getElementById('c_license');
//var c_licenseemail = document.getElementById('c_licenseemail');
var data=$('#myForm').serialize();
$.ajax({
url: "/paydb.php",
type: "POST",
data: data,
async:false,
dataType:'html',
success: function (value) {
alert("Sent: "+data);
}
});
}
</script>
Relevant Code from Database php file:
mysqli_select_db($conn, "main_db" );
$c_license = $_POST['c_license'];
$c_name = $_POST['c_name'];
$c_licenseemail = $_POST['c_licenseemail'];
//Another method was attempted below.
//$data=$_POST['serialize'];
//$c_licenseemail = $data['c_licenseemail'];
//$c_license = $data['c_license'];
//$c_name = $data['c_name'];
$query = "INSERT INTO `invoices`(`company`, `licensenum`, `licenseemail`) VALUES ('$c_name','$c_license','$c_licenseemail');";
mysqli_query($conn, $query);
The data is sent as:
c_name=testname&c_license=3&c_licenseemail=testemail%40email.com
Any help is much appreciated!
Please use the
mysqli_query($conn, $query) or die(mysqli_error($conn));
For duplicate key, you need to make the primary key to auto increment in your database.
In your success callback function replace alert(data) with alert(value) and in your database.php file echo any of the post variables to just check whether the values are correctly sent to database.php via ajax post.

how to fetch data from sql server database in php without refreshing the page

I am trying to get some data from the database. I create a function that is located in functions.php file that return a value. On another page, I create a variable and just get that value. I was trying to use the onkey to check the database but then I realize that i need to know the amount of tickets even if they don't type anything.
Here is the function:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$amount_of_tickets = $row['number_of_tickets'];
}
return $amount_of_tickets;
}
And, I am trying to check the database (without refreshing the page) and get the value on this page:
application.php
$amount_of_tickets = is_ticket_able($conn);
Then, I just check that $amount_of_tickets is not 0 or 1. Because if is one then some stuff have to change.
I am doing this (inside application.php):
if($amount_of_tickets !=0){
//show the form and let them apply for tickets.
//also
if($amount_of_tickets == 1){
//just let them apply for one ticket.
}
}
EDIT: I saw that AJAX would be the right one to use, but I am so confuse using it.
UPDATE:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
return $ticket;
}
application.php
$amount_of_tickets = is_ticket_able($conn);
<script type="text/javascript">
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
alert(global_isTicketAble);
if( global_isTicketAble == 0 ){
window.location.replace("http://www.google.com");
}
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
});
}
</script>
So, now the problem is that when I alert(global_isTicketAble); it doesn't alert the value from the database but it does alert everything that is inside application.php...Help plzzz
Server side
Assuming you need to check $amount_of_tickets periodically and this can be computed into application.php, inside that file you'll have
<?php
// $conn is defined and set somewhere
$amount_of_tickets = is_ticket_able($conn);
echo $amount_of_tickets;
exit(0);
?>
This way when the script is invoked with a simple GET request the value is returned in the response as simple text.
Client Side
ajax is the way to go if you want to update information on page without reloading it.
Below is just a simple example (using jQuery) that may be extended to fit your needs.
The code below is a JavaScript snippet. A global is used to store the value (globals should be avoided but it's just for the purpose of the example)
Then a function is invoked and the updated value is fetched from function.php script.
The function -prior termination- schedules itself (with setTimeout) to be re-invoked after a given amount of milliseconds (to repeat the fetch value process).
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
// eventually do something here
// with the value just fetched
// (ex. update the data displayed)
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
}
}
Note that $.ajax() sends the request but does not wait for the response (as async is set to true). When the request is received the function specified as success is executed.
Complete jQuery ajax function documentation can be found here
http://api.jquery.com/jquery.ajax/
I assume that you have a page (application.php) that displays a table somewhere.
And that you wish to fill that table with the data found in you database.
I'm not sure about WHEN you want these data to be refreshed.
On button click or periodically (like ervery 5 seconds)... But it doesn't matter for what I explain below.
In application.php:
Assemble all your page as you already know how.
But inside it, somewere, just insert an empty div where your table should show:
<div id="dynamicContent"></div>
Also add this script at the bottom of the page:
<script>
function getData(){
PostData="";
$.ajax({
type: "POST",
url: "function.php",
data: PostData,
cache: true,
success: function(html){
$(Destination).html(html);
}
});
}
getData(); // Trigger it on first page load !
</script>
There is 2 variables here... I named it "PostData" and "Destination".
About PostData:
You can pass data collected on the client side to your PHP function if needed.
Suppose you'd need to pass your user's first and last name, You'd define PostData like this:
Fname=$("#Fname").val(); // user inputs
Lname=$("#Lname").val();
PostData="Fname="+Fname+"&Lname="+Lname;
In your function.php, you will retreive it like this (like any normal POST data):
$Fname=$_POST['Fname'];
$Lname=$_POST['Lname'];
If you do not need to pass data from your client side script to you server side PHP... Just define it empty.
PostData="";
Then, about Destination:
This is the place for the empty "dynamic div" id ( I named it "dynamicContent" above).
Don't forget about the hashtag (#) for an id or the dot for a class.
This is a jQuery selector.
So here, PostData would be defined like this:
Destination="#dynamicContent";
The result of the ajax request will land into that "dynamic div".
This WILL be the result of what's defined in function.php..
So, if you follow me, you have to build your table in function.php...
I mean the part where you do your database query and your while fetch.
echo "<table>";
echo "<tr><th>column title 1</th><th>column title 2</th></tr>"
while ($row = sqlsrv_fetch_array($stmt)){
echo "<tr><td>" . $row['data1'] . "</td><td>" . $row['data2'] . "</td></tr>";
}
echo "</table>";
So if you have no data, the table will be empty.
You'll only get the table and table headers... But no row.
There is then no need for a function that checks if there is data or not.
Finally... About the trigger to refresh:
In application.php, you may place a button that fires getData()... Or you may define a setInterval.
It's up to you.
This is how I use ajax to refresh part of a page without reloading it completly.
Since ajax is new to you, I hope this answer will help.
;)
------------------------
EDIT based on Ariel's comment (2016-05-01)
Okay, I understand! Try this:
In application.php:
<div id="dynamicDiv"></div>
<script type="text/javascript">
// timer to trigger the function every seconds
var checkInterval = setInterval(function(){
checkTicket();
},1000);
function checkTicket(){
$.ajax({
type: "POST",
url: "function.php",
data: "",
cache: true,
success: function(html){
$("#dynamicDiv").html(html);
}
});
}
function noMoreTikets(){
clearInterval(checkInterval);
window.location.replace("http://www.google.com");
}
</script>
In function.php:
// Remove the "function is_ticket_able($conn){" function wrapper.
// Define $conn... Or include the file where it is defined.
// I assume that your query lookup works.
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
// Add this instead of a return.
if($ticket>0){
echo "There is still some tickets!"; // Text that will show in "dynamicDiv"
}else{
?>
<script>
$(document).ready(function(){
noMoreTikets();
});
</script>
<?php
}
Remember that your PHP scripts are executed server-side.
That is why your "return $ticket;" wasn't doing anything.
In this ajax way to call function.php, its script is executed alone, like a single page, without any relation with application.php, which was executed long ago.
It produces text (or javascript) to be served to the client.
If you want to pass a PHP variable to the client-side javascript, you have to echo it as javascript.
So here, if the PHP variable $ticket is more than zero, some text saying that there is still tickets available will show in "dynamicDiv" and the application page will not be refreshed. I suppose it shows a button or something that allows students to get a ticket.
Else, it will be the javascript trigger to "noMoreTikets()" that will land in the "dynamicDiv".

How to get data from AJAX in PHP without using a function

NOTE: No more down-votes please, just because you cannot answer the question/ or cannot understand the problem doesn't mean you have to down-vote. I clearly said I can provide more information/be more specific if you need me too.
Edited title for clarification
I am using javascript to validate the form client side, then using ajax to pass 3 arrays worth of data to a separate PHP page for processing. Just trying to perform a basic query with one of arrays before i begin.
the ajax request says it's working, and when I go into the network tab, then click response, it shows all the arrays with the correct values/indexes.
But on the PHP side nothing is happening. I have no idea how to debug the PHP because it's on a different page. I'm assuming this has something to do with my syntax, as I have got this too work before, but i used ajax in a function. I am very new to ajax, so I am not too sure if I am doing this correctly. I have tried a valid $wpdb query on the page and nothing is happening. How do i properly structure my PHP page to work with the ajax? Any way I can debug my PHP when ajax fires?
If you need additional information please let me know.
AJAX CALL:
$.ajax({
type: "POST",
url: "?page_id=251",
data: { vData: videoData, tsData: tsValues, dData: tsDescriptions},
success: function(){
$("#errorMessage").text("ajax success.");
}});
?page_id=251 (PHP page)
<?php
$videoData = $_POST['vData']; // i have also tried $_GET['vData'];
$vSRC = $videoData[0];$vTIT = $videoData[1];$vDES = $videoData[2];$vPDF = $videoData[3];$vDAT = $videoData[4];
$uID = get_current_user_id();
global $wpdb;
$wpdb->insert( $wpdb->prefix."uservideo", array(
"user_id" => $uID,
"video_src" => $vSRC,
"video_title" => $vTIT,
"video_description" => $vDES,
"pdf_file" => $vPDF,
"video_date" => $vDAT
));
?>
I found the solution to the issue.
I needed to call a function with the ajax, cannot just call a page. I'm sure you can just call the page but no one knows how apparently.
AJAX
<script type="text/javascript">
function insert_data(vidData,timesData,descData){
$.ajax({
url: '?page_id=251',
type: 'POST',
data: {action: 'insert_video', vData: vidData, tsData: timesData, dData: descData },
dataType: 'json',
success: function(response){
alert('dhsdhjsdjhsjhdjhsd');
}
});
}
</script>
PHP
<?php
function insert_video($videoData,$tsValue,$tsDesc){
$videoData = $_POST['vData'];
$vSRC = $videoData[0];$vTIT = $videoData[1];$vDES = $videoData[2];$vPDF = $videoData[3];$vDAT = $videoData[4];
$tsValue = $_POST['tsData'];
$tsDesc = $_POST['dData'];
$uID = get_current_user_id();
global $wpdb;
$wpdb->insert( $wpdb->prefix."uservideo", array(
"user_id" => $uID,
"video_src" => $vSRC,
"video_title" => $vTIT,
"video_description" => $vDES,
"pdf_file" => $vPDF,
"video_date" => $vDAT
));
}
echo insert_video($_POST['vData'], $_POST['tsData'], $_POST['dData']);
?>

Calling a php function from Javascript and using a javascript var in the php code

JavaScript
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "/test.php",
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Php
<?php
$content = $_POST['prime'];
$fn = "content.txt";
$content = stripslashes('prime'"\n");
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
?>
So this is all the relevant scripting I think. I have a script that can get prime numbers and it works perfectly. But now I want to record these numbers on a text file. This is how I am trying to do it but I am having no success at all. Thank you. The issue is the numbers aren't being recorded.
I added an alert the Ajax is working. But when I add a form to the php script and submit it that works. So the ajax and php scripts are not working together as such.
You should read up about AJAX and see how you can pass information to a serverside page using Javascript and retrieve the return value.
http://www.w3schools.com/ajax/default.asp
https://www.youtube.com/watch?v=qqRiDlm-SnY
With ajax and jQuery it is actually simple.
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "myScript.php", // URL of your php script
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
alert("success");
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
myScript.php :
<?php
$content = $_POST['prime'];
...
You should definately look for Asynchronous JavaScript and XML.
You can choose between using AJAX with a Javascript function, or simplify your life with jQuery
Here is a sample:
//STEP ONE: INCLUDE THE LAST VERSION OF JQUERY
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
//STEP TWO, GET YOUR FUNCTION TO WORK:
function sendVariableTo(variable,url) {
$.ajax({
url:url, //Or whatever.php
type: "GET", //OR POST
data: { myVar: variable}, //On php page, get it like $_REQUEST['myVar'];
success:function(result){
//If the request was ok, then...
alert(result) //Result variable is the php page
//output (If you echo "hello" this alert would give you hello..)
},
});
}
Hope this helped, bye !

Update mysql data on textarea click off

I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/

Categories

Resources