AJAX post jQuery to PHP $_POST - javascript

I have this modal jQuery AJAX:
$('#switch_modal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).attr('data-id');
$.ajax({
type : 'post', // commented for this demo
url : 'pars.php', // commented for this demo
data : 'id='+ rowid,
success : function(data) {
$('.fetched-data').show().html(rowid); // show rowid for this demo
}
});
});
My mysql query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
while ($row = $result->fetch_assoc()) {
My modal data-id:
<a href="#viewgame" data-toggle="modal" data-id="<?php echo $row['id'];?>"">
How can i do to use the var rowid like a PHP post? Something like that:
$id = $_POST['rowid'];
echo $id;

If i understand well this test your doing...
Your JavaScript rowid is the value.
The $_POST identifier is id.
Try this in your PHP:
$id = $_POST['id'];
echo $id;
You'll get the javascript rowid sent as a POST value (named as $_POST['id']) via ajax... And returning in data on ajax success.
$('.fetched-data').show().html(data);
So you'll have to use data in your jQuery html()... Wich is the echoed text.
-----
EDIT AFTER ACCEPTATION of this answer
(Based on your last comment)
So i have this query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$gameid = $row['id'];
}
}
So i want to use $gameid variable into this query:
$sql = "SELECT * FROM games WHERE id='".$gameid."'";
I understand, that you want to get THE LAST matching full line where winner value is empty from games table.
No need for an ajax call...
No need for a second query.
Just do it:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query);
$row = $result->fetch_assoc();
for ($i=0;$i<sizeOf($row);$i++){ // This is the «size» (number of values) of one row, the last fetched.
echo $row[$i] . "<br>";
}
You'll get all your line values echoed...
This will be the LAST matching line fetched.
If you have many matching lines and want all results, do it like this:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query));
while ($row = $result->fetch_assoc()) { // While fetching, echo all values of one matching line.
echo "row id: " . $row['id'] . "<br>";
echo "values: <br>";
for ($i=0;$i<sizeOf($row);$i++){
echo $row[$i] . "<br>";
}
}
Notice that this script, that I suggest, will enlight you about the while fetch loop possible results. You'll have to work a little to have it displayed correctly on your page.
;)

Related

i have code like this for auto complete feature but am not able fetch the data from the data base.kindly help me out

My aim is to fetch location from the database once user start entering in the input tetc field
i have done all the coding properly but the also am not able to fetch the data from the database.
<!--My java script code-->
$(function() {
$( "#LocationName" ).autocomplete({
source: 'search.php'
});
});
<!--My Search.php code-->
<?php
include('dbConnect.php');
$searchTerm = $_GET['term'];
$sql = mysql_query ("SELECT LocationName,From arealistmain WHERE LocationName LIKE ?");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = array (
'value' => $row['LocationName'].'',
);
}
//RETURN JSON ARRAY
echo json_encode ($array);
?>
First of all don't use mysql_* functions as they were deprecated in PHP 5.5 and removed in PHP 7 instead use mysqli_* functions.
Second thing you should always sanitize user input don't just do $searchTerm = $_GET['term']; read more about this
Then your SQL query should read
$query = "SELECT LocationName From arealistmain WHERE LocationName LIKE '%$searchTerm%';";
The comma before FROM removed and the $searchTerm is enclosed in two percentage signs to match all
Update your query to below code
$sql = mysql_query ("SELECT LocationName From arealistmain WHERE LocationName LIKE '%".$searchTerm."%'");
$array = array();
while ($row = mysql_fetch_array($sql)) {
$array[] = $row['LocationName'];
}

Dropdown box to insert value to MYSQL db OnChange using AJAX and PHP

