i already search for this question but the result is a litte confusing because today is my first time to encounter ajax and most answer is ajax. so i decided to post a question which is my work and trying to have someones help from here to guide me about ajax. this is for my project need some help please
this is my query for getting the values from database and display it to my dropdownlist
<?php
include('config.php');
$sql="SELECT food FROM menu";
$lists=mysql_query($sql);
?>
this is my dropdown list... i fetch data from my database to have my values in dropdown list
<select name="fname" id='mySelect' value='Foodname'>
<?php
while($food = mysql_fetch_array($lists)) {
echo '<option value='.$food['food'].'>'.$food['food'].'</option>';
}
echo '</select>';
?>
now i want to show the price of the selected food in the dropdown list.. i want it to show in input text so i am able to edit it if i want to
<input type='text' class="form-control" name='prc'>
this is my database
for select options give value as the database Id, like this
echo '<option value='.$food['id'].'>'.$food['food'].'</option>';
considering as id to be autoincrement column in DB.
Then write ajax like this.
$(document).ready(function() {
$("#mySelect").change(function(){
var val = $('#mySelect option:selected').val();
$.ajax({
url: "path to php file to get the price",
type: "POST",
dataType: "HTML",
data: {"id": val}
async: false,
success: function(data) {
// for textbox add id as price
$("#price").val(data);// data will have the price echoed in somefilename.php
}
});
});
});
Lets say the url in ajax is somefilename.php
so in somefilename.php, yyou shud write query like this
<?php
include('config.php');
$id = $_POST['id'];//same name as in ajax data
$sql="SELECT price FROM menu where id = $id";
// echo the price here
?>
What ever you echo here, it will come in ajax success function with parameter 'data', then you can assign to the required textbox as i have done in success function()
Related
I need to get the value of the selected item on the drop down selection populated from sql database. Then that value is needed in the sql statement to get the specific record.
I already populated the drop down selection. Code below
<select name="year" id="year">
<?php
$query = mysql_query("SELECT distinct Year(fromdate) FROM emp WHERE empcode='$emp' order by Year(fromdate) desc");
while ($row = mysql_fetch_array($query)){
$year = $row[0];
echo "<option value=\"".$year."\">".$year."</option>";
}
?>
</select>
This is the php code for me to get the record using the value from the drop down.
<?php
$sql = mysql_query("SELECT salary FROM emp WHERE empcode='$emp' and Year(fromdate) = '$year'");
$row = mysql_fetch_array($sql);
$salary=$row[0];
?>
Then after that I need to pass the result to a textbox
<input id="salary" name="salary" value="<?php echo $salary; ?>">
What is the code needed for me to pass the selected item value from drop down "year" to PHP variable $year for sql statement? I already looked here in Stack Overflow for the answers but there is no question that look like mine.
What is wrong with people it needs sql why vote down
Do an ajax call to your php file, listening to your select onchange event, like so:
$('#year').on('change', function() {
$.post( "path/file.php", {
year: $(this).val()
})
.done(function( data, status ) {
console.log('data: '+data+' status: '+status);
if(status == 'success'){
//pass to your input ?
//data is what your php file will echo/output
$('#salary').val(data);
}else{
//how do you want to handle http error ?
}
});
});
If you want to get select box value without refreshing page then you need to do code with AJAX.
http://api.jquery.com/jquery.ajax/
On change please pass the year value to AJAX and then in AJAX file write down query for salary getting and after success full result put this value in salary filed using jQuery function
I am trying to make an ajax request to my PHP file.
The ajax request occurs when my "Country" select option menu changes. The result is suppose to be a new select option menu titled "State Province" and the options would be based off the choice made in the "Country" select option menu.
This is what I want it to look like:
The problem I'm having is when the ajax is making a request to the PHP, the PHP seems to be returning an empty array:
Does anyone know what might be wrong?
Thank you!
HTML for the select option:
<select name="Country" class="form-control input-sm" id="Country">
</select>
Ajax code with the onchange function:
$("#Country").on("change",function(){
var val = $('#Country').val();
performAJAX(val,'Country','StateProvince');
});
function performAJAX(choice,prevSelect,newSelect){
$.ajax({
type: "post",
url: "select-creation.php",
data: {choice: choice, prevSelect: prevSelect,newSelect: newSelect},
dataType: "json",
success: function(data){
var obj = $.parseJSON(data);
console.log("meow meow");
}
});
}
PHP code:
<?php session_start();
try{
$choice = $_POST['choice'];
$prevAttri = $_POST['prevSelect'];
$nxtAttri = $_POST['newSelect'];
$data = array();
$sql = 'SELECT '.$nxtAttri.' FROM agents WHERE '.$prevAttri.' = :userChoice';
include_once $_SERVER['DOCUMENT_ROOT'].'/inc/Database.class.php';
$db = new Database();
$conn = $db->getConnection();
$query = $conn->prepare($sql);
$query->bindValue(':userChoice',$choice,PDO::PARAM_STR);
if($query->execute()){
$data = $query->fetchAll(PDO::FETCH_ASSOC);
}//stmt
return json_encode($data);
}catch(PDOException $e){
echo $e->getMessage();
}
?>
Your code return json_encode($data); seems to be nothing or invalid because your code doesn't use a function.
Just use echo json_encode($data);
In the ajax side, you don't need to use $.parseJSON(data); because you already specify the dataType to json it will immediately convert the data response by PHP to an object type.
For an ‘Edit’ modal, I initiate an ajax call to the php script named getSelectedMember.php that bring the information from the table items (Table 2).
<?php
require_once 'db_connect.php';
$memberId = $_POST['member_id'];
$sql = "SELECT * FROM items WHERE itemID = $memberId";
$query = $connect->query($sql);
$result = $query->fetch_assoc();
echo json_encode($result);
?>
This formulation_fk is in the table items a value of a select option from another table named formulation (Table 1).
This is code of 'edit.php' :
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text"><br>
</div>
<div>
<label>Formulation</label>
<select id="editFormulation">
</select>
</div>
<button type = "submit">Save changes</button>
</form>
My question is while updating a single item, how can I pass the select options from the formulation table in my edit form where the select option value will be the formulation_fk from the table items?
And this is my ajax call:
$.ajax({
url: 'getSelectedMember.php',
type: 'post',
data: {
member_id: itemID
},
dataType: 'json',
success: function(response) {
$("#editName").val(response.name);
$("#editFormulation").val(response.formulation_fk);
$(".editMemberModal").append( ? ? ? ? ? ? )
}
});
For clarification of my question, let's think that to edit Water, the action flow would be like this:
Click the edit button for ‘Water’.
Ajax call to getSelectedMember.php to get the name (Water) and
formulation_fk (1).
On response, Name field will output ‘Water’
and Formulation filed will output a dropdown select from
formulation table where option value = “1”
Something like this image below.
I have been trying to solve it for a while but I'll really appreciate any suggestion or expert help. Thanks in advance.
The PHP code needs to return an array of all the formulations, in addition to the formulation_fk from the items table.
$memberId = $_POST['member_id'];
$sql = "SELECT * FROM items WHERE itemID = $memberId";
$query = $connect->query($sql);
$result = $query->fetch_assoc();
$sql = "SELECT * FROM formulation";
$query = $connect->query($sql);
$formulations = array();
while ($row = $query->fetch_assoc()) {
$formulations[] = $row;
}
$result['formulations'] = $formulations;
echo json_encode($result);
Then the AJAX code can fill in the <select> before setting its value.
success: function(response) {
$("#editFormulation").empty(); // Clear out previous value
$.each(response.formulations, function() {
$("#editFormulation").append($("<option>", {
value: this.formulationID,
text: this.formulation_name
}));
});
$("#editFormulation").val(response.valuation_fk);
$("#editName").val(response.name);
}
So Ive been struggling with this problem all day and can't seem to get around it.
I need to call a php query whenever an option from a dropdown menu is selected.
<select class="selectpicker" id="headSelector">
<?php
$cname = $_GET['cname'];
$linkID = mysql_connect("localhost","USER","PASS");
mysql_select_db("USR", $linkID);
$SQLCurr = "SELECT `AName` FROM `Char-Armor` WHERE `CName` = '$cname' AND `AType`= 'Head'";
$currHeadValues = mysql_query($SQLCurr, $linkID);
$currRow = mysql_fetch_row($currHeadValues);
$curr = $currRow[0];
if($curr == '' || $curr == NULL){
$curr = 'None';
}
$SQLHead = "SELECT AName FROM `Armor` WHERE AType = 'Head'";
$allHeadValues = mysql_query($SQLHead, $linkID);
echo "<option>".$curr."</option>";
while($row = mysql_fetch_assoc($allHeadValues)){
echo "
<option>".$row['AName']."</option>
";
}
?>
</select>
The php part needs to take the 'AName' from the option and use it to insert into a table.
I have done a lot of reading about AJAX but I do not quite understand how it is supposed to work. I think it is like html -> js -> Ajax -> php
I need it to stay on the same page when an option is selected.
Any explanation would be great, thanks!
Here's what you can do.
1). As soon as an option is selected, run a jquery onchange event and get the value of the selected option.
2). Now, run an ajax request with the value of the selected value and post this data to a backend php file.
3). Now on this backend php file, receive data and process (run the query).
Code Sample.
Change your option line in this way.
<option value="$row['AName']">".$row['AName']."</option>
jQuery-Ajax
$("#headSelector").change(function(e){
//get the value of the selected index.
value = $(this).val();
//make an ajax request now
$.ajax({
url: 'yourPhpBackendScript.php',
type: 'POST',
data: {value: value},
success:function(response)
{
alert(response);
}
})
})
yourPhpBackendScript.php
//You can now receive the selected value as $_POST['value'];
//get the value now
$value = $_POST['value'];
//you can apply validations if you want.
//Now, run the query and send a response. Response can be a simple message like data submitted etc. So
runQueryHere
echo "inserted"; //response returned to ajax rquest
First of all, return the string like this:
$options_arr = '';
while($row = mysql_fetch_assoc($allHeadValues)){
$options_arr .= "<option>".$row['AName']."</option>
";
}
echo $options_arr;
Use the change event like this:
$("#headSelector").change(function(){
$.ajax({
data: '',
url: 'your_url',
type: 'POST',//Or get
success: function(options_array){
$("#headSelector").empty().append(options_str);
}
});
});
I'm working on creating a simple online booking system using PHP and AJAX.
The current layout is:
Each booking grabs a preset list of items then users can add additional items that they need.
To do this I have set up an AJAX button that calls a new drop down list each time its clicked. (This means a page could have 1 additional item or even 20, depending on how many they need.)
Once the additional items have been selected, they can then submit the form and will be guided to a confirmation page that is meant to list what they have chosen.
The issue:
None of the data is being carried through from any of the drop down lists that get added.
My AJAX script and php code on page 1 is:
<script>
function changeIt()
{
$.ajax({
type: "POST",
url: "details.php"
}).done(function( result ) {
$("#msg1").append( "" +result);
});
}
</script>
<form name ="addequip" id="addequip" action="confirmbooking.php" method="post">
<input type='button' value="Add Item" onClick="changeIt()"/>
<div id="msg1"></div>
<input type='submit' value='submit'/>
details.php:
<?php
require_once("dbconn.php");
$sql = "SELECT REFERENCE, DESCRIPTION FROM descEquip";
$result = mysql_query($sql,$conn);
?>
<select name="equip">
<?php while ($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row["REFERENCE"];?>"><?php echo $row["DESCRIPTION"];?></option><?php } ?>
</select>
And lastly my confirmation page is:
<?php $item = $_POST['equip']; ?>
<?php echo $item ?>
I'm not too sure if i need to add something to the AJAX script in order for this to work as intended or if something needs to be changed in the details.php? (I'm very new to AJAX)
I have viewed a previous question 'passing form data to mySQL through AJAX' and I couldn't make it work for me.
Lastly, for additional lists (when more than 1 item is required) do I need to have a feature that states each equip list have a different name? likename="equip<?php echo $i ?> where $i = 1++;
Any tips or examples would be appreciated,
thanks.
Never assume all will work as you want it - check if sth goes wrong in your code:
var jqxhr = $.ajax(
{
type: 'GET',
async: false,
url: 'details.php',
success: function(data, textStatus /* always 'success' */, jqXHR)
{
// ok if we are here it means that communication between browser and apache was successful
alert( 'on_ajax_success data=[' + data + '] status=[' + textStatus + ']' );
$("#msg1").innerHTML( result );
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert( 'ERROR: [operation failed]' );
}
});
Moreover - use Firefox with Firebug installed so that you can see your ajax queries/responces.