How can I use the Ajax response in another function - php

I have a dropdown list with values from the database. I used AJAX to dynamically display the price of the selected item form the database. I want to use the price value for further processing

var dataForFuture;
$.get('ajax/test.html', function(data) {
dataForFuture = data;
// other code...
});

Related

PHP - Text Field value based on selected value from List Box

may I know how can I setting the text field's value according to the selected value from List box?
Table in database
HTML form
For example:
If I choose "DIP" from the List Box then the Text Field will display "Diploma in Information Technology (Programming)" automatically since I setting the Text Field became disabled.
P/S: List Box function was done. I just need some guides to settle the Text Field
var code = $('#code').val();
$.ajax({
type: "POST",
data: {code: code},
url: 'get_name_list.php',
success: function(data) {
$('#text_field').val(data);
}
in get_name_list.php make a query for fetch program_name and return its value. you can get code from $_POST['code']. and in success you need to set value for that textbox.
You can do it using Javascript/Jquery. Take idea from this.
Example :
1.) $ProgInfo is array of prog_code and prog_name.
2.) On change dropdown call below function with parameter (prog_code)
3.) getProgName will return you prog_name
Javascript function :
function getProgName(prog_code=null){
var json_user = <?=json_encode($ProgInfo)?>;
if(json_user.hasOwnProperty(prog_code)){
return json_user[prog_code];
}else{
return null;
}
}
$('id or class of name').html(getProgName("Your prog_code"));

JQuery PHP AJAX filter based on multiple checkbox array

