Ajax, retrieving ID of insert from within function - php

I'm trying to use Ajax to insert form data into the database and return the ID of that insertion.
It currently works as far as inserting (I can see it in the database) but I'm using alert to test that it's getting the ID of the insert and it simply says undefined.
Is there something I'm doing wrong to retrieve the ID?
<script type="text/javascript">
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#pageForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "addPage.php",
data: string,
cache: false,
success: function(result){
alert(result.id);//this will alert you the last_id
}
});
});
});
</script>
addPage.php
$title = $_POST['addTitle'];
$page_type = $_POST['pageType'];
$display_id = $_POST['displayId'];
$duration = $_POST['durationSet'];
$addpage = "
INSERT INTO pages (title, page_type_id, display_id, duration)
VALUES ('$title','$page_type','$display_id','$duration');
";
if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
echo json_encode(['id'=>$last_id]);
echo "New record created successfully" . $last_id;
} else {
echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}

Try to return last inserted data id
$title = $_POST['addTitle'];
$page_type = $_POST['pageType'];
$display_id = $_POST['displayId'];
$duration = $_POST['durationSet'];
$addpage = "
INSERT INTO pages (title, page_type_id, display_id, duration)
VALUES ('$title','$page_type','$display_id','$duration');
";
if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
$data = json_encode(['id'=>$last_id]);
echo "New record created successfully" . $data ;
} else {
echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}

https://www.w3schools.com/PHP/php_mysql_insert_lastid.asp
Please first search before ask a question
if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
echo "New record created successfully" . $last_id;
} else {
echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}

Related

AJAX and PHP code not working

I am sending my form data through AJAX but for some reason my PHP script is not running. The test echo's Im using in my PHP script is not showing. The window.alert("success") does show but HIDE and SHOW form1 and form2 also does not work.
Here is the code:
$('#mainform').on('submit', function(event) {
//test for empty fields
//test for Bots
//insert data into DB
//pass t_code on to next form
//create a page number for tabs
event.preventDefault(); //stops form on submit
var a = document.forms["mainform"]["hidden"].value;
if (a === ""){
var formData = {};
$.each($("#mainform").serializeArray(), function (i, field) {
formData[field.name] = field.value;
});
$.ajax({
url: 'insert_tut_description.php',
data: formData,
method:'POST',
success: function(response) {
window.alert("success");
pnum = 1;
t_code = form.elements["t_code"].value;
$("#form1").hide();
$("#form2").show();
document.getElementById("pnum").innerHTML = pnum;
}
});
};
});
<?php
echo "php running";
require 'config/config.php';
$t_title = $conn->real_escape_string($_POST['t_title']);
$t_code = $conn->real_escape_string($_POST['t_code']);
$t_image = $conn->real_escape_string($_POST['t_image']);
$hidden = $conn->real_escape_string($_POST['hidden']);
$t_desc = $conn->real_escape_string($_POST['t_desc']);
$t_url = "something.php";
echo $t_title;
echo t_url;
if(empty($hidden)){
echo "hidden is empty";
$query = "INSERT into tutorial_list (title, description, t_code, t_url, image,) VALUES('" . $t_title . "','" . $t_desc . "','" . $t_code . "','" . $t_url . "','" . $t_image . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
} else {
$conn->close();
}
}
?>

Error with PHP validation

