Using JS element in PHP - javascript

I've a button inside a form:
echo '<tr class="user-personal-info">';
echo "<td><p>".$row['user_id']."</p></td>";
echo "<td><input placeholder='Username' type='text' value='".$row['user_name']."'/></td>";
echo "<td><input placeholder='Email' type='email' value='".$row['user_email']."'/></td>";
if($row['user_status'] == 1) {
echo "<td><select>";
echo "<option>User</option>";
echo "<option>Admin</option>";
echo "</select></td>";
} else {
echo "<td><select>";
echo "<option>Admin</option>";
echo "<option>User</option>";
echo "</select></td>";
}
echo "<td><input id='delete_btn' onclick='deleteUser(this);' type='submit' value='Delete'/></td>";
echo '</tr>';
As you can see there is a click event on the button. When i hit the button the following javascript function is executed. ID containes the id of a specific row ($row['user_id']):
function deleteUser(deze) {
const ID = deze.parentNode.parentNode.children[0].innerText
$.ajax({
url: "./includes/delete_user.php",
method: "POST",
data: {id:ID},
success: function(data) {
alert(data);
}
});
}
I want to send this ID variable to PHP to delete that specific record that matches with the ID. The problem is that my ID from JS is not send to PHP. When i echo this in PHP i get following error: Notice: Undefined index: id in....
PHP code:
<?php
include_once('./conn.php');
session_start();
$id = $_POST['id'];
echo $id; //can't echo this variable sent from javascript...
?>

You've put your submit button in a <form>, so after the JavaScript runs (but before the Ajax response is back and you alert it) the browser navigates to a new page (killing the JS program that is waiting for the response).
It is the new page that is showing the error and not the Ajax response.
Don't use type="submit" if you don't want to submit a form.
Use type="button".

Related

jQuery/AJAX data isn't posting

I am trying to create a very basic auction page on a site I am working on. I'm sort of working it out as I go along but I am now a bit stuck.
Data is stored in a MySQL table, this data has the image link, the ID, and the current bid.
I then retrieve the data in PHP/HTML, 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'><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: £" . $row['CurrentBid'] . "</div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid'/></div>";
echo "<div class='auction-bid'><button name='submit' id='submit' value='" . $row['ID'] . "' type='submit'>Place Bid!</button></div>";
echo "</div></form>";
}
echo "</table>";
This code pulls through the items absolutely fine. Along with a textbox for a name and a bid (I am not doing anything with the name at the moment).
My jQuery then looks like this:
$(document).ready(function(){
$('#auction').submit(function(){
var id = $('#submit').val();
var bidname = $('input[name=bidname]').val();
var bid = $('input[name=bid]').val();
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
success: function(){
}
});
return true;
});
});
Again this is very basic and I am not concerned about validation just yet.
And finally here is a snippet of my PHP code:
$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$query = "UPDATE auction SET CurrentBid = '$bid' WHERE ID = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
My problem is that when I click submit, nothing really happens. All the variable names and values get put into the browser address bar, and the page just seems to refresh.
The data does not get posted and when I debug with Firebug, I just get a red cross and it doesn't give me any errors.
I know from just looking at my code that best practices aren't followed, but I just want to get something working and then tidy it up later.
If anyone could point me in the right direction that would be a big help.
Thank you, and if you need anymore information please just let me know.
First of all: You need to rewrite your form element every element should have an unique id to differentiate the respective element.
<?php while($row = mysqli_fetch_array($result)){ ?>
<form name='auction' id='auction<?php echo $row['ID'] ?>'>
<input type='hidden' name='id' value='<?php echo $row['ID'] ?>'>
<div class='auction-thumb'>
<div class='auction-name'><?php echo $row['Item'] ?></div>
<img class='auction' src='<?php echo $row['ImagePath'] ?>' />
<div class='auction-bid'>Current Bid: £<?php echo row['CurrentBid'] ?></div>
<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname'/></div>
<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid'/></div>
<div class='auction-bid'>
<input type='submit' name='submit' value='Place Bid!'>
</div>
</div>
</form>
and replace your jquery code to
$(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).('input[name="bid"]').val();
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
success: function(){
}
});
return false;
});
});
You need to re-write this a bit: ID's have to be unique and when you loop through your items you assign the same IDs over and over to elements in different forms.
So when you try to get the values in your submit handler, jQuery does not know which value to get (it probably gets the value of the first element with that ID).
You should start with changing the IDs to for example classes and then serialize (for example...) the submitted form - $(this) in your submit handler - to get the correct data.
Add following keys in ajax to trace the errors.
$.ajax({
url: "auction-handler.php",
type: "POST",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
crossDomain:true,
success: function(result){ console.log(result); }
error: function(httpReq,status,exception){
alert("error - " +status+" "+exception);
}
});

