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...
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
}
I have a form named as my-form. Inside of it has a 2 textbox and 1 multiple select tag. I'm unable to get all the passed data in PHP.
textbox1 has a name "tname"
textbox2 has a name "tcode"
multiple select has a name "tsubteam"
I am able to pass all the data but i don't know how to get all the data in PHP
var arr = [];
$('#tsubteam > option').each(function(){
arr.push(this.value +","+this.text)
});
$.ajax({
type: "POST",
url: "modify_team.php",
dataType: "json",
contentType: "application/x-www-form-urlencoded; charset=UTF-8;",
data: `$('#my-form').serialize()+"&id="+getQueryVariable('id')+"&subteam="+JSON.stringify(arr),
cache: false,
success: function(data)
{
console.log(data)
},
error: function(xhr, ajaxoption, thrownerror)
{
alert(xhr.status+" "+thrownerror);
}
And in PHP:
<?php
$tcode = $_POST['tcode'];
$tname = $_POST['tname'];
$id = $_POST['id'];
$subteam = $_POST['subteam'];
?>
I already resolved the main problem here.
All I did was change the
dataType: "json"
into
dataType: "text"
And modify the retrieving code of each option tag into
$('#tsubteam > option').each(function(){
item = {}
item["id"] = this.value
item["name"] = this.text
arr.push(item)
});
In PHP:
$tcode = $_POST['tcode'];
$tname = $_POST['tname'];
$id = $_POST['id'];
$subteam = json_decode($_POST['subteam'], true);
foreach($subteam as $k=>$v)
{
$subteam_name = $v["name"];
$subteam_id = $v["id"];
}
The output of passed data in AJAX
tcode=CMPSS&tname=Compass&id=1&subteam=[{"id":"1","name":"Compass Team A"},{"id":"2","name":"Compass Team B"},{"id":"3","name":"Falcon"},{"id":"4","name":"GPON"},{"id":"5","name":"TTV"},{"id":"6","name":"INFRA"},{"id":"7","name":"OSS"}]
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'];
I got two dropdowns and i need to get both values to get data from my database.
$(document).ready(function(){
$('.fabric').on('change',function(){
var fabricID = $(this).val();
console.log("fabric id_price is " + fabricID); //debugging
if(fabricID){
$.ajax({
type:'GET',
url:'cart_functions.php',
dataType: 'json',
data: {
fabric_id: fabricID
},
success:function(html){
$('.icms' + id).text(data.val);
}
});
//closing tags
$('.size').on('change',function(){
var sizeID = $(this).val();
if(sizeID){
$.ajax({
type:'GET',
url:'cart_functions.php',
dataType: 'json',
data:{
size_id: sizeID
},
success:function(html){
$('.icms' + id).text(data.val);
}
});
//closing tags
i'm sending these both values to my calculate.php
<?php header('Content-Type: application/json');
include_once '../incluedes/conn_cms.php';
if(isset($_GET["size_id"],$_GET["fabric_id"])){
$size_id=$_GET["size_id"] ;
$fabric_id=$_GET["fabric_id"] ;
$query3 =" SELECT * FROM valores_almofadas
WHERE size='$size_id'
AND price_id ='$fabric_id'";
$result = mysqli_query($conn,$query3);
while($rows = mysqli_fetch_assoc($result)){
if($_SESSION['estado'] == 'SP'){
$ICMS = $rows['icms_7'];
}else{
$ICMS = $rows['icms_12'];
}
$_SESSION['icms']=$ICMS;
} echo json_encode($_SESSION['icms']);
}
?>
So i select a fabric and then a size fabric value is my id and size is 50 or 45.
fabricid= 1 and size = 50 <-- i am sending this to my calculate.php
So i want to get back the value into a session.
and the result must be on a td..
<td class="icms'.$id.'">R$:'.$_SESSION['icms'] .'</td>
But its not working, i'm not good at ajax, can you tell me whats wrong and how can i fix these mess?
Make sure both values are always sent with the request
$(document).ready(function() {
$('.fabric, .size').on('change', sendData);
function sendData() {
var fabricID = $('.fabric').val();
var sizeID = $('.size').val();
if ( fabricID !== "" && sizeID !== "") {
$.ajax({
type : 'GET',
url : 'cart_functions.php',
dataType : 'json',
data : {
fabric_id: fabricID,
size_id: sizeID
}
}).done(function(html) {
$('.icms' + this.id).text(data.val);
});
}
}
});
You are never sending both values in any ajax call, only one or the other. You need to additionally get the value for fabric_id in your .size change event and vice versa.
Hi I have a select box that when it is changed I want the value in a database to be updated via Ajax. Using the console I can see that my saveedit2.php file is not being called.
Select Box
<form><select id="workingpattern">
<?php
if(isset($workingpatterns) && !empty($workingpatterns)){
foreach($workingpatterns as $k4=>$v4) {
?>
<option value="<?php echo $workingpatterns[$k4]["workingpatternid"]; ?>">
<?php echo $workingpatterns[$k4]["text"]; ?></option>
<?php }}?>
</select></form>
Ajax:
<script>
$(document).ready(function(){
$('#workingpattern').change(function(){
var e = document.getElementById("workingpattern");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "saveedit2.php",
type: "post",
data: value,
success: function(data) {
console.log(data);
}});
});
</script>
SaveEdit2.php
<?php
require_once("connect_db.php");
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
?>
There are a few issues that I see. First, I would use 'this' to get the element and use jQuery to get the value since you are using it already. Secondly, you need a name for the value in the data set:
$('#workingpattern').change(function(){
var value = $(this).val();
$.ajax({
url: "saveedit2.php",
type: "post",
data: 'value='+value,
success: function(data) {
console.log(data);
}
});
});
Try
Ajax
$('#workingpattern').change(function(){
var value = $("#workingpattern").val();
$.ajax({
dataType: "json",
url: "./saveedit2.php",
data: {'value':value},
success: function(data){
if(data['result']=="ok")
alert("Done");
else
alert("Error");
}
});
SaveEdit2.php
<?php
require_once("connect_db.php");
$ajax_result = "error";
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
if($result)
$ajax_result = "ok";
echo json_encode(array('result'=>$ajax_result));
?>