AJAX Call issues - no data passing (relatively inexperienced here!) - php

I assume i am doing something really simply wrong here (to all you seasoned programmers), but forgive me i have spent hours and hours reading trying to understand how AJAX calls work...
My variables aren't making it to recordsale.php to be inserted into SQL table.
The javascript variables are displayed on the HTML page, so i know they contain data.
Can anyone offer some advice?
(any response knocking my ability will not be appreciated - I AM TRYING :) )
My form submit button in html looks like this
<form action="recordsale.php" method="post">
<input type="image" src="assets/CompleteSale.png" alt="Submit"> </form>
My AJAX Post Function:
$( "#submit" ).submit(function( event ) {
alert("hello");
// Jquery code for making AJAX call to server side script
$.ajax({
method: "POST",
url: "recordsale.php",
data: { adultqty: adultticketqty, concessionqty: concessionticketqty, studentqty: studentticketqty, childqty: childticketqty, programqty: programqty, totalsell: totalsaleprice }
})
//alert(adultqty + childqty)
});
Recordsale.php
<?php
$adultticketqty = $_POST['adultqty'];
$concessionticketqty = $_POST['concessionqty'];
$studentticketqty = $_POST['studentqty'];
$childticketqty = $_POST['childqty'];
$programqty = $_POST['programqty'];
$totalsaleprice = $_POST['totalsell'];
//include('phpsqlget.php');
/* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "speedway", "speedwayticketsales");
// Check connection
if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt insert query execution
$sql = "INSERT INTO stdsalesrecords (qtyadulttickets, qtyconcessiontickets, qtystudenttickets, qtychildtickets, qtyprograms, totalsell) VALUES ($adultticketqty,$concessionticketqty,$studentticketqty,$childticketqty,$programqty,$totalsaleprice)";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully."; }
else{ echo "ERROR: Could not able to execute $sql. "
. mysqli_error($link); } // Close connection mysqli_close($link);
?>

This is how i usually do my ajax submissions. there are other ways of handling form submission.
Check out $(form).serialize() amongst others.
$( "#submit" ).submit(function( event ) {
var adultticketcty = $('selector').val();
//continue filling out the fields and mirror them in the below dataString.
var dataString = 'adultqty='+adultticketcty+'&concessionqty='+concessionticketqty;
//Check if you set the correct values in the datastring.
console.log(dataString);
$.ajax({
type: "POST",
url: "recordsale.php",
data: dataString,
success: function(data){
//check whatever is returned from recordsale.php
console.log(data);
}
});
});
then in your recordsale.php do this to see if anything is returned in your ajax success call:
$adultticketqty = $_POST['adultqty'];
$concessionticketqty = $_POST['concessionqty'];
echo $adultticketqty;
Not related to the question, but i wanna recommend checking out pdo queries to prevent sql injections etc.

solved my issue
had to write a function to write my JS Variables into hidden elements in the form
function save()
document.getElementById("qty").value = Aqty;
then add the hidden elements to my form
<form method="post" name="submit" id="submit" action="record.php" >
<input type="hidden" id="qty" name="qty" value="" >
<input type="submit" value="Submit" onclick="save();">
works a treat!

Related

Form with AJAX always returns 0

So I'm trying to send information from an AJAX call in a form to a table in SQL. This is the form:
<form name="likedGames" method="post" id="likeForm" action="like.php">
<input type="text" name="liked" id="likeInput" value="123"/><button type="submit" id="likeButton"><i id="like" class="fa-solid fa-heart"></i></button>
</form>
This is the AJAX call:
$(document).ready(function () {
$("#likeForm").submit(function (event) {
var liked = $("#likeInput").val();
$.ajax({
type: "POST",
url: "like.php",
data: liked,
}).done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
And this is like.php:
<?php
$started = session_start();
$conn = new mysqli('localhost','root','password','mydb');
if(!$conn){
die("Connection Failed: ".mysqli_connect_error());
}
$userId = $_SESSION['userId'];
// $like = $_POST['liked'];
$like = isset($_POST["liked"] ) ? $_POST["liked"]: '';
$stmt = $conn->prepare("INSERT INTO likes(user_id, gameId) VALUES (?,?)");
$stmt->bind_param("ss", $userId, $like);
$execval = $stmt->execute();
$stmt->close();
$conn->close();
?>
As you might see, there is a commented line in like.php, because that was my first attempt to retrieve the info from the liked input, but it didn't work.
What happens right now when a user clicks into the submit button is that the database gets indeed updated, but the gameId column always gets 0 as the value. Shouldn't it get 123 (or whatever the user types in the input)? I'm quite lost at the moment, so any help will be highly appreciated. Also, if there is anything I can do to improve the post, just let me know. Thank you!
I guess, your ajax-call should look like this:
$.ajax({
type: "POST",
url: "like.php",
data: {liked : liked},
}).done(...)
See: https://api.jquery.com/jquery.ajax/

AngularJS form data not stored in MySQL db

In my AngularJS app, the data entered into the form are not stored in the MySQL database after hitting the submit button. An alert after successful form data submit however indicates that it is working.
Also, after hitting the submit button, I want the app to proceed to the next view (#/setup-step2) - however it remains at step1.
html partial (#/setup-step1):
<form ng-submit="submitForm1()">
Job title: <input type="text" name="jobtitle" ng-model="formData1.jobtitle">
Vacancy ID: <input type="text" name="vacancyid" ng-model="formData1.vacancyid">
<button type="submit" class="animatedbutton"> Proceed </button>
</form>
controller.js:
var ctr = angular.module('myApp.controller', []);
ctr.controller
('Step1Controller', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http){
$scope.formData1 = {};
$scope.submitForm1 = function() {
$http({
method: 'POST',
url: 'php/setup-step1.php',
data: $.param($scope.formData1),
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
console.log(data);
alert("It worked");
})
.error(function(data) {
console.log(data);
alert("It didn't work");
})
}
}]);
setup-step1.php in folder /php:
<?php
include_once('db.php');
// Check connection
if(mysqli_connect_errno())
{echo '<p>Connection to MySQL server failed: '.mysqli_connect_error().'</p>';}
else
{echo '<p>Connection to MySQL server successful.</p>';}
$_POST = json_decode(file_get_contents("php://input"), true);
if (empty($_POST['jobtitle']))
{$errors['jobtitle'] = 'Job title is required.';}
else {
// Escape user inputs for security
$jobtitle = $_POST['jobtitle'];
$vacancyid = $_POST['vacancyid'];
$data = "INSERT INTO campaign (Job_title, Job_id) VALUES ('$jobtitle','$vacancyid')";mysql_query("INSERT INTO campaign (Job_title, Job_id) VALUES ('$jobtitle', '$vacancyid')");}
if ($connect->query($data) === TRUE)
{$conn->close();}
else
{echo "Error: " . $sql . "<br>" . $conn->error;}
exit();
?>
First,
Be sure that you enable the cors before performing any request to the server.When you are working with angularjs this usually means that you are making cors requests to the server.If you didn't enable cors option you cannot call any method from the server since it is not allowed.
Second,
just keep php code inside your setup-step1.php.You don't need any html code there since it will return result of your requet only.
Third,
As I know you cannot change location of the webpage from erver because server domin and website domains are different.You need to redirect the user to another page in angularjs. You can find the ways of redirecting in angularjs by using $location or $state.
I found the answer myself. The problem was incorrect php and mysql syntax. Updated the code the way it works now.

How to update values in my DB with values from <select> tags - (Not $_POST)

I want to take values from <select> or <input> tags but using function onclick button, not using $_POST. I did a try but I have stack on syntax. In case of $_POST goes like this:
The button in to my form:
<input class="" name="submit" type="submit" value="UPDATE" />
My update query:
if (isset($_POST['submit']) or isset($_GET['submit'])){
$db =& JFactory::getDBO();
$query = "UPDATE table
SET name = '".$_POST["name"]."',
lastname = '".$_POST["lastname"]."',
rank = '".$_POST["rank"]."'
WHERE id=1";
$db->setQuery($query);
$db->query();}
Now I am trying to do something like this:
The button in to my form:
<input class="" name="submit" type="submit" value="UPDATE" onclick="update()" />
My update query:
function update(){
$db =& JFactory::getDBO();
$query = "UPDATE table
SET name = ???,
lastname = ???,
rank = ???
WHERE id=1";
$db->setQuery($query);
$db->query();}
But what is the syntax to call <select> and <input> tags names? Or their values in other words.
You're confusing the code that runs on the client-side (JS) with the code that runs on the server-side (PHP). JS runs after the PHP finished - so you can't "call" from JS to functions in PHP unless you submit a form (POST/GET) or use AJAX.
TYou must use $.ajax if you want to do this just by clicking a button and not refreshing or redirecting your browser
1) Read about http://api.jquery.com/jQuery.ajax/
2) add an eventhandler on your button onclick="update();"
3) create an ajax thingy like:
function request(variable1,variable2,variable3){
var request = $.ajax({
url: "/server.php", // The address of you php script that will handle the request
type: "POST", // Method type GET / POST in this case POST (Similar to form submission methods....)
data: { // What you send to the server 'VariableName' : VariableValue, in this case you assign the varaiables that were passed to the request function.
'var1': variable1,
'var2' : variable2,
'var3': variable3
},
dataType: "json" // The response type you expect from the server
})
request.done(function(msg) // Function being called when everything is ok and server sends back data
{
console.log(msg) // handle the reply / data
})
request.fail(function(jqXHR, textStatus) // Something went wrong...
{
console.log(textStatus); // See the error report
console.log(jqXHR);
})
request.complete(function(){
console.log("Ajax request complete!"); // This will always be executed when a request has completed even if it failed. (Executes after .done and .fail)
})
}
So you cound do this inside your update function that is being called whenever you click the button:
function update()
{
var val1 = $.('#selectbox').val();
var val2 = $.('#inputbox').val();
var val3 = $.('#textarea').val();
new request(val1,val2,val3);
}
The request / variables will be sent using the POST method so in you php script
you may process them as you would do with a form
if(isset($_POST['var1']) && isset($_POST['var2']) && isset($_POST['var3']))
{
$serverReply = doThings($_POST['var1'],$_POST['var2'],$_POST['var3']);
//and this is how you reply to your client/browser in json format
echo json_encode($serverReply);
}
Make sure to Check more in Depth tutorials regarding ajax comunication.
There are plenty around on the net.
onclick called function javascript
function javascript implements with ajax
example:
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});

ajax call to check duplicate data

Here is the form to have ajax check out user existence.
<!DOCTYPE html>
<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.fail(function()
{
$('#user').html("This user already exists");
}
);
}
</script>
</html>
And here is the userexists.php module
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username=$_POST('username');
$sql="SELECT username FROM ".TABLENAME." WHERE username=".$username;
$query=mysql_query($sql);
if(0!=mysql_numrows($query))
{
//
}
else
{
}
?>
But I am stuck to really figure out how the ajax function actually works, what should I enter the blank field after I know that the entered username has been used, for example ? I don't understand ajax at all.
[UPDATE]
Thank you, I understand it now, I have got several answers, don't know which one to choose as the best reply. No option to choose all.
You have a lot of mistakes in your code, try codes below:
<!DOCTYPE html>
<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax({
type: "POST",
data: {
username: $('#username').val(),
},
url: "userexists.php",
success: function(data)
{
if(data === 'USER_EXISTS')
{
$('#user')
.css('color', 'red')
.html("This user already exists!");
}
else if(data === 'USER_AVAILABLE')
{
$('#user')
.css('color', 'green')
.html("User available.");
}
}
})
}
</script>
</html>
And for your php code:
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username = mysql_real_escape_string($_POST['username']); // $_POST is an array (not a function)
// mysql_real_escape_string is to prevent sql injection
$sql = "SELECT username FROM ".TABLENAME." WHERE username='".$username."'"; // Username must enclosed in two quotations
$query = mysql_query($sql);
if(mysql_num_rows($query) == 0)
{
echo('USER_AVAILABLE');
}
else
{
echo('USER_EXISTS');
}
?>
Since you're new to AJAX, let me try and help you a bit better with some explanations as we go.
AJAX stands for Asynchronous Javascript And XML. Using it, you can make a request to another page and have your original page behave differently according to the results returned by the other page.
So how is this useful? Well; You could set an onblur even on a 'username' field to check a remote script to see if a username is already in use. (Which you are already doing in your current setup. Good work!)
Firstly; the .fail() is telling your current page "If the ajax request fails, lets do this code". This is called a callback. A callback is a function of javascript code to execute when the asynchronous request is finished.
So what you want to actually do is use the .done() method. This tells your jQuery request "Hey, when you're done doing this request, do this chunk of code. While you're doing that, im going to sit here and handle anything else that happens".
So you can see there is a slight difference between using .done() and .fail(), however I can see how you can be easily confused with .fail() being new to ajax.
So lets get back to your current problem. Lets modify the ajax to something more like this:
$("#submit").click(function()
{
$.ajax({
type: "POST",
data: "username="+$("#username").val(),
url: "userexists.php"
})
.done(function(response){
$('#user').html(response);
});
});
What this does is bind an onclick handler for your submit button with the id "submit". So now you can remove onclick="register_user". Secondly, it says, "Hey webpage, go send userexists.php the username textbox value with the parameter name username. When you've finished that request, set the html of #user to the response.
So off it goes and does it.
Now your PHP file, you can do:
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn = mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username = mysql_real_escape_string($_POST['username']); // Stop some MySQL injections
$sql="SELECT username FROM ".TABLENAME." WHERE username='$username'";
$query=mysql_query($sql);
if(mysql_numrows($query) == 0)
{
echo 'Username is available!'
}
else
{
echo 'Sorry, username is in use.';
}
?>
So once your script does its query, if it finds a result it will say in the HTML div "Username is available!". Otherwise, if it finds a match, it says "Sorry, username is unavailable".
Hope this helps you understand ajax a little better!
It's technically up to you. (For example) You could return a "1" for "user exists" and "0" for "user doesn't exist", or return a more detailed XML. The client app (Javascript) will read the returned result and print out an appropriate message to the user.
The .fail method should be used in case your function actually fails (server side error etc). So it doesn't seem appropriate for what you're trying to do. I would put in your ".done()" code a test of the returned values as described above and print out the correct message.
Javascript:
.done(function ( data ) {
if(data == "0")
alert("Your username is OK");
else
alert("Your username is already used");
});
PHP:
if(0!=mysql_numrows($query))
{
echo "0";
}
else
{
echo "1";
}
Function .fail in ajax is used when server return unexpected datas. But your php code dont return anything. Use something like this:
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.done(function(_return)
{
if(_return)
{
if(_return['status']=='yes')
{
$('#user').html(_return['msg']);
}
}
})
.fail(function());
}
And in php:
if(0!=mysql_numrows($query))
{
$return = array('status'=>'yes',
'msg'=>"User alredy exist");
echo json_encode($return);
return true;
}
Now you can add more conditions with many statuses and parse it in javascript.

Problems with PHP SQL HTML & AJAX submission

So I have yet another problem,
I am trying to get an AJAX script to work, but upon click the page will reload but fail to UPDATE the database field.
The code im using I have working for other similar scripts on the site but for some reason this one, using the same code doesnt work, the code used follows below;
HTML code to send the call to AJAX:
<input onClick="read('<? echo $id; ?>')" id="read" name="read" type="checkbox" value="1" style="position:relative; top:2px; width: auto">
The code to confirm user selection and send onto a form handling file:
function read(ID) {
if(confirm('Are you sure you have read this carefully, you will not be alerted again "' + ID + '" ?')) {
$.get('http://<? echo ROOT . ADMIN . INCLUDES; ?>formHandling.php', { read: ID }, function(data) {
window.location.href = 'http://<? echo $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].""; ?>';
});
}
return false;
}
Lastly the code to handle the SQL query:
if (isset($_GET['read'])) {
// Pass the GET data and associate them to variables
$read = trim($_GET['read']);
$query = "UPDATE cms_motd SET read='$read' WHERE id='1'";
$result = mysql_query($query)or die("Database query died: " . mysql_error());
unset($_GET['readConfirm']);
}
Thanks in advance for all that help.
Regards,
Dan.
Don't you mean:
$query = "UPDATE cms_motd SET read='1' WHERE id='$read'";
Instead of:
$query = "UPDATE cms_motd SET read='$read' WHERE id='1'";
Edit:
I don't know if it is a copy&past error:
$result = mysql_query($query);or die("Database query died: " . mysql_error());
Needs to be:
$result = mysql_query($query) or die("Database query died: " . mysql_error());
I have some challenges with the fact that you do the query but don't give your code any feedback to continue. For example, what if the query fails? Do you just press on?
Here's how I handle these sort of Ajax transactions (yes, longhand!)
$('#read').click(function() {
$("#div").dialog({ //Shows dialog
height: 250,
width: 450,
modal: true,
buttons: {
"Cancel": function() {
$( this ).dialog( "close" );
},
"Save": function() {
$.ajax({
url: "url.php", //
timeout: 30000,
type: "POST",
data: $('#form').serialize(),
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown)
},
success: function(data){
$('#updatediv).html(data.stuff);
src="web/imgs/icons/24deleteB.png"></td>';
}
$( this ).dialog( "close" );
}
}
});
});
Now, the URL.php will do the query and return a json_encoded string back to the AJAX that will then be able to know if the transaction was succesful via the success/error functions. You could do additional conditioning on the success case to ensure that something was saved a particular way or that a result matched a case that you wanted it to before doing something. On success, I show just a simple .html inner html type action, but you could do any quantity or variety of things such as show/hide, inner html, etc. The choice is yours. Also, note that I use Jquery UI dialogs instead of system dialogs, so you'd need Jquery UI to make it look pretty if you used this verbatim. Finally, rather than onclick note that I'm using the .click functionality that Jquery provides, which is just a hair cleaner.

Categories