Adding and deleting a row from SQL database using Ajax and JQuery

I have a PHP snippet that generates a table and fills it, and adds a delete button at the end of each row.
while($row = mysql_fetch_array($result)){
$num=$row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><form action='delete.php' method='post'><button type='submit' value=$num name='deleteId'>delete</button></form></td>";
echo "</tr>";
}
The delete.php file is this one :
<?php
$host="localhost";
$username="root";
$password="";
$db_name="students";
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$id = $_POST['deleteId'];
$sql="DELETE FROM students WHERE id='$id'";
$result=mysql_query($sql);
?>
I want to do this using Ajax asynchronously, ie. I don't want my page to refresh. Tried a million ways, yet it fails each time. Thanks in advance.
Instead of using a form, you need to write your own JavaScript to handle the server call. Here's one way to do it. Make your PHP look something like this:
while($row = mysql_fetch_array($result)){
$num=$row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><button onclick="deleteStudent($num)">delete</button></td>";
echo "</tr>";
}
And then have a JS function that looks something like this:
function deleteStudent(studentId) {
$.ajax({
url: "delete.php",
method: 'post',
data: {
deleteId: studentId
}
});
}
Another way:
Firstly, assign a unique ID for each of the delete button.
while($row = mysql_fetch_array($result)){
$num = $row['id'];
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['adress']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td><button id='delete-" . $row['id'] . "'>delete</button></td>";
echo "</tr>";
}
Then use jQuery:
$('button[id^="delete"]').click(function () {
var id = $(this).attr('id').substr(6);
$.ajax({
type: "POST",
url: "delete.php",
data: {deleteId: id}
});
});

php post form with variable and javascript submit

I have a list of items from a database and I am trying to post to a specific entry in that list using javascript to submit a form. I have no idea why it's not working though. Here is my code...
<?php
...
while loop to get results {
echo "<form action='scheduled.php?id=$row[id]' method='post' id='sche'>";
echo "<td onclick=\"javascript:document.getElementById('sche').submit();\">".$row['firstname'];
echo "</td>";
echo "</form>";
}
?>
The weird part is that it WILL post, but it doesn't pull the right 'id'. It will take the first one on the list and post to that 'id'.
my URL reads "...scheduled.php?id="
Because of the loop, you are defining many different forms with the same id "sche". You need to give each element their own id.
<?php
...
while loop to get results {
echo "<form action='scheduled.php?id=$row[id]' method='post' id='sche_$row[id]'>";
echo "<td onclick=\"javascript:document.getElementById('sche_$row[id]').submit();\">".$row['firstname'];
echo "</td>";
echo "</form>";
}
?>
Notice the new sche_$row[id] for "id"

<input> calling a PHP function using AJAX

