Combining two dropdown selection to retrive one result ajax/php - php

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.

Related

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

Ajax call returns nothing

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

how to fetch mysql data using ajax when one input is filled using function.php

mysql table
|order_no |order_name |
| -------- |------------|
| 43423 | abc |
??????????????????????????
now my question is how do i use ajax to fetch the order name and city when i order number ? any help is appreciated..
I have a code here:
ValidateForm.js
var searchTimeout; //Timer to wait a little before fetching the data
$("#order_numbr").keyup(function() {
searchKey = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(searchKey);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
function getUsers(searchKey) {
$.ajax({
type : "POST",
async: false,
data : "action=checkOrdrNum",
url : ajaxurl,
dataType:"json",
success: function(data) {
if(data.status) {
$("#ur_name1").val(data.userData.order_name);
}
}
}"This order number does not exist");
}
And ofcourse the function.php file:
add_action('wp_ajax_nopriv_checkOrdrNum','checkOrdrNum');
add_action('wp_ajax_checkOrdrNum','checkOrdrNum');
function checkOrdrNum(){
global $wpdb,$current_user;
$response = Array();
$response['status'] = false;
$query = mysql_query("SELECT `order_name` FROM `art_work_history` WHERE `order_no` LIKE '%".$_POST['value']."%' LIMIT 1"); //Or you can use = instead of LIKE if you need a more strickt search
if(mysql_num_rows($query)) {
$userData = mysql_fetch_assoc($query);
$response['userData'] = $userData;
$response['status'] = true;
}
echo json_encode($response);
}
U need to pass input value to the ajax
I thnk that was the only thing missing
function getUsers(searchKey) {
$.ajax({
type : "POST",
async: false,
data : "action=checkOrdrNum",
url : ajaxurl,
dataType:"json",
data: {value: searchKey}, // this is the line missing
success: function(data) {
if(data.status) {
$("#ur_name1").val(data.userData.order_name);
}
}
});
}

how to return html code and php value in one ajax call

i have a simple ajax call which returns html codes,
//=======-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-==-=-==-=-=-=-=
//SEARCH Submit ===============================================================================
$('.clicked_search').live("click",function() {
var from = $('#from').val();
var to = $('#to').val();
var sel = $('#sel').val();
var BegDT = new Date(from);
var EndDT = new Date(to);
var sum = BegDT - EndDT;
alert (BegDT +" b"+ EndDT +" e"+ sum);
if(sum > 0 | from == "" & to != "" | from != "" & to == ""){
$('.inv_date').show();
}
else{
$("#app_panel").html('<div id="flash" align="left" ><img src="img/clientimg/ajax.gif" align="absmiddle"> <span class="loading">Loading Request...</span></div>');
$("#clock").html('<div id="flash2" align="left" ><img src="img/clientimg/ajax.gif" height="15px" align="absmiddle"> <span class="loading"><font size="1">Loading Request...</font></span></div>');
$.ajax({
type: "POST",
url: "database/clientpanel/logs/search_call_log.php",
data: {
from: from,
to: to,
sel: sel
},
cache: false,
success: function(html){
$("#flash").hide();
$('.inv_date').hide();
$("#app_panel").append(html);
}
});
$.ajax({
url: "database/clientpanel/logs/search_clock_log.php",
cache: false,
success: function(html){
$("#flash2").hide();
$('.inv_date').hide();
$("#clock").append(html);
}
});
}
return false;
});
but i also want it to return values that was produced from the php which the ajax called,
session_start();
include("../../dbinfo.inc.php");
// connect to the database
$client_id = $_SESSION['clientid'];
//===========THIS PHP VALUES RIGHT HERE===================================
$out = 0;
$in = 0;
$ext =0;
$min = 0;
$sec = 0;
//====================================================================
$query=" select * from call where client='$client_id' ORDER BY date_time DESC";
$result = $mysqli->query($query);
how can i return the "html code" together with the "php values" using one ajax call?
You could transfer your data in a JSON format.
Within your PHP, you'll build an array with all the data you want to pass back for the AJAX call.
$results = array(
'html' => $html,
'variable1'=>'value1',
'variable2'=>'value2',
...
);
Now you encode this array into a JSON format using json_encode() -
$jsonString = json_encode($results);
echo $jsonString;
This is the value that you echo out of your PHP.
Now in your jQuery $.ajax request, you'll need to specify the dataType:json, and you'll be able to access all the parameters in your success callback -
$.ajax({
type: "POST",
dataType: "json",
...
success: function(data){
...
$("#app_panel").append(data.html);
// also available :
// data.variable1 and data.variable2
}
});

jquery passing variables to php file

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

Categories