I am creating a basic auction site and got quite far with help from this community. I am near finishing this now but having a slight issue with server side validation.
Auctions are listed on a PHP page with html and PHP, PHP runs a MySQL query and then lists the results. Example here:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction" . $row['ID'] . "'>
<input type='hidden' name='id' value='" . $row['ID'] . "' />
<div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £<div class='nospace' id='" . $row['ID'] . "'>" . $row['CurrentBid'] . "</div></div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname' autocomplete='off'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid' autocomplete='off'/></div>";
echo "<div class='auction-bid'><input type='submit' name='submit' value='Place Bid!' /></div>";
echo "<div class='bid-success' id='bid" . $row['ID'] . "'>Bid placed!</div>";
echo "</div></form>";
}
echo "</table>";
mysqli_close($con);
Once the user clicks the submit button, the following jQuery is executed:
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).find('input[name="bid"]').val();
var currentbid = $('#'+id).text();
var itemdesc = $(this).find('.auction-name').text();
bid = parseFloat(parseFloat(bid).toFixed(2));
currentbid = parseFloat(parseFloat(currentbid).toFixed(2));
if (bidname == '')
{
alert("No name!")
return false;
}
/* if (bid > currentbid)
{
alert("Bid is greater than current bid");
}
else
{
alert("Bid is too low!");
return false;
}*/
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
success: function(data){
$('#bid'+id).fadeIn('slow', function () {
$(this).delay(1500).fadeOut('slow');
});
//$('#auction' + id).find('.nospace').html(currentbid);
},
error: function() {
alert("bid too low");
}
});
return false;
});
});
If the code POSTS, the following PHP code is run on the handler page:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$itemdesc = $_POST['itemdesc'];
$highestbid = mysqli_fetch_row(mysqli_query($con,"SELECT CurrentBid from Auction WHERE ID = '$id'"));
if ($bid <= $highestbid)
{
$_SESSION['errors']['bid'] = 'Sorry, but the bid is too low';
echo json_encode($_SESSION['errors']);
exit;
}
else
{
$query = "UPDATE auction SET CurrentBid = '$bid', Bidder = '$bidname' WHERE ID = '$id'";
$query2 = "INSERT INTO auction_log (Item, Bid, Bidder) VALUES ('$itemdesc','$bid','$bidname')";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_query($con, $query2) or die(mysqli_error());
mysqli_close($con);
I added some server side validation to make sure that the bid posted is higher than what is currently in the MySQL table.
The problem I am having is that I get the "Sorry, but the bid is too low" error no matter what bid I put in.
If I put a bid higher than the current bid, I get the error, if I put a bid in lower, I get the error.
Both ways I go about it also trigger the success section of the AJAX.
I feel like I'm missing something very simple, so if anyone could help that would be great.
I am not sure why it's being downvoted, I am just looking for some help.
Thanks
The way that you're handling AJAX error is not very good because it only alerts you that you have an error, but you don't know what goes wrong.
In the AJAX object, replace the current error callback with one that logs the actual error to the console:
replace
error: function() {
alert("bid too low");
}
with
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
and you'll know for sure what is the error

ajax success doesnt alert anything

I have an AJAX request and if get id succeeds I would like to alert the data.
If I print_r my PHP function I get the correct result.
My ajax:
$.ajax({
type: "GET",
url: "getQuestions.php",
datatype: "json",
data:{
compid: id[4].innerHTML
},
success: function(response){
alert(response);
}
});
My getQuestions.php:
<?php
include "functions.php";
getQuestions($_GET['compid']);
My function getQuestions($compid) in functions.php:
function getQuestions($compid){
$int=intval($compid);
$vastus=array();
$conn = dbconnect();
$sql="SELECT * FROM bet_question WHERE compid = $int";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
return json_encode($vastus);
}
If I do print_r(getQuestions("some valid id")) in getQuestion.php I get valid result and if I do var_dump($_GET['compid']) in getQuestion I'll get the correct id from ajax request.
If I check if the request is sent using inspect elements I get that request is sent with correct params, but the response is empty.
Instead of return you need to use echo and it should be updated as
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
echo json_encode($vastus);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
exit;
You don't have to return the data, use echo instead, and set content type:
function getQuestions( $compid ) {
$int=intval($compid);
$vastus=array();
$conn = dbconnect();
$sql="SELECT * FROM bet_question WHERE compid = $int";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
#header( 'Content-Type: application/json' );
echo json_encode( $vastus );
exit;
}
Hope it helps

Updating database field in PHP when link is pressed

My page lists out all of the rows from a MySQL table and puts them inside separate divs as links.
while($row = mysqli_fetch_array($result))
{
echo "<a href='projects/" . $row['dir'] . "'><div>";
echo "<h2>" . $row['name'] . "</h2>";
echo "<p>Created: " . $row['date_created'] . "</p>";
echo "<p>Last opened: " . $row['date_last_opened'] . "</p>";
echo "<p>" . $row['description'] . "</p>";
echo "</div></a>";
}
When I click on a box (div), it opens that specific project. What I need, is to update the 'date_last_opened' field for a project to the current date when I click into one. The column for it in the table is of type 'date'.
Thanks to anyone that can help.
Simple method would be use of Jquery and AJAX:
First add click function to your link in while loop like this:
echo "<a href='projects/" . $row['dir'] . "' onclick='update(".$row['name'].")';><div>";
and in your JS file use Jquery Ajax:
function update(name){
var now = new Date();
var dateToInsert = now.format("dd/M/yy h:mm tt");//or whatever format you need
var projectName = name;
$.ajax({
type: "POST",
url: "update.php",
data: { date: dateToInsert, name: projectName}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
and your update.php:
if(isset($_POST['date']) && $_POST['name']){
$sql = "update yourTable set date ='".$_POST['date']."' where name= '".$_POST['name']."'";
//Rest of the code to execute query
}
else{
echo "AJAX call failed to send post variables";
}

how i can insert data in mysql and retrieve simulteneously in php on the click of one button?

actually i want to send a comment to the each image and it should display just after clicking the button . I am able to do insert and retrieve the comment but it require refresh the page and i don't want to refresh....just like orkut.plz help me i m new in php...
thans to all............
insertimg.php
//________________________________________FOR INSERT COMMENT_____________________________________________________
if (isset($_POST['Submit']))
{
$sql = "INSERT INTO comment(imid, comm) values ('".mysql_real_escape_string(stripslashes($_REQUEST['imgId']))."', '".mysql_real_escape_string(stripslashes($_REQUEST['Comment']))."')";
//$sql = "INSERT INTO comment (com) VALUES ($_POST['Comment'])";
//$sql="UPDATE upload SET comm='$_REQUEST['Comment']'WHERE id='$_REQUEST['imgId']'";
if($result = mysql_query($sql ,$conn))
{
echo "submited:";
}
else
{
echo "<h1>problem </h1> ".mysql_error();
}
}
For display comment..
$page=$_GET["page"];
$sql = "select comm from comment where imid = '".$page."'";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo"Comments:";
echo "<br>";
echo "<br>";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
//echo $row['comm'];
echo "<textarea name=\"Comment\" style=\"background-color:#81F7BE;\">"; echo $row['comm']; echo "</textarea>";
//echo "<font>";
echo "<br>";
echo "<br>";
}
mysql_close($conn);
?>
You can solve it with AJAX.
You can use something like jQuery Ajax library.
$.ajax({
type: "POST",
url: "inserting.php",
data: "imid=1&comm=Hi",
success: function(msg){
alert( "Ajax Response: " + msg );
}
});

Categories