Ajax not working, PHP, AJAX - php

I'm trying to use ajax on a select tag with 2 options, but it's not getting the $_POST for some reason. It prints out the "---", but it does not print out the $_POST value, which is either 1 or 2. I'm not sure what I did wrong. Please take a look at my code right here, and if you figure out which part of the code is wrong, please point it out with a working example. Thank you.
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
<?php
echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"input\",\"name\",\"output\")'>";
echo "<option value = '1'> 1 </option>";
echo "<option value = '2'> 2 </option>";
echo "</select>";
echo "<div id = 'output'></div>";
?>
newtestx.php
<?php
$name = $_POST['name'];
echo $name."---";
?>

You need to change this line:
echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"select\",\"name\",\"output\")'>";

1: Maybe you want to post the value. data:{select:$("select[name='name']").val()}.
But selector is false. tag is select not input.
`echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"input\",\"name\",\"output\")'>";";`
`data: { select: $(type+'[name='+theName+']').val()},`
2: .php will not get the param. Because your data's key is select, so $name = $_POST['select'];.
Finally, you want to return data, should use die($name);
`$name = $_POST['name'];
echo $name."---";`

Related

Auto populate text fields based on dropdown selection where all values come from a MYSQL table

I'm trying to auto populate some text fields (rate1 and rate2) based on a dropdown selection (instid and instfirstname). The values are all in one mysql table called tbl_insts. I'm trying the solution found in How to Get Content in text field dynamically, based on dropdown selection in php, but can't get it to work. Does anyone have any suggestions? Thanks in advance.
This is my mysql table called tbl_insts
instid instfirstname rate1 rate2
1 john 50 45
2 eric 25 45
This is my html form. I'm able to populate the dropdown correctly but not the text fields.
<select name="instfilter" id="instfilter">
<?php
if ($stmt = $conn->prepare("select instid, instfirstname from tbl_insts order by instid")) {
$stmt->execute();
$stmt->bind_result($instid, $instfirstname);
echo '<option value="-1" selected="selected">Please select...</option>';
while ($stmt->fetch()) {
echo '<option value="'.$instid.'">'.$instfirstname.'</option>';
}
$stmt->close();
}
?>
</select>
<!-- Fields that I want to populate based on the selection on top -->
<input type="text" name="rate1" id="rate1" />
<input type="text" name="rate2" id="rate2" />
This is my code before the tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$('#instfilter').change(function(){
var inst = $(this).val();
$.ajax({
type:'POST',
data:{inst:inst},
url:'getrates.php',
success:function(data){
$('#rate1').val(data);
$('#rate2').val(data);
}
});
});
</script>
This is my code in getrates.php in the same directory as the html file above.
<?php
if (isset($_POST['inst'])) {
$qry = "select rate1, rate2 from tbl_insts where instid = ".
$_POST['inst'];
$rec = mysql_query($qry);
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1'];
echo $res['rate2'];
}
}
}
die();
?>
try change data:{inst:inst} to data:{'inst':inst}
now you returning a string from getrates.php. From you code structure, you can do like this:
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1']."|".$res['rate2'];
}
}
..and
success:function(data){
var inputs = data.split('|');
$('#rate1').val(inputs[0]);
$('#rate2').val(inputs[1]);
}
hope this helps.
Untested, but I think these changes should do the job.
while ($res = mysql_fetch_array($rec)) {
$result = [
'rate1' => $res['rate1'],
'rate2' => $res['rate2']
];
}
.......
die(json_encode($result));
and
success: function(data){
data = $.parseJSON(data);
$('#rate1').val(data.rate1);
$('#rate2').val(data.rate2);
}

How to update dynamically populated content with AJAX

