refresh jquery mobile div after getting data using php and ajax - php

php file:
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_assoc($result)) {
$orgID=$row["InstancesID"];
echo "description: " . $row["describtion"]. "<br><br>"." - Type: " . $row["type"]. "<br><br>". "-Amount: " . $row["amount"]. "<br><br>";
echo"<input type='button' onclick=SendID($orgID) value='updateee'/> <br><br>";
}
ajax function:
$(document).ready(function(){
$("#show").click(function(){
$.ajax({url: "http://127.0.0.1/testupdate.php?f=ShowAllInstances",
success: function(result){
//alert(result);
$("#divshow").html(result);
}});
});
});
this displays the returned data in html page I want to display them in jquery mobile page.
any help please

Related

How can I get clicked input radio value from autocomplete to send in form to php file

I'm doing an input with autocomplete where my user can select multiple users from database and I want to submit those select users in my form where action goes to a php file that does a INSERT in the database.
So this is the input, I want the selected users to show up in p#selecionados but user selects one at a time:
<form id="formCriaJogo" method="post" action="./components/insert.php">
<label>Other users</label>
<input type="text" name="autor" id="autor" placeholder="Write users name" />
<div id="autorLista"></div>
<p id="selecionados"></p>
<button type="submit">Insert</button>
</form>
And this is jquery code to do the autocomplete:
$(document).ready(function() {
$('#autor').keyup(function() {
var query = $(this).val();;
if (query != '') {
$.ajax({
url: "./components/search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$("input#autor").css("margin-bottom", '0');
$("#autorLista").css("display", 'block');
$('#autorLista').fadeIn();
$('#autorLista').html(data);
},
error: function(error) {
console.log(error);
}
});
}
});
$('input#autor').on('change', function() {
alert($('input[name=autor]:checked', '#formCriaJogo').val());
});
});
Also, here is search.php that does the search:
<?php
include_once "../connection/connection.php";
if (isset($_POST['query'])) {
$link = new_db_connection();
$stmt = mysqli_stmt_init($link);
$output = '';
$input = $_POST['query'];
$query = "SELECT id_user, nome_user FROM users WHERE nome_user LIKE CONCAT(?, '%')";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, 's', $input);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_user, $name_user);
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) > 0) {
while (mysqli_stmt_fetch($stmt)) {
$output .= "<input type='radio' value='" . $id_user . "' name='autor'>" . $name_user . "<br>";
}
} else {
$output .= '<p>The user your looking for doesn't exist.</p>';
}
echo $output;
}
Now the clicked input type=radio value which contains users' id and name I want the user name in p#selecionados just to show them what he selected and also send id and name of user selected when submitting my form.
You can create an array in jquery so , whenever you select an option from autocomplete box.. put that value inside that array in jquery .I have use checkbox instead of radio-button in below code and whenever user select any option that data will get inserted in array i.e:index and when insert button is clicked the selected data will get display in p#selecionados tag and also an ajax will call to send your selected data to php page.Also i have added value='" . $id_user."," . $name_user . "' you can split this using .split() with delimiter , to get both userid and username.Sample code :
var index = [];
//when check-box is changed
$('input[name=autor]').change(function() {
//checking if checkbox is check put it in array
if ($(this).is(':checked')) {
index.push($(this).val());
console.log(index)
} else {
//if uncheck remove the element from array
if ((index1 = index.indexOf($(this).val()) !== -1)) {
index.splice($.inArray(index1, index), 1);
console.log("remove");
}
}
});
//when insert button is click
$("button").click(function() {
//clear the p tag content
$("p#selecionados").html("");
for (var i = 0; i < index.length; i++) {
//append all selected check box
$("p#selecionados").append(index[i] + "<br />");
console.log("userid & username" + index[i]);
}
if (index != '') {
$.ajax({
url: "yourphp_page_name",
method: "POST",
data: {
//sending array to php
data: index
},
success: function(data) {
//do something
},
error: function(error) {
//do something
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user . <br/>
<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user . <br/>
<button type="submit">Insert</button> <br/><br/> Selected data :
<p id="selecionados"></p>
Then in your php side ,you need to get that array i.e : data using $_POST['data'] and then explode your array and use it as per your requirement.

Ajax - Sending and Receiving

I have 2 files, A .js and a .php. The .php connects to the MySQL DB and the .js is the front end of the system.
I'm in the middle of trying to set it up so it sends a hash key to the ajax which returns the correct data for the related person from the database.
So far it does work as it send the hash from the URL to the PHP file and returns back the data in the console log.
//AJAX Function
//Grabs Varibles from PHP
var hash = window.location.hash.substr(1);
$(function() {
$('.hashfield').text(hash)
});
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
console.log(data);
},
error:function() {
console.log("FAIL");
}
})
This is within the .js file which sends the hash
<?php
if(isset($_REQUEST['WorkingHash'])){
$hash = $_POST['hash'];
function IDHASH($hash){
echo $hash;
}
IDHASH($hash);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, CustomerName, ContactName, Address, City, PostalCode, Country FROM customers WHERE ID=$hash";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
This is the .php file. I need to return the data from the database related to the correct customer ID.
All the data being echoed from the while loop will need it's own variably within a js format
My Goal is to retrieve each entry from the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
}
instead use
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
print_r(json_encode($row));
}
and in js
javacript
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
data = JSON.parse(data);
console.log(data);
//YOU CAN USE data.ID , data.CustomerName and so on
},
error:function() {
console.log("FAIL");
}
})
How about something like this:
Edit
instead of return data echo it like this:
if ($result->num_rows > 0) {
// echo the data instead of return
echo json_encode($result->fetch_assoc());
}
To access the properties of the object you can in your success function do that :
success: function(data){
// parse your data first
data = JSON.parse(data);
//Return of AJAX Data
console.log(data.CustomerName);
console.log(data.ContactName);
// you can assign them to a variables if you want
var customerName = data.CustomerName;
var ccontactName = data.CustomerName;
}

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

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";
}