I'm hoping someone can point me in the right direction. I'm primarily a PHP developer but I'm really trying to get my head around jquery and javascript more due to the increasing number of AJAX work requests we receive.
Basically I have a sidebar filter that works fine. It is based on 3 things. A group, category and sub category. So for example, Boots as the category, Leather (type) as a sub category and Black (colour) as tertiary filter. At the moment it works based on a GET form. However I want to use live filters instead so as they click a checkbox, it updates the results based on a query. I can write all the PHP for this but I'm struggling to get the data together by jQuery. I've looked at using jQuery .each and .change.
There are 3 groups of checkboxes and they are all based on arrays. So for example again: category[], subcategory[], tertiary[].
Thanks in advance for the help.
Some example HTML
<input id="$ProdCatLabel" class="side_filter_checkbox" name="ProdCatFil[]" type="checkbox" value="$ProdCat">
<input id="$ProdSubCatLabel" class="side_filter_checkbox" name="ProdSubCatFil[]" type="checkbox" value="$ProdSubCat">
<input id="$BrandingLabel" class="side_filter_checkbox" name="BrandFil[]" type="checkbox" value="$Branding">
My attempts:
var prodcats = $('side_filter_prodcats[name="ProdCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
var prodsubcats = $('side_filter_prodsubcats[name="ProdSubCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
$.ajax({
type: "POST",
url: "[ENTER PHP URL HERE]",
data: "ProdCats=" + prodcats + "ProdSubCats=" + prodsubcats,
success: function(msg) { $(".content_area").html(msg); }
});
Am I barking up the right tree here?
Ok let's say your checkboxes have the classes category, subcategory and tertiary. You could attach a click event handler to each group that calls the function to load in the correct data, passing the checkbox value and a class or data-attribute to the function as parameters.
// Your main DOM ready function
$(document).ready(function() {
// Checkboxes click function
$('input[type="checkbox"]').on('click',function(){
// Here we check which boxes in the same group have been selected
// Get the current group from the class
var group = $(this).attr("class");
var checked = [];
// Loop through the checked checkboxes in the same group
// and add their values to an array
$('input[type="checkbox"].' + group + ':checked').each(function(){
checked.push($(this).val());
});
refreshData(checked, group);
});
function refreshData($values, $group){
// Your $values variable is the array of checkbox values
// ie. "boot", "shoe" etc
// Your $group variable is the checkbox group
// ie. "category" or "subcategory" etc.
// Now we can perform an ajax call to post these variable to your php
// script and display the returned data
$.post("/path/to/data.php", { cats: $values, type: $group }, function(data){
// Maybe output the returned data to a div
$('div#result').html(data);
});
}
});
Here's an example of the checkbox click function in action: http://jsfiddle.net/F29Mv/1/

add elements in 2nd dropdown list depending upon the element selected in 1st dropdown using jquery and php

I'm trying to populate Cities as per the State selected by user in dropdown lists.
I've a function in jquery defined as:
function onchange1(dropdownmenu,field_name,id)
{
alert(field_name);
$.post(
'wppb.city.php',
{ field_name: id},
function(data) {
alert(data);
$('#'+dropdownname).html(data);
alert("Data Loaded: " + data);
});
alert($('#'+dropdownname).html());
}
and I'm trying to get values from the location where I've called this function.
I've called this function in html tags as:
<select name="state" id=state onChange="onchange1(city,state,this.value);">
where city is the name of my 2nd dropdownmenu, state is the field_name and this.value is the id.
But when this function is being called and when alerted it's showing [objectHTMLSelectElement].
How to retrieve values from HTML and use it in jquery function ?
I believe what you want is
$('#'+field_name.id).val()
You might also want to look into serializeObject , a good post is this Convert form data to JavaScript object with jQuery

Dynamically change dropdowns via SQL and calculate sums?

I've got a row in a table with 3 fields laid out as so:
Job Pay Grade Cost
<Select> <Select> <Calculation>
I've got an SQL table with the information above in it, for example:
Job Pay Grade Cost
Techie 1 100
Techie 2 200
Engi 2 300
Engi 3 400
Engi 4 500
What I need to do is to be able to select a Job from the dropdown and then the Pay Grade select box will change depending on what matches that job in the SQL database. It will then show the cost which relates to the to selected.
How can I go about this as I am a little stuck
First create ajax request when a job title is selected. WIthin the success callback of the request will generate html for the options for pay grade select from JSON response from server
jQuery
$('select.jobTitle').change(function(){
var $titleSelect=$(this);
$.getJSON('processJobGrades.php', { jobTitle : $(this).val() }, function(response){
var gradesOptionsHtml='';
/* create options html from json response */
$.each( response, function(i, item){
gradesOptionsHtml+='<option value="'+item.grade+' data-cost="'+item.cost+'">'+item.grade+'</option>';
});
$titleSelect.parent().find('select.jobGrade').html(gradesOptionsHtml);
});
});
IN processJobGrades.php receive $_GET['jobTitle'] . Do DB lookup and create json to send back.
PHP
$outputArray=array();
/*in loop over DB data:*/
$outputArray[]= array( 'grade'=>$row['grade'], 'cost'=>$row['cost']);
/*Output final array as JSON*/
echo json_encode( $outputArray);
jQuery change handler for paygrade select to get cost
$('select.jobGrade').change(function(){
var cost=$(this).find(':selected').data('cost')
$(this).parent().find('input.jobCost').val( cost);
})
You need to post the select job via $.ajax and then in success function populate the dropdown list like this:
function selectHandler (event, ui)
{
var id = event.target.id;
$.ajax({
type: "POST",
url: "/php/get_quantity_type.php",
dataType:"json",
data: { ingridient : ui.item.value},
success: function(data){$("#"+id+"_t").empty(); $.each(data,function(index,value) {$("#"+id+"_t").append('<option value="' + value + '">' + value + '</option>');})}
});
}
This example takes a name of a material from select list posts it via $ajax() to a php script and writes it down to a new dropdown list which id is based on id that triggered the event. If you need the php code just ask:)
You bind your job list to the event handler above:
("#job_list").bind("select",selectHandler);
This code posts data to "/php/get_quantity_type.php", and passess the result to function declared in success attribute;

using multiselect dropdown and looping through its values using jquery

I have a multiselect drop down, on selecting multiple items from it, i need to pass the value of this multiselect into an ajax file, and create divisions dynamically and load the data retreived from the ajax files into these dynamic divisions.
var itemvalues= [];
$('#MultiSelectItemID :selected').each(function(i, selected) {
itemvalues[i] = $(selected).val();
});
$('#itemContent').html(LoadHTML);
$('#itemDetailsContainer').fadeIn('',function(){
$('#itemContent').load('ajax_calls/item_details.php?ItemID='+$('select[name=MultiSelectItemID]').val() || [],
function(){
$(this).show('highlight');
}); });
Now , i want to loop through each value in the itemvalues[] array and pass it to my php file and get the data and load it into a new division.
Please help.
Will this do the job? (Note I 've changed "MultiSelectItemID" to simply "ItemID" and serialize()d it.)
http://jsfiddle.net/svzsY/8/
var itemvalues = [];
$('#itemContent').html(LoadHTML);
$('#itemDetailsContainer').fadeIn('', function() {
$('#itemContent').load('ajax_calls/item_details.php', ($('select[name=ItemID]').serialize() || []), function() {
$(this).show('highlight');
});
});

Categories