Sql not setting value on UPDATE - javascript

I've been trying to update my orders table in my database using ajax. It seems as though my sql is not executing or there may be a problem with my syntax, I have checked and verified that the id variable I am passing through has been passed using POST and it successfully alerts when called upon in the javascript. The problem I am having is that my table is not updating.
my php here
if(isset($_POST['completed_id']) === true) {
$comp_id = $_POST['completed_id'];
include 'http://trecoolable.koding.io/res/res_php/conn.php'; //connection successful
$sql = "UPDATE resorder_tb SET res_complete = 1 WHERE res_id =".$comp_id; //not updating, checked and names are correct
echo $comp_id; //shows when echoed into my msg in javascript
}
javascript
$("#compacc_but").click(function(){
var completed_id = record_id;
$.ajax({
url: "http://trecoolable.koding.io/res/res_php/getOrder.php",
type: "POST",
data: {completed_id:completed_id}, ///passing correct values
success: function(msg)
{
alert(msg); //alerting properly
}
});

Are you executing the $sql statement?

Just change this code like below-
$sql = "UPDATE resorder_tb SET res_complete = 1 WHERE res_id =".$comp_id." ";
mysql_qyery($sql);

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".

Unable to send jQuery variable with string content to PHP using jQuery AJAX function?

The code snippet for the jQuery function looks like:
function addMessage() {
if (textval != "") {
text_string='<div class="alert-box round"><p class="text-left">' + userName + ':' + textval + '</p></div></br>';
alert(text_string);
$.ajax({
type:"POST",
url:"process.php",
data: {'text_string': text_string},
cache:false,
success:function(){
alert("submitted")
}
});
$("input[type=text]:last").val("");
}
enterButton = 0;
}
The process.php code looks like:
<body>
<?php
//$host = "localhost";
$text_string=$_POST['text_string'];
echo "string submitted is".$text_string;
?>
</body>
I get alerts showing value of text_string and then the "submitted", but when I open the php page, it shows an error:
Undefined index: text_string
I've seen various answers, none of them seem to be the case for mine. Is the problem in PHP code or jQuery code or both?
If you want to save the value passed by the AJAX request for the next time you load "process.php", try saving it in the session. So, you could change your code to:
<?php
session_start();
// Store value in session if it is passed
if (isset($_POST['text_string'])){
$_SESSION['text_string'] = $_POST['text_string'];
}
// Read and echo value from session if it is set
else if (isset($_SESSION['text_string'])){
$text_string=$_SESSION['text_string'];
echo "string submitted is".$text_string;
}
?>
Now, your PHP script will store the passed value in the session, and will echo that stored value should you load the page elsewhere. (Another alternative is to store the value in a database...though I'm not sure if you have one set up at the moment.)
Hope this helps! Let me know if you have any questions.

Ajax call for a a url freezes browser

I have a function in view used to transfer a value from a text box to a table displayed on a page. Basically it updates the URL and goes into a function called update_verified_phone(). There is another function which is used to update the records using a model named user_info_model() and uses controller named users_info().
Problem is when when I use an AJAX function to post to the controller function named update_verified_phone(), the browser freezes and hangs up. I was wondering why it is happening?
Sorry just new to AJAX.
Here is the code :
$(document).ready(function()
{
$('#btnVerify').click(function(event)
{
event.preventDefault();
var uid = $('#user_id').val();
var verified_phone = $('#textNum').val();
if (isNaN(verified_phone))
{
alert("Please enter only numbers for user verified_phone");
}
else
{
$('#textNum').val('');
//$.post(base_url+'users_info/update_verified_phone', {uid:user_id,verified_phone:textNum}, function(response)
//{
$.ajax
({
type: "POST",
url:base_url+'users_info/update_verified_phone',
data: {uid:user_id,verified_phone:textNum},
//async: true,
dataType: 'json',
success:function(data)
{
if(data)
{
var headingHtml = headingTemplate
({
'verified_phone':data[0].verified_phone,
'verified_timestamp':data[0].verified_time
});
$('.userinfo').html(headingHtml);
$('.userinfo tr td:eq(4)').html(data[0].verified_phone);
$('.userinfo tr td:eq(5)').html(data[0].verified_time);
}
}
});
}
});
});
I think you missed to specify JS variable base_url correct it out. After that once you check your AJAX request URL response by direct hit from browser address bar and check what if issue is there OR not.
Let me know if you require any more information regarding this.
Thanks!
This is pretty difficult but I try to solve it.
Query 1: Insert query with SELECT statement
//If history_verified_phone:id is auto incremental then no need to cover it into INSERT statement so removed.
$instVerified = "INSERT INTO history_verified_phone(lastverified_phone,lastverified_time,verified_phone,verified_time)
SELECT users.verified_phone,users.verified_time,'". $textNum ."',NOW() FROM users WHERE id = '". $user_id ."'";
Query 2: Update query
$updtUser = "UPDATE users SET verified_phone = '" . $textNum . "', verified_time = NOW() WHERE id = '" . $user_id . "'";
Query 3: Select query
$selUser = "SELECT verified_phone,verified_time from users WHERE id = '" . $user_id . "'";
Please replace variable with your query, $instVerified for Query 1, $updtUser for Query 2 and $selUser for Query 3 and after that please check what happen. Because I have some doubt with your given query may failed and that is the reason for issue.
Please let me know what is outcomes here.

How to retrieve list of users from mysql in javascript

Hi I am adding dynamic validation to a form on my webpage to stop unnecessary page reloads. The form is for registring an account, and I want to be able to check if the username that the user selects is already taken, however as far as I know I can only retrieve data from mysql in php. How should I go about this?
Use PHP to load a list of existing users into an array when the registration page loads and then use that array to do the Javascript validation.
you can using ajax.
this is function in php:
function check_registration() {
if ($_POST['val']) {
$query = "select user from member where user = '" . $_POST['val'] . "'";
$row = $this->countRow($query);
if ($row > 0) {
echo "user has been taken";
}
}
}
and this is ajax that u can put in html
<script>
$(document).ready(function(){
$('#input1').keyup(function(){
var values = $('#input1').val();
var dataString = 'val='+ values;
$.ajax
({
type: "POST",
url: "http://localhost/authentication/check",
data: dataString,
cache: false,
success: function(html)
{
$("#error1").html(html);
}
});
});
});
</script>

Categories

Resources