Post more than one parameter to ajax - php

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
}

Related

Automatic Form Completed With PHP Ajax

I have two textboxes namely no_id and customer_name. when the user enters no_id, customer_name is filled in automatically.
Form
<form>
<input type="text" name="no_id" onkeyup="autofill()" id="no_id">
<input type="text" name="customer_name" id="customer_name" readonly>
<!--textbox customer_name is readonly-->
</form>
Javascript
<script type="text/javascript">
function autofill(){
var no_id = $("#no_id").val();
$.ajax({
url: 'ajax.php',
data:"no_id="+no_id ,
}).success(function (data) {
var json = data,
obj = JSON.parse(json);
$('#customer_name').val(obj.customer_name);
});
}
</script>
ajax.php
include 'conn.php';
$npwp = $_GET['no_id'];
$query = mysqli_query($conn, "select * from ms where no_id='$no_id'");
$ms = mysqli_fetch_array($query);
$data = array(
'customer_name' => $ms['customer_name']);
echo json_encode($data);
The scripts above works for me.
Now I want to modify it.
When the no_id entered is NOT stored in the database, the customer_name box attribute becomes readonly=false, so the user can fill in customer_name box.
you can use jquery onChange method on no_id input to send no_id value and search it's stored in the database or not and return true or false (0 or 1)like this code:
$('#no_id')onchange(function(){
var no_id = $(this).val();
$.ajax({
url: 'ajax.php',
data:"no_id="+no_id ,
}).success(function (data) {
if(data == true){
$('#customer_name').attr('readonly');
}else if(data == false){
$('#customer_name').removeAttr('readonly');
}
});
});
I prefer to create another function for no_id onChange method
Here I am counting rows in mysql and if rows == 0, then removing readonly attribute
Javascript
<script type="text/javascript">
function autofill(){
var no_id = $("#no_id").val();
$.ajax({
url: 'ajax.php',
data:"no_id="+no_id ,
success : function (data) {
var json = data;
obj = JSON.parse(json);
if(obj.success=='true') {
$('#customer_name').val(obj.customer_name).attr("readonly", true);
} else {
$('#customer_name').val("").attr("readonly", false);
}
}
})
}
</script>
AJAX.php
include 'conn.php';
$npwp = $_GET['no_id'];
$query = mysqli_query($conn, "select * from ms where no_id='$npwp'");
if(mysqli_num_rows($query) >= 1 ) {
$ms = mysqli_fetch_array($query);
$data = array('customer_name' => $ms['customer_name'], 'success'=>'true');
echo json_encode($data);
} else {
$data = array('success'=>'false');
echo json_encode($data);
}

ajax dropdown box when a variable exists

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'];

Ajax get value from php

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...

Multiple search option in PHP MySQL AJAX

I want to put multiple search option in PHP file through AJAX method. With one search (Search by name )option its working fine but when I put another search field ( Like Search by gender) then its search only with gender only. I can't do search for both of them at a same time.
This is main index.php file
This is tablepage.php file where ajax method calling + display data
<script charset="UTF-8">
function pagination(page)
{
var search = $("input#fieldSearch").val();
var record = $("select#pageRecord").val();
var gender = $("select#fieldSearch1").val();
if (search!=="")
{
dataString = 'starting='+page+'&gender='+ gender+'&name='+search+'&perpage='+ record+'&random='+Math.random();
}
else{
dataString = 'starting='+page+'&perpage='+record+'&random='+Math.random();
}
$.ajax({
url:"tablepage.php",
data: dataString,
type:"GET",
success:function(data)
{
$('#divPageData').html(data);
}
});
}
function loadData()
{
var dataString;
var search = $("input#fieldSearch").val();
var record = $("select#pageRecord").val();
var gender = $("select#fieldSearch1").val();
dataString = '&gender=' + gender + 'name='+ search + '&perpage=' + record;
$.ajax({
url: "tablepage.php",
type: "GET",
data: dataString,
success:function(data)
{
$('#divPageData').html(data);
}
});
}
</script>
<?php
error_reporting(E_ALL^E_NOTICE);
include('pagination_class.php');
include('connect.php');
if (isset($_GET['name']) and !empty($_GET['name'])){
$name = $_GET['name'];
$sql = "select * from fmaf where name like '%$name%'";
}
if (isset($_GET['gender']) and !empty($_GET['gender'])){
$gender = $_GET['gender'];
$sql = "select * from fmaf where gender = '$gender'";
}
else{
$sql="select * from fmaf left join status ON fmaf.id = status.sid GROUP BY fmaf.id ";
}
if(isset($_GET['starting'])){ //starting page
$starting=$_GET['starting'];
}else{
$starting=0;
}
$recpage=$_GET['perpage'];
$obj = new pagination_class($sql,$starting,$recpage);
$result = $obj->result;
?>
this is pagination.js file
$(document).ready(function(){
$('#divLoading').ajaxStart(function(){
$(this).fadeIn();
$(this).html("<img src='loading.gif' /> ");
}).ajaxStop(function(){
$(this).fadeOut();
});
loadData();
function loadData()
{
var dataString;
var search = $("input#fieldSearch").val();
var record = $("select#pageRecord").val();
var gender = $("select#fieldSearch1").val();
dataString = '&gender=' + gender + 'name='+ search + '&perpage=' + record;
$.ajax({
url: "tablepage.php",
type: "GET",
data: dataString,
success:function(data)
{
$('#divPageData').html(data);
}
});
}
$("form#formSearch").submit(function()
{
loadData();
return false;
});
});
Rest of pagination.class.php file is working fine.
I just checking for singe GET parameter and if user want to find with name and gender vise than in that case i just add this code
if( !empty( $_GET['name']) && !empty( $_GET['gender']))

Insert parsed JSON into html

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();
});

Categories