So I've got 2 boxes. On the left I have a list of items pulling from the database which I can drag and drop to the right. This works great. I can't for the life of me work out how to get it to post the data for the list on the right and I think I've tried every example Google has to offer this week.
When I do a print_r($_POST); on the page this submits to, I get Array ( ) with nothing in it. It doesn't seem to be grabbing the ID's and serializing them.
Does anyone have experience with this see anything I'm missing?
<script>
$(function() {
$( "ul.droptrue" ).sortable({
connectWith: "ul"
});
$( "ul.dropfalse" ).sortable({
connectWith: "ul",
dropOnEmpty: true
});
$( "#sortable1, #sortable2" ).disableSelection();
});
$( "#sortable2" ).sortable({
axis: 'y',
handle : '.handle',
update: function (event, ui) {
var data = $(this).sortable('serialize');
console.log(data);
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: 'setlists-edit-process.php'
});
}
});
</script>
<ul id="sortable1" class="droptrue">
<?php
$_GET['setlist_id'];
$sql = "SELECT material_id, material_name FROM material WHERE user_id=$session_id";
$result = mysqli_query($conn, $sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
while($row = mysqli_fetch_array($result))
{
echo "<li id=" . $row['material_id'] . ">" . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
?>
</ul>
<ul id="sortable2" class="dropfalse">
</ul>
Replace this:
while($row = mysqli_fetch_array($result))
{
echo "<li id=" . $row['material_id'] . ">" . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
with:
while($row = mysqli_fetch_array($result))
{
echo '<li id="material_' . $row['material_id'] . '">' . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
Sortable expects the ID to be in the format setname_number.
Moreover, your code outputs in the format id=abc (no quotations), and rather it should be id="abc" with surrounding quotes.
Related
this code displays the name as i type, as i type it gives suggestion of names and when clicked on it it displays the result in the textbox.but i want to display the id related to that name from database when i clicked on that name from the dropdown option. please help
<input type="text" name="st_id" id="st_id" ><div id="txtHint" style="position: absolute; width:390px ;"></div>
ajax code:
$(document).ready(function () {
$("#st_id").keyup(function () {
var search = $(this).val();
if (search != '') {
$.ajax({
type: "POST",
url: "ajaxcode.php",
data: {search: search},
success: function (data) {
$("#txtHint").fadeIn();
$("#txtHint").html(data);
}
});
}
});
});
php code
<?php
if (isset($_POST["search"])) {
$display = '';
$q = $_POST["search"];
$stmt = $DBconnect->prepare("SELECT * FROM table1 WHERE First_name LIKE :sh ");
$stmt->bindValue(':sh', '' . $q . '%', PDO::PARAM_STR);
$stmt->execute();
$display = '<ul class="list-unstyled">';
foreach ($stmt as $row) {
if ($row) {
$display .= '<li>' . $row["First_name"] . ' ' . $row["Middle_name"] . ' ' . $row["Last_name"] . '</li>';
} else {
$display .= '<li>name not found</li>';
}
}
$display .= '</ul>';
echo $display;
}
?>
Most naive way I can come up with is adding an id to the top ul
<ul id="name_suggestion" class="list-unstyled">
and the id to the <li> tag with a data- attr
$display .= '<li data-user-id = '. $row["id"] . '>'.$row["First_name"].' '.$row["Middle_name"].' '.$row["Last_name"].'</li>';
Then add an a click listener to the li:
$('#name_suggestion li').on('click', function(e){
let val = $(this).attr('data-user-id');
$('#st_id').val(val);
});
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
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";
}
I want to add data to my database, and get back the response from php which accesses the database.
javascript code:
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
var responseText = "onbekend";
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
So when the a name isn't valid or is already in existence, I can add this message to a span element in my html.
This is my php code:
<?php
if($_POST)
{
// Create connection
$con=mysqli_connect("localhost","root","root","websitedb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = getdate();
$date_time = $date['year'] . "-" . $date['mon'] . "-" . $date['mday'] . " " . $date['hours'] . ":" . $date['minutes'] . ":" . $date['seconds'];
$uitdagerArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitdager'] . "'");
$uitgedaagdeArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitgedaagde'] . "'");
$uitdager = mysqli_fetch_array($uitdagerArray);
$uitgedaagde = mysqli_fetch_array($uitgedaagdeArray);
$uitdagerId = $uitdager['id'];
$uitgedaagdeId = $uitgedaagde['id'];
$sql="INSERT INTO duels (uitdager, uitgedaagde, aanmaakdatum, gespeeld) VALUES ('" . $uitdagerId . "','" . $uitgedaagdeId . "','" . $date_time . "','" . "0" . "')";
if(!mysqli_query($con,$sql)) {
echo mysql_errno() . ": " . mysql_error() . "\n";
}
else {
echo "Duel Toegevoegd";
}
mysqli_close($con);
}
?>
So is it possible that the text from echo in my php code will be passed to the 'response' from the succes function?
edit:
this is my html code
<div id="nieuwDuel">
<h2>Nieuw Duel</h2>
<form name="form" method="post">
Uitdager: <input type="text" id="naamUitdager" placeholder="naam uitdager">
Uitgedaagde: <input type="text" id="naamUitgedaagde" placeholder="naam uitgedaagde">
<input type="submit" class="nieuwDuelToevoegen">
</form>
<span id="duelToegevoegd" style="display:none"></span>
Home
</div>
I assume that your PHP code is right. then what you need to change is your jQuery code.
just change the following code :
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
into following :
responseText = response;
$('#duelToegevoegd').html(responseText);
I don't know what you are going to do with
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
So, I leave it out for now
hope it helps
Yes it should work. Try changing your JS to
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
console.log(response);//This will output the response you are getting to the console so you can check it
$("#duelToegevoegd").html(response);
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
Also I wouldn't echo out any errors you get back to the client
echo "Failed to connect to MySQL: " . mysqli_connect_error();
Although it depends who the user is, but you don't want anyone unauthorised to see these errors
I have the following jquery script
$("li").click(function(){
var id = $(this).attr("id");
$.get("getData.php", {id: id}, function(data){
$("ul").after(data);
});
$(this).css("color","red");
});
and the getData.php file
<?php
include("db_config.php");
$ctgID = $_GET["id"];
if(isset($ctgID))
{
getData($dbh, $ctgID);
}
function getData($dbh, $ctgID)
{
try{
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $dbh->prepare("select ctgid, ctgdescription from categories where ctgparentid = $ctgID");
$sql->execute();
$result = $sql->rowCount();
if($result >0)
{
echo "<ul>";
while($row = $sql->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
echo "<li class=\"subCtg\" id=\"". $row[0] . "\">" . $row[1] . "</li>";
}
echo "</ul>";
}
else
{
echo "1";
}
}
catch(PDOException $e){
die($e);
}
}
?>
Even if the above is working perfectly for the top level categories its not working when i am clicking on the subCtg class that is created. Can you help me please?
Use click event like this, that trigger on your existing and dynamic lists as well:
$('ul').on('click', 'ul li', function(){
.....
});
Take a look on this example
HTML:
<ul>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
JS:
$(document).on('click', 'li', function(e){
e.preventDefault();
e.stopPropagation();
$(this).parent('ul').after('<ul><li>new item click here </li></ul>');
});
Live demo: http://jsfiddle.net/jogesh_pi/YdByT/
Use Jquery Bind instead of click event ..
$( ".subCtg" ).bind( "click", function() {
alert( "User clicked " );
});
Jquery Bind
As you load new ul/li elements, you have to bind the "click"
event on them.
Try this:
PHP
...
while($row = $sql->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
echo "<li class=\"subCtg\" onclick=\"myFunc(".$row[0].");\" id=\"". $row[0] . "\">" . $row[1] . "</li>";
}
...
Javascript
$("li").click(function(){
var id = $(this).attr("id");
myfunc(id);
});
function myFunc(id){
$.get("getData.php", {id: id}, function(data){
$("#"+id).parent(ul).after(data);
});
$("#"+id).css("color","red");
}
An only-javascript approach could be:
function myFunc(id){
$.get("getData.php", {id: id}, function(data){
$("#"+id).parent(ul).after(data);
});
$("#"+id).css("color","red");
//create onclick event on new elements
$("li").each(function(){
$(this).click(myFunc($(this).attr("id")));
});
}