I have some code which populates like so:
<select class="form-control" name="accommodation_ID" id="accommodation_ID">
<option value="-1">-- Please Select --</option>
<?php
$AccomodationID = 13; //For testing purposes
$accommodation_query = mysqli_query($conn,"SELECT ENTITIES.LastName,
ACCOMMODATION.AccomodationID, ACCOMMODATION.PUPoint
FROM ACCOMMODATION, ENTITIES WHERE ENTITIES.Entity_ID =
ACCOMMODATION.Entity_ID")
or die("Error: ".mysqli_error($conn));
while($accommodation_Results = mysqli_fetch_array($accommodation_query)){
if($accommodation_Results['AccomodationID'] == $AccomodationID){
echo '<option selected value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
$PUPoint = $accommodation_Results['PUPoint'];
}
else{
echo '<option value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
}
}
?>
</select>
<label>Pick Up Point</label>
<input type="text" name="PUPoint" readonly value="<?php echo $PUPoint; ?>">
This code works no problem, it checks the database and looks for a match, if it does, set is as the selected option, grab the PUPoint (Pickup point) variable and store it in the input field.
My problem now, is when I go to select a different option from the dropdown list, the pickup point input field doesn't update anymore. This is what I had, working before I implemented the above:
j$('select[name=accommodation_ID]').change(function(event) {
event.preventDefault();
var accommodationID = j$(this).val();
post_data = {'accommodation_ID':accommodationID};
var data = {
"action": "Accommodation_Details"
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
j$('input[name=PUPoint]').val( data["PUPoint"] );
},
error: function (request) {
console.log(request.responseText);
}
});
});
booking_Modify.php
//checks and switch statement related code
$return = $_POST;
$return["accommodation_ID"] = $_POST["accommodation_ID"];
$return["SQL"] = "SELECT * FROM ACCOMMODATION WHERE AccommodationID = ".$_POST["accommodation_ID"]."";
$query = mysqli_query($conn,"SELECT * FROM ACCOMMODATION WHERE AccomodationID = ".$_POST["accommodation_ID"]."")
or die("Error: ".mysqli_error($conn));
$row = mysqli_fetch_array($query);
$return["PUPoint"] = $row["PUPoint"];
$return["json"] = json_encode($return);
echo json_encode($return);
I've done some echoing/console.log and noticed that it's always passing the same Accommodation ID number (13) into booking_Modify.php. It doesn't change when I select a different option now. I don't know if it's because of the "selected" attribute applied to the option element now. Any ideas would be greatly appreciated
You have defined your $AccomodationID = 13; //For testing purposes before which is printed in every iteration of the while loop instead of the current ID. Probably you want to write $accommodation_Results['AccomodationID'] as the option value.

Getting value from dynamically created pop up menu

I have a menu that is dynamically created. When the user selects a value, I need to get that value and use it for a query statement. This is not a form, just a menu on the page.
I have:
<select name="topic" id="topic">
<option value="optiont" selected="selected">Select topic...</option>
<?php
while ($row = mysqli_fetch_array($sql))
{
echo "<option value=\"optiont$count\" name=\topic[]\">" . $row['topic'] . "</option>";
$count++;
}
?>
</select>
I want to know which option is selected. How can I do this??
This will get the value when you change the DDL:
$('#topic option').on("change", function () {
var opt_ID = $(this).val();
//Do something here using opt_ID as the value e.g.
window.location = '/URL/file.php?' + opt_ID;
});
Try this:
jquery:
var selvalue = $("#topic option:selected").val();
$.get( "demo.php?value="+selvalue, function(data) {
alert(data);
});
Demo.php:
<?php
$sel = $_GET['value'];
// write your query here
?>

send data on button click from javascript to database

