I am trying to make an ajax call for the an dropdown box(dynamic)
when the variable $place is available it will make an ajax call and populate
the dropdown box.
I am trying to pass the variable $place to listplace.php and encode it in json data and get the datalist values but not sure the encoded json file is correct
I just given a try and not sure below code works, please help.
Dropdown box
<select>
<option selected disabled>Please select</option>
</select>
Ajax call
<?php if(isset($_GET['place']) && $_GET['place'] !='') {?>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $place ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
var $el = $("#name");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
}
});
</script>
<?php } ?>
listplace.php
<?php
$sql = #mysql_query("select placename from employee where placename= '$place'");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
Change your AJAX call to the following.
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<?php } ?>
And your PHP to
<?php
$place = $_POST['place'];
$sql = #mysqli_query($conn,"select placename from employee where placename= '$place'");
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r['placename'];
}
if (count($rows)) {
echo json_encode(['option'=> $rows]);
}else {
echo json_encode(['option'=> false]);
}
var request;
// Abort request is previous doesnt end
if (request) {
request.abort();
}
// Make request
request = $.ajax({
type: "POST",
url: 'listplace.php',
dataType: 'json',
// One option is passed php into script
data: {
department: '<?= $place ?>'
}
// but I prefer this solution
// html markup:
// <div style='display:none;' data-place>YOUR_PLACE</div>
// or hidden input, in final it doesnt matter...
data: {
department: $('[data-place]').text()
}
});
request.done(function(response, textStatus, jqXHR){
// check response status
// HTML Markup:
// <select id='select'></select>
var select = $('#select');
select.empty();
// add default option first one disabled, selected, etc.
// data are rows in your situatios
// append data to select with lodash for example
// _.map(response.rows, function(row){...}
// jQuery each
// $.each(response.rows, function(index,row){...}
})
request.fail(function(){
// do something
})
request.always(function(){
// do something
})
in your .php is missing line
$place = $_POST['department'];
Related
PHP code :
<?php include_once 'includes/dbconnect.php';
$name = $_POST['name'];
$year = $_POST['year'];
$term= $_POST['term'];
$semester= $_POST['semester'];
$class= $_POST['class'];
$query = "SELECT * FROM hostelfee WHERE RegNo = '$name' AND PayYear='$year' AND PayTerm='$term' AND PaySemester='$semester' AND PayClass='$class' ";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
echo json_encode($row);
}
?>
<script type="text/javascript">
function ch() {
$(document).on('change',function() {
name = $('#name option:selected').val();
year = $('#year').val();
term = $('#term').val();
semester = $('#semester').val();
class = $('#class').val();
$.ajax({
type : 'POST',
dataType: 'json',
data: {name : name,year : year,term:term,semester:semester,class:class},
url:'getBalance.php',
success:function (result) {
$('#Year').val(result['PayYear']);
$('#student-balance').val(result['Balance']);
}
});
});
}
</script>
I have a payment page where I first have to select student No, Year and term, then the balance of that period will be selected.
The challenge is that I can only send one parameter from PHP to ajax. How to use more than one parameter?
you can use serialize.
<script type="text/javascript">
function ch() {
$(document).on('change',function() {
//use serialize to get multiple value of form. Add your form id - #form. you can also use form name, class
form_data = $('#form').serialize();
$.ajax({
type : 'POST',
dataType: 'json',
data: {action : 'hostelfee',formdata : form_data},
url:'getBalance.php',
success:function (result) {
$('#category').val(result['PayYear']);
$('#student-contact').val(result['Balance']);
}
});
});
}
</script>
In getBalance.php file use parse_str to get the serialize data in array.
if($_POST['action'] == 'hostelfee'){
parse_str($_POST['formdata'], $form_data);
//here will get all the parameter like name, year,term,semester and class etc in array.
print_r($form_data);
//add your code here
}
Ajax
$(document).ready(function(){
$("#diklat").change(function(){
var diklat = $("#diklat").val();
$.ajax({
url: "function.php",
data: {'action': 'diklat'},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
$get_action = $_GET['action'];
if($get_action=='diklat'){
$diklat = $_GET['diklat'];
$angkatan = mysql_query("SELECT id,name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan)){
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
The value didnt include in my ajax, ajax only read echo. how to get that value
You have written data: {'action': 'diklat'} but it should dilkat without quotes as its variable so in php you will get value in $_GET['action'].
Ajax
$(document).ready(function(){
$("#diklat").change(function(){
var diklat = $("#diklat").val();
$.ajax({
url: "function.php",
data: {'action': diklat},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
if($_GET['action'] == 'diklat'){
$diklat = $_GET['action'];
$angkatan = mysql_query("SELECT id,name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan)){
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
You should pass 2 variables, one action and another id (diklat)
Ajax:
$(document).ready(function(){
$("#diklat").on('change', function(){
var diklat = $("#diklat").val();
$.ajax({
type: "POST",
url: "function.php",
data: {'action': 'diklat', 'diklat':diklat},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
$action = isset($_POST['action']) ? $_POST['action'] : '';
if ($action == 'diklat')
{
$diklat = isset($_POST['diklat']) ? $_POST['diklat'] : '';
$angkatan = mysql_query("SELECT id, name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan))
{
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
Two things:
For a GET request, to ask a PHP server, data should be URL-encoded (as you see here, query string is just appended to the URL...) So tell 'data' : '?action=diklat' ...
EDIT : Jquery automatically converts object to Url-encoded query string... So It work with array ! I'm confusing with angular's $http...
And also, the parameter will be in $_GET['action'] (because action is parameter name, and diklat the value... So PHP convert query string to associative array, with parameters names as keysn and values as values...
I have a page with list of buttons, when each button is clicked, it's value is captured and ajax call in made. PHP does DB updates on ajax call. I want to return data to ajax call. The data is obtained from DB. But I'm unable to point out what's the error in below code.
Here is PHP code:
if (isset($_GET['val']))
{
$chapter_id=$_GET['val'];
$sql= "SELECT file_name,edit_link,name,email FROM `chapter_list` where chapter_id='$chapter_id'";
$result = mysql_query($sql,$rst);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
}
$update=mysql_query("UPDATE `chapter_list` SET `status` = '$update_status' WHERE `chapter_list`.`chapter_id` = '$chapter_id';");
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
}
Here is the AJAX request
$(document).ready(function(){
$('.btn').click(function(){
var clickBtnValue = $(this).val();
$.ajax ({
url: '',
data: { val : clickBtnValue},
dataType:'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I'm not getting the alert!
Try like this.
Maybe response data is null.check your php code(query lines).
Here My php code is :
if (isset($_GET['val'])) {
$vol_name = 'dummy_name';
$vol_email = 'dummy_email';
$vol_link = 'dummy link';
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
exit;
}
My javascriptcode is :
<input type="text" class="btn" value="test" />
<script type="text/javascript">
if('addEventListener' in document){
document.addEventListener("DOMContentLoaded", function(e){
//dom loaded
$(document).on("click",".btn",function(e){
e.preventDefault()
var e_val = $(this).val();
console.log('my value is :' + e_val);
if(e_val){
$.ajax({
type: "get",
dataType: 'json',
url: 'here your url or slash',
data: { // request e_val
val : e_val,
}
}).done(function(xhr) {
// console.log(xhr);
if(xhr.name){
alert('response data is '+ xhr.name);
}
})
}
})
},false)
}
</script>
try this..
while($row = mysql_fetch_assoc($result))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
$ret[$vol_name]= array(
'email'=>$vol_email,
'link'=>$vol_link
);
}
then use in the return statement..
echo json_encode($ret);
You can send parameters in HTML
<button class="btn" atribute_id="21543">Button</button>
$(document).ready(function() {
$('.btn').click(function() {
var Value_of_Btn= $(this).attr("atribute_id"); <-------
$.ajax({
url: '',
data: {
val: clickBtnValue
},
dataType: 'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I've tried many methods, from tutorials and other questions posted but nothing seems to work. I'm trying to get data sent from php into divs and variables with jquery. I have the array set up on the php side, and everything works fine but on the jquery side i always get an unexpected identifier error or the div is left blank or both
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_rowtest = parseInt(var_numdatacheck);
function waitupdate(){
$.ajax({
type: 'POST',
url: 'update.php',
data: {function: '3test', datacheck: var_rowtest},
dataType: "json",
success: function(check) {
var data = JSON.parse(check);
var_rowtest = data[id]; // sets the variable numcheck as the new id number
$('#datacheck').html(data[0]); // I've confirmed data[0] has a value but the div is left blank
}
error: function(msg) {
console.log(msg)// here i get an unexpected identifier error
}
});
}
$(document).ready(function() {
waitupdate();
});
The output from the php is
{"id":"4","0":"Name"}
here is the actual php code
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$check['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery)){
?>
<?php $check[]= $row['First Name']; ?>
<?php
}
echo json_encode($check);
}
?>
</div>
</ul>
This will work for you,
var var_rowtest = data['id'];
var value= data[0];
set variable var_rowtest and value in your div as needed.
I guess var_rowtest = data[id]; is not a proper syntax, use above syntax
Please try and change your variable names, and that error function declared in the $.ajax threw a JS error for me.
Another thing that is unnecessary is the JSON.parse - I made the PHP script called "update.php" return back the correct header:
<?php header('content-type: application/json');?>
This code works:
var numDataCheck = 1,
rowTest = parseInt(numDataCheck);
function waitupdate() {
$.ajax({
type: 'POST',
url: 'update.php',
data: {function: '3test', datacheck: rowTest}, dataType: "json",
success: function(data) {
rowTest = data.id;
$('#datacheck').html(data[0]);
}
});
}
$(document).ready(function() {
waitupdate();
});
acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}