JS $('form').change(function() only triggers on first form item

Following on from my question yesterday, I now have the code below somewhat successfully working. It allows me to change the first form item and submits it to 'process.php' in the background and turns the field green. However the trigger only works on the first form item, in this case "cstate". It doesn't trigger when "clocation" is changed. If you change clocation and then cstate then both form submit fine so it's simply that the .change function isn't triggering when clocation is changed. I'm not good enough at JS (total JS noob) to know why it isn't working so I'd appreciate any help you can give me.
Thanks!
$sql = "select * from `$table1`";
$result = mysql_query ($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$carid = $row["car_id"];
$carnum = $row["carnum"];
$carlocation = $row["carlocation"];
$carstate = $row["carstate"];
$formname = "#form".$carid;
print '<script type="text/javascript">';
print " var cnum;";
print " cnum = '$formname',";
print "
$('form').change(function()
{
console.log(cnum);
$.ajax({
type: 'post',
url: 'process.php',
data: $(this).serialize(),
success: function() {
}
});
return false;
});
</script>";
echo "<table>";
echo "<tr id='$carid'>";
echo "<td>$carnum</td>";
echo "<td><form action='' method='post' id='form$carid'>";
echo "<select id='popup' name='cstate'>";
echo "<option value='In-Service-Bay'>In Service Bay</option>";
echo "<option value='Awaiting-Service'>Awaiting Service</option>";
echo "<option value='Service-Complete'>Service Complete</option>";
echo "</select></td>";
echo "<select id='popup' name='clocation'>";
echo "<option value='Carpark-1'>Carpark-1</option>";
echo "<option value='Carpark-2'>Carpark-2</option>";
echo "<option value='Carpark-3'>Carpark-3</option>";
echo "</select></td>";
echo "</form></tr>";
}
echo "</table>";
Use .on() and wrap code inside document.ready.
$(document).ready(function(){
$('form').on('submit',function()
{
//code here
});
});
also put this code outside the while loop. Also form does not have change event try using .submit()
Solved it by using a separate form for each input selection. Works brilliantly now.
Thanks to all those that tried to help.
Adam

Categories