Form with AJAX always returns 0 - php

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/

Related

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

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!

Ajax doesn't call server side function when jquery handler is fired

I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/

Save to database without a form using jQuery and PHP

I'm trying to save some data to a database without the use of an html form and was wondering if anyone could help me as I'm no expert in PHP. So far I have got:
JQuery
$('.summary').on('click', '#btn_save', function () {
var summary_weight = $('#summary_weight').text();
var summary_bmi = $('#summary_bmi').text();
var summary_consumed = $('#summary_consumed').text();
var summary_burned = $('#summary_burned').text();
var summary_total = $('#summary_total').text();
var user_id = $('#user_id').text();
//All values stored correctly
$.ajax({
type: "POST",
url: "save.php",
data: //Data to send,
success: function () {
$('.success_message').html("success");
}
});
});
There is no issue at the first stage as all my values are stored in the variables correctly. I just don't know in what format to send them across to save.php.
save.php
<?php
require_once 'dbconfig.php';
//Connects to database
if($_POST)
{
//Not sure what to post here
$current_date = date('Y-m-d');
try{
$stmt = $db_con->prepare("INSERT INTO entry(user_id, date, weight, bmi, calories_consumed, calories_burned, calorific_deficit) VALUES(:user, :date, :weight, :bmi, :consumed, :burned, :deficit)");
$stmt->bindParam(":user", $user_id);
$stmt->bindParam(":date", $current_date);
$stmt->bindParam(":weight", $summary_weight);
$stmt->bindParam(":bmi", $summary_bmi);
$stmt->bindParam(":consumed", $summary_consumed);
$stmt->bindParam(":burned", $summary_burned);
$stmt->bindParam(":deficit", $summary_total);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
I'm not sure how to post this data to save.php and then how to process it to be sent to the database. I've also added a variable of current_date to send the current date to a field in the database.
Can anyone help me and fill in the blanks? Or maybe I'm going about this the wrong way?
Send your data in an object, like so:
// Declare data as an empty object
var data = {};
// Assemble the properties of the data object
data.summary_weight = $('#summary_weight').text();
data.summary_bmi = $('#summary_bmi').text();
data.summary_consumed = $('#summary_consumed').text();
data.summary_burned = $('#summary_burned').text();
data.summary_total = $('#summary_total').text();
data.user_id = $('#user_id').text();
$.ajax({
type: "POST",
url: "save.php",
// pass the data object in to the data property here
data: data,
success: function () {
$('.success_message').html("success");
}
});
Then, on the server side, you can access directly via $_POST superglobal:
$summary_weight = $_POST['summary_weight'];
$summary_bmi = $_POST['summary_bmi'];
// etc...
You can send all this data in the data parameter as given below:
$('.summary').on('click', '#btn_save', function () {
var summary_weight = $('#summary_weight').text();
var summary_bmi = $('#summary_bmi').text();
var summary_consumed = $('#summary_consumed').text();
var summary_burned = $('#summary_burned').text();
var summary_total = $('#summary_total').text();
var user_id = $('#user_id').text();
//All values stored correctly
$.ajax({
type: "POST",
url: "save.php",
data: {summary_weight: summary_weight, summary_bmi:summary_bmi, summary_consumed:summary_consumed, summary_burned: summary_burned, summary_total:summary_total, user_id:user_id },
success: function () {
$('.success_message').html("success");
}
});
});
And the, process it in save.php like this
$summary_weight = $_POST['summary_weight'];
and use it in the query to save it in database.

AJAX subscription form not working

I'm working on a subscription form. It takes a users email, on click it should check if the email is in the database, if it is return false, if not it should add it and then return true.
I'd like all this done using ajax to improver user experience.
The function no longer seems to be getting called, I'm very new to AJAX so not sure where the problem might be. Any help appreciated.
HTML:
<section>
<h4>Stay Updated</h4>
<p>Sign up for our newsletter. We won't share your email address.</p>
<form name="newsletterForm" id="newsletterForm" action="" method="post">
<div class="input-append row-fluid">
<input type="email" placeholder="Email Address" class="span6" name="newsletterEmail" id="newsletterEmail"/>
<input type="submit" id="newsletterSubmit" name="newsletterSubmit" value="newsletterSubmit" onclick="newsletterSignup(); return false">
<p id="status"></p>
</div>
<!--close input-append-->
</form>
</section>
PHP:
Ive removed the test to chec if the email is present to simplify things.
<?php require(dirname(__FILE__).'../core/init.php');
if($_POST){
$email = $_POST['newsletterEmail'];
if($newsletter->addEmail($email) == true){
$data['message'] = "Signed up";
$data['success'] = true;
}
echo json_encode($data);
}
the php function:
public function addEmail($email){
$query = $this->db->prepare("INSERT INTO `newsletter` (`email`, `signupDate`)
VALUES (?, ?)");
$mysqltime = date ("Y-m-d H:i:s", time());
$query->bindValue(1, $email);
$query->bindValue(2, $mysqltime);
try{
$query->execute();
return true;
}catch(PDOException $e){
die($e->getMessage());
}
}//end add email function
AJAX:
function newsletterSignup(){
var email = $('#newsletterEmail').val();
if(email == ""){
$('input#newsletterEmail').focus();
return false;
}
var params = {email: email};
var url = "newsletterSignup.php";
$.ajax({
type: 'POST',
url: url,
data: params,
dataType: 'json',
beforeSend: function(){
alert("ASD");
document.getElementById("status").innerHTML='<img src="sending.gif"/>sending...';
},
success: function(data){
alert("success");
if(data.success == true){
document.getElementById("status").innerHTML= '<p>Sent!</p>' ;
}else{
document.getElementById("status").innerHTML= '<p>Error!</p>' ;
}
},
error: function(error){
alert("Gets ERRORA");
console.log(error);
}
});
}
It's worth noting that the sign up form is in the footer which is an include. not sure if that's relevant or not.
EDIT: The alert in beforeSend is being shown so I know it's calling the function etc. The alert in error doesn't get called though. There are no XHR messages in the log.
three problems it seems
it couldn't find the php file
when it could it wasn't happy with my require statement at the top
then the POST variable wis named incorrectly.
Now working.

Ajax update table with php content

How to make an animated table only animate when a new record is added to the database.
Ajax/Js (in index.php):
$.ajax({
url : 'Not sure what goes here?',
data : {Not sure what goes here?},
dataType : 'application/json', // Is this correct?
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
var newitem = function(response){
var item = $('<div>')
.addClass('item')
.css('display','none')
.text(response)
.prependTo('#scroller')
.slideDown();
$('#scroller .item:last').animate({height:'0px'},function(){
$(this).remove();
});
}
My php (latest.php):
include ('db.php');
$sql2 = "SELECT * FROM `feed` ORDER BY `timez` DESC";
$res2 = mysql_query($sql2) or die(mysql_error());
while($row3 = mysql_fetch_assoc($res2)){
$user = $row3['username1'];
$action = $row3['action'];
$user2 = $row3['username2'];
echo ''.$user.''.$action.''.$user2.'<br>'; // Needs to be a json array?
I can't get this to work, here's how the table operates http://jsfiddle.net/8ND53/ Thanks.
$.ajax({
url : your_php_file.php',
data : {data you'r going to send to server}, // example: data: {input:yourdata}
success: function(response) {
$('#table_id').append('<tr>'+response+'</tr>'); // response is the date you just inserted into db
}
});
in your_php_file.php:
add the item into db
echo that inserted data # if you echo, then you can catch this with ajax success function then you append it into your table.
try to fill as below:
$.ajax({
type: "post"
url : 'locationOfphpCode/phpCode.php',
data : {data you want to pass}, //{name: "dan"}
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
in your php code you need to receive the data you have passed from the ajax call:
<?php
$name = $_POST['name'];
...
?>
you may add some validations in your php code.
hope this will help you.
the example you have given is using setInterval(newitem, 2000)
so you have to call ajax function on some fixed interval.

Categories