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']))
Related
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);
}
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 am trying to get a form to work, but when I call ti with ajax, it will not work.
// ----------------------------EDIT----------------------------
I actually found exactly what I was looking for while browsing around.
jQuery Ajax POST example with PHP
I just have one question, would this be the best way to get the data, or could I call it from an array somehow?
post.php
$errors = array(); //Store errors
$form_data = array();
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$_POST['name'])); //Get data
if (!empty($errors)) {
$form_data['success'] = false;
$form_data['errors'] = $errors;
} else {
$form_data['success'] = true;
$form_data['country'] = $query['country'];//Have a bunch of these to get the data.
$form_data['city'] = $query['city'];//Or is there an easier way with an array?
$form_data['zip'] = $query['zip'];
// Etc, etc
}
echo json_encode($form_data);
Then in index.php just call it via:
$('.success').fadeIn(100).append(data.whatever-i-have-in-post);
// ----------------------------v-ORIGINAL-v----------------------------
This is I have so far. At the bottom you can see I have an if statement to check if I could get the results from post, but it always results in "unable to get country" (I'm checking with google.com). I don't know if I am doing it correct or not. Any ideas?
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString
});
}
return false;
});
});
</script>
<form id="form" method="post" name="form" style="text-align: center;">
<input id="name" name="name" type="text">
<input class="submit" type="submit" value="Submit">
<span class="error" style="display:none">Input Empty</span>
<?php
include_once('post.php');
if($query && $query['status'] == 'success') {
$query['country'];
} else {
echo 'Unable to get country';
}
?>
</form>
Post.php
$ip = $_POST['name'];
//$ip = isset($_POST['name']); // I dont know if this makes a difference
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
Try with this after changing the dataString = {name: name}
$(".submit").click(function() {
var name = $("#name").val();
var dataString = {name: name};
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(response) {
// Grab response from post.php
}
});
}
return false;
});
The best way i like to grab the JSON data from ajax request. You can do it by slightly changes in your script.
PHP File
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
echo json_encode(array('status'=>true, 'result'=>$query)); // convert in JSON Data
$(".submit").click(function() {
var name = $("#name").val();
var dataString = {name: name};
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
dataType: 'json', // Define DataType
success: function(response) {
if( response.status === true ) {
// Grab Country
// response.data.country
// And disply anywhere with JQuery
}
}
});
}
return false;
});
I am trying to make an ajax call on click on anchor tag dynmically generated from $.each loop for a JSON response.
For Information : #records is my table and .update is the class of anchor tag in that table.
Please be informed that the table is generated dynamically.
Now the problem is that my ajax call is returning nothing even i have checked it error: but no response received. I have tried alerting my var data just before the ajax call and it worked.So the problem starts from the ajax call. Moreover, my server side code is running fine.
// Update existing customers
$("#records").on('click', ".update", function() {
var data = '?'+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data: data,
success: function(response) {
console.log(response);
}
});
});
Thanks in advance.
For reference below is the code that generates the table.
// Function to make datagrid
function getRecords() {
$.getJSON("viewcustomers.php", function(data) {
var items = [];
var xTd = '';
var xTr = '';
$.each(data, function(key, val) {
var c = 0;
var id = 0;
$.each(val, function(key1, val1) {
if (c == 0)
{
id = val1;
}
c++;
xTd += '<td>' + val1 + '</td>';
});
xTd += '<td>Edit</td>';
xTd += '<td>Delete</td>';
xTr = '<tr>' + xTd + '</tr>';
items.push(xTr);
xTd = '';
xTr = '';
});
$("#records").append(items);
});
}
Updated the server side code:
page url : localhost/hotel/viewcustomers.php
/**
* Fetch single row for the purpose of update / delete.
*/
if(isset($_GET['update'])){
$customer = new Customers;
$Id = $_GET['update'];
$customer_single = $customer->View_Single_Customer($Id);
echo json_encode($customer_single);
unset($customer);
}
This line is not used the right way var data = '?'+ $(this).attr('id');
Change it like this: var my_id = $(this).attr('id');
Then update the line data: data with data : {id:my_id}
Complete code :
$("#records").on('click', ".update", function() {
var my_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data : {id : my_id},
success: function(response) {
console.log(response);
}
});
});
Or do it like this:
$("#records").on('click', ".update", function() {
var param = '?id='+ $(this).attr('id'); /*notice that I have added "id=" */
$.ajax({
type: "GET",
url: "viewcustomers.php" + param,
/* remove the data attribute */
success: function(response) {
console.log(response);
}
});
});
Modify it as
$("#records").on('click', ".update", function() {
var request = '?id='+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php" + request,
success: function(response) {
console.log(response);
}
});
});
I used thickbox components in Joomla. I am submitting form using jQuery ajax but jQuery not getting values after click on submit buttons. I used
and created script.js file containing :
jQuery(document).ready(function(){
jQuery('.wp_btn').click(function() {
var id = $j(this).attr('id');
var url = $j(this).attr('value');
if (document.cookie.indexOf('visited=true') == -1) {
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
jQuery("#dwnlnk").val(url);
TB_show('', '/#TB_inline?KeepThis=true&id=9876asdvfrty54321&height=250&width=350&inlineId=mypopup&caption=Subscription', '');
}else{
window.location = url;
}
});
//
jQuery(document).on('submit', '#subscription',function(){
return false;
});
jQuery(document).on('click', '#btnSubmit',function(){
var url = jQuery('#dwnlnk').val();
var txtname = $j('input[name=txtname]').val();
var txtemail = $j('input[name=txtemail]').val();
jQuery.ajax({
type: 'POST',
url: 'whitepapers/',
data: jQuery('#frmsubscription').serialize(),
success: function(data) {
alert(data);
//if(data == 'true') {
window.location = url;
//}
}
});
});//end click
});
I already tried document.getElementById('txtname').value but its not getting value of textbox. When I entered static value then its getting value.
You have to use jQuery or $ to select an element.
Try this
var txtname = jQuery('input[name="txtname"]').val();
var txtemail = jQuery('input[name="txtemail"]').val();
OR
var txtname = $('input[name="txtname"]').val();
var txtemail = $('input[name="txtemail"]').val();