So I have a php page that gets data from database and displays a table. Each td symbolises a seat in a movie theater. What i want to do is when a user clicks on one or more tds, and clicks send, the status column for each td in the database changes to 1 from 0(default). When the database is accessed next time, the td's with status=1 have a different color.
My code upto now is:
<div id="screen">SCREEN</div>
<div id="Seatings">
<?php echo "<table border='1'>
<tr>
<th>Seating</th>
</tr>";
$count=0;
echo "<tr>";
echo"<td id='Seat_rn'>A</td>";
while($row = mysql_fetch_array($sql))
{
if($count<10){
echo "<td id='Seat_A' class='count'>" . $row['Seat'] . "</td>";
}
$count++;
}
echo "</tr>";
$sql=mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
echo "<tr>";
echo"<td id='Seat_rn'>B</td>";
while($row = mysql_fetch_array($sql))
{
if($count>=10){
echo "<td id='Seat_B' class='count'>" . $row['Seat'] . "</td>";
}
$count++;
}
echo"</tr>";
echo "</table>";
?>
</div>
<input type="button" value="Done" name="done" onclick="window.close()">
My jquery code is:
$("td #Seat_A").click(function(){
$(this).css("background", "red");
});
$("td #Seat_B").click(function(){
$(this).css("background", "red");
});
$(document."done").click(function(){
alert(price:750 Baht);
})
I am nowhere near what i want and I'm sorry if any of my code is "amatuer-ish" but I am new to this and I have been trying very hard. Would appreciate any help that I can get.
First of all you have to add an ID to every TD on your table, i.e. Seat ID, For example:
echo "<td id='Seat_A' data-seat='". $row['id'] ."'class='count'>" . $row['Seat'] . "</td>";
Then send this ID to your PHP script with Ajax:
$("td #Seat_A").click(function(){
var seat_number = $(this).data("seat");
$.ajax({
type: 'POST',
url: "/take_a_seat.php",
data: 'seat_number='+seat_number,
success: function(data){
$(this).css("background", "red");
}
dataType: "json"
});
});
On the PHP script you have to do what you want to the seat with this ID and return true or false as a result. Let's suppose you have a field named reserved in your database table. You can get the unique ID and update that row to reserved = 1 for example.
Try this easy to use ajax script to accomplish your task
Features: you can show an gif img before send data to db in beforeSend section get response from php file in success section hide img after data inset in db in complete section and show successful or not success msg
var myVar = 'your desire data you want to send to db';
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"myVar="+myVar,
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
Javascript is client side. Your database is server side.. So you have to use php to change your database entries.
In short, if you want to execute PHP stuff without reloading page, than use AJAX. You can use it with your favorite JQuery.
This is an overview. For existing records you should some thing like this
<?php
$count=1;
$res = mysql_query("SELECT * FROM Seating_para_20 Where Seat > '10'");
while($row = mysql_fetch_array($sql)) {
if($row['status']==1) {
$tdcolor = 'red';
} else {
$tdcolor = 'blue';
}
?>
<td id="td-<?php echo $count;?>" sytle="background-color:<?php echo $tdcolor; ?>" onclick="reserveseat(<?php echo $count; ?>);" >
<?php
$count++;
}
?>
For changing after page load you will do ajax operation
<script type="text/javascript" language="javascript">
function reserveseat(count) {
$.ajax({
type: 'POST',
url: "bookseat.php",
data: '',
success: function(data){
$("#td-"+count).css("background-color", "red");
}
});
}
</script>
In bookseat.php you will change the status ... :-) Read about ajax from here . :-)

Can't make autocomplete work with ajax + jQuery

I'm trying to accomplish autocomplete task with the help of ajax (jQuery). Lets have a look at scripts
here is html =>
<input type="text" name="user_key" id="user_key">
here is javascript in the same file =>
<script type="text/javascript">
$(function(){
$("#user_key").autocomplete({
source: function(request,response){
var suggestions = [];
$.ajax({
url: "/ajax/autocomplete.php",
type: "POST",
data: {user_key:$(this).val()},
success: function(result){
$.each(result,function(i,val){
suggestions.push(val.name);
});
},
dataType: "json"
});
response(suggestions);
}
});
});
</script>
and here is php script from autocomplete.php file =>
if (!$connection->connect_errno){
if ($connection->set_charset("utf8")){
if ($r = $connection->query("SELECT name FROM users WHERE name LIKE '" . $_POST['user_key'] . "%'")){
for ($x=0,$numrows = $r->num_rows;$x<$numrows;$x++){
if ($row = $r->fetch_assoc()){
$array[$x] = array("name",$row['name']);
}
}
$r->free();
}
}
}
echo json_encode($array);
PS. It doesn't work. Please help , I've been trying to accomplish this task for the past 2 days,but can't get it to work. Thanks beforehand :)
$array[$x] = array("name",$row['name']);
this is making name and the value from the database both as the elements of the array()
change the code of autocomplete.php to
if (!$connection->connect_errno){
if ($connection->set_charset("utf8")){
if ($r = $connection->query("SELECT name FROM users WHERE name LIKE '" . $_POST['user_key'] . "%'")){
for ($x=0,$numrows = $r->num_rows;$x<$numrows;$x++){
if ($row = $r->fetch_assoc()){
$array[$x] = array("name"=>$row['name']);
}
}
$r->free();
}
}
}
echo json_encode($array);
This will make name as the key for the value fetched from the database
this will help you.
You need to take another look at the autocomplete docs but you will be able to find an answer here: jquery auto-suggestion example doesn't work

Categories