I am having trouble executing SQL via AJAX when a dropdown box is changed and would like some help if possible.
Background Info
I have been tasked with creating a daily calendar that shows all the classes ran at a gym, which at its maximum is 5 x classes of 6 (30) people per hour for 14 hours.I'm no pro and I may have created a convoluted way around this issue, please let me know if i have.
I have managed to create the view which consists of 14 columns of 30 drop down boxes (5 x classes of 6 per hour for 14 hours). Each drop down box polls the db and if an entry resides it will populate the box with the name of the bookinguser. If no booking is found it will create a drop downbox that polls the members table and presents all the members of the gym, which when changed, will hopefully book that person in. - herein lies my current issue!
Each drop down box's name corresponds to the time, group and headcount which I intend on passing to javascript function and eventually to the SQL statement. Each option's value corresponds with the memberid which will also be passed giving all the information needed to construct the SQL.
The code I have so far
HTML - snipped generated from php loops
<div id="results">
<div id="07" class="column">07:00<br/>
<div id="group1">
<select name="07:00-1-0" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
<select name="07:00-1-1" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
PHP
<?php
$mysqli = new mysqli("localhost", "root", "", "gym");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
function hyphenate($str) {
return implode("-", str_split($str, 2));
}
function getmembers($time,$group,$iteration)
{
$date=$_GET["date"];
$date=hyphenate($date);
$date = explode('-', $date);
$new_date = $date[2].'-'.$date[1].'-'.$date[0];
$mysqli = new mysqli("localhost", "root", "", "gym");
if ($iteration == 0){
$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1");
}
else {$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1,$iteration");
}
$rowcount=mysqli_num_rows($result);
if ($rowcount==$iteration && $iteration == 0)
{
$result = $mysqli->query("select firstname, lastname,memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
else if ($rowcount>=$iteration){
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)">';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option><option value="cancel">Cancel</option>';
}
echo "</select>";
}
else{
$result = $mysqli->query("select firstname, lastname, memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
}
?>
JS
function getda(id,booking){
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:id
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
}
samefile.php
<?php
if(isset($_POST['get_option']))
{
inlude 'config/config.php';
$name=$_POST["get_option"];
echo "<SCRIPT>
alert('$name');
</SCRIPT>";
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
$mysqli->close();
?>
The console in chrome looks fine (below) but no records are inserted and the php alert doesn't show. I havent passed any of the variable to the SQL as I was first testing that a query executed properly
jquery.min.js:4 XHR finished loading: POST "http://localhost/gym/samefile.php".send # jquery.min.js:4n.extend.ajax # jquery.min.js:4getda # cal.php?date=140416:42onchange # cal.php?date=140416:36ListPicker._handleMouseUp # about:blank:535
Might want to look into jQuery's .change(). I think that it would work with something like below for your code. You could also have it call your function that has ajax in it as well
$( ".class" ).change(function() { //can use #id here too
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:this.value
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
});
I see three problems in samefile.php - include spelled incorrectly, an extra semicolon, and a missing closing bracket:
<?php
if(isset($_POST['get_option']))
{
include 'config/config.php';
$name = $_POST["get_option"];
//this should be converted to parameterized queries
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
if(is_object($query)){
echo 'successfully inserted';
} else {
echo 'insert failed';
}
$mysqli->close();
} else {
echo 'no data to process!';
}
?>

Elements not included in div when added using Javascript

I have a list of products on my website a Catalogue. The following PHP Code uses javascript to create a div and insert all the product description links inside it.
$sql = "SELECT * from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo "<script>document.getElementById('products').innerHTML = '<div class=ks>';</script>";
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
echo "<script>document.getElementById('products').innerHTML += '$xx';</script>";
}
echo "<script>document.getElementById('products').innerHTML += '</div>';</script>";
Ignore all the ks style sheet class and all the mysql stuff for now.
The problem is it displays the grey backgrounded div (grey from style sheet)
and THEN the links. I need the links to be inside the div.
For a little explanation for those of you who are confused by the pieces of code unrelated to the primary purpose of this question,
The Products table in MySQL is a table that hold all my product info including price, name, id, e.t.c.
the "Getdesc.php?hid=..." link is a link to a php web page that will display all the information about the product from it's Id.
"Products" is an Id of a different div that contains this internal div (With the products I mean) PLUS some other stuff ( I don't feel like telling you all about it).
Sorry for the messy code, thanks in advance.
Javascript:
//from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener () {
document.getElementById('products').innerHTML = this.responseText;
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.php", true);
oReq.send();
PHP
$sql = "SELECT <columns> from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo '<div class="ks">';
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
echo '' . htmlspecialchars($row['Name']) . '<br>';
}
echo '</div>'
why not put everything in a variable :
$html = '<div class="ks">'; // btw you forgot those double-quotes. you html won't evaluate the class if not surrounded by double-quotes
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
$html.= $xx;
}
$html.= '</div>';
then echo it? if you're using php, then there's no need to change the page with javascript after it's been loaded, you just sent all the remainder of the page to the client, why not directly put this code at the right place?
echo $html;

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

PHP populate drop box with jquery

I have a script which fetches options from a script php to populate a drop down list on the main page.
Here's the javascript
<script>
//# this script uses jquery and ajax it is used to set the values in
$(document).ready(function(){
//# the time field whenever a day is selected.
$("#day").change(function() {
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json'
success: function(data) {
//# $("#time").html(data);
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.timing + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
Here's the php script which gets data from a database.
<?php
$con = mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query = "SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
//$res = array();
echo "<select name='timing' id='timing'>";
//Initialize the variable which passes over the array key values
$i = 0;
//Fetches an associative array of the row
$row = mysqli_fetch_assoc($result);
// Fetches an array of keys for the row.
$index = array_keys($row);
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
//array_push($res, $index[$i]);
json_encode($index[$i]);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo json_encode($res);
echo "</select>";
?>
It's not working. I get an error from console saying missing '}' in javasrcipt on line
$("#day").change(function(){
I can't seem to find an error either.
You need to add a comma on the line above the one triggering the error :
dataType : 'json',
It's because you don't have a comma on the line above it...
It's hard to say where is problem, because you mixed things together. On Javascript side you expect JSON but on PHP side you generate HTML.
Use JSON for sending data between server and browser. Ensure that you actually generate valid JSON and only JSON.
This line does nothing (function returns value, but not modifies it)
json_encode($index[$i]);
This line does not make sense - variable $res is not initialized;
echo json_encode($res);

Categories