I am trying to call a PHP function using AJAX to check if the pressed button is the right button.
But I can't seem to figure it out.
I am using this as <input> code :
<?php
$i=0;
while ($i<4){
?>
<input style="background-color: <?php echo $buttonColors[$i]; ?>" onclick="echoHello(<?php echo $i?>)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php $i=$i+1; } ?>
and I'm trying to call a PHP function when the button is clicked. I tried this :
<script>
function echoHello()
{
alert("<?php hello(); ?>");
}
</script>
<?php
function hello() {
echo "Hello World";
}
?>
This worked so I tried to change this to :
<script>
function echoHello(num)
{
alert("<?php hello(num); ?>");
}
</script>
<?php
function hello($num) {
if($num == 1) {
echo "Correct button!!!";
} else {
echo "WRONG BUTTON";
}
?>
But this didn't seem to work. What am I doing wrong?
I think you have quite some thing mixed up here.
I would suggest just writing out the buttons, and pass the buttons value to the javascript:
<?php
$i=0;
while ($i<4){
?>
<input onclick="echoHello(this.value)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php
$i=$i+1;
} ?>
and then in your javascript (after adding all the jQuery goodness):
function echoHello(btnValue) {
$.ajax({
type: "POST",
url: "formhandler.php",
data: { buttonValue: btnValue }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
The javascript above will send the button value to your 'formhandler.php' page, using AJAX.
In the 'formhandler.php', you could then check what the value of $_POST["buttonValue"] is.
Using your setup, together with jQuery, PHP and JSON, it could be something like this:
function echoHello(btnValue) {
$.getJSON('page.php', {
choice: btnValue
})
.done(function(data) {
// based on $_GET["choice"], your PHP could render some JSON like:
// {"background":"image.jpg","fields":["newValue1", "newValue2", "newValue3"]}
// clear the current html
$("#form").html('');
// load a new background
$('body').css({'background-image':data.background})
// set up the new fields:
$.each(data.fields, function( i, item ) {
$("#form").append('<input type="text" value="' + item + '"/>');
});
});
}
This is just a sample, to give you an idea! It's untested also ;)

Single Div refresh with jquery Ajax and PHP

Okay So I have a div on my page that has some code for display option groups in a select input. And then on the other side displaying the options in that group after the selection is made. My html/php code for this is below:
<div class="row">
<div class="col-lg-6">
<label class="control-label" for="productOptions">Select your
product options</label> <select class="form-control" id=
"productOptions">
<option>
Select an Option Group
</option><?php foreach($DefaultOptions as $option): ?>
<option value="<?php echo $option['GroupID']; ?>">
<?php echo $option['GroupName']; ?>
</option><?php endforeach; ?>
</select>
</div>
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
</div>
By default on the original page load, $GroupOptions does not exist in the form, because it is set after the user selects the Group they wish to choose from. I call the php script by using ajax to avoid page reload
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function() {
$("#groupOptions").html(dataString);
}
});
return false;
});
Then the ajax goes to a php call that gets the options that match the groups id in the database.
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
}
Now I want to refresh the div #GroupOptions to display the results from the query above, and make <?php if($GroupOptions): ?> set to true.
I managed to refresh the div with $("#groupOptions").html(dataString); in the success function of the ajax call. But that only returns well the dataString. (obviously). Is there a way to truly refresh just the div. Or a way to pass the info from the php call into the success function?
UPDATE:
You have 4 problems in your current code:
Problem #1 and Problem #2 - In your separate PHP script you are not echoing anything back to the Ajax. Anything you echo will go back as a variable to the success function. Simply the add echo statement(s) according to the format you want. Your 2nd problem is that you are trying to echo it in the HTML part, where $GroupOptions does not even exist (the Ajax simply returns an output from the PHP script, it's not an include statement so your variables are not in the same scope).
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
//this is where you want to iterate through the result and echo it (will be sent as it to the success function as a variable)
if($GroupOptions):
foreach ($GroupOptions as $optionValue):
echo $optionValue['optionName'];
endforeach;
endif;
}
In your Ajax, add a variable named data to the success function, which will receive the output from the PHP script. Also notice that your url is incorrect, you need to post to an actual external file such as my_custom_script.php.:
$.ajax({
type: "POST",
url: "your_external_script.php",
data: dataString,
success: function(data) {
if (data && data !== '') {
//data will equal anything that you echo in the PHP script
//we're adding the label to the html so you don't override it with the new output
var output = '<label class="control-label">Group Options</label>';
output += data;
$("#groupOptions").html(output);
} else {//nothing came back from the PHP script
alert('no data received!');
}
}
});
Problem #4 - And on your HTML, no need to run any PHP. Simply change:
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
to
<div class="col-lg-6" id="groupOptions">
</div>
Hope this helps
You have to take the response in yout success callback function and actually give a response in your oho function
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(dataString) { //take the response here
// convert dataString to html...
$("#groupOptions").html(newHtml);
}
});
return false;
});
PHP:
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
echo json_encode($GroupOptions ); //give a response here using json
}

Categories