ajax and javascript drilldown script addition - javascript

I have a make/model/engine search form, the user selects the make which then populates the model, the user selects the model and it populates the engine. The problem I have encountered is that several of the manufacturers (make) use the exact same model. The script I have chooses the engine based on the model only. I would like to modify the script so it chooses the engine based on the make AND model, this would resolve my problem. I am somewhat familiar with javascript but I am no expert, I see the ajax requests in the aircraftMakeModel.php file but do not know how to add the make to the query. I have included the three files used below. Any help is appreciated in advance.
Thanks
Tom
aircraftMakeModel.php
<script type="text/javascript">
$(document).ready(function()
{
$('#aircraftMake').change(function()
{
var make=$(this).val();
var dataString = 'make='+ make;
$.ajax
({
type: "POST",
url: "include/getAirFrame.php",
data: dataString,
cache: false,
success: function(html)
{
$('#aircraftModel').html(html);
}
});
});
});
$(document).ready(function()
{
$('#aircraftModel').change(function()
{
var model=$(this).val();
var dataString = 'model='+ model;
$.ajax
({
type: "POST",
url: "include/getEngine.php",
data: dataString,
cache: false,
success: function(html)
{
$('#engineModel').html(html);
}
});
});
});
</script>
getAirFrame.php
<?php
include "../connection.php";
$q = $_POST['make'];
$q = addslashes($q);
$rs=mysqli_query($link,"SELECT DISTINCT(`aircraftModel`) FROM `aircraftData` WHERE `aircraftMake` = '$q' ORDER BY aircraftModel ; ");
echo '<option value="0">Aircraft Model</option>';
while($data = mysqli_fetch_row($rs)){
$sa=$data[0];
echo '<option value="'.$sa.'">'.$sa.'</option>';
?>
<?php } ?>
getEngine.php
<?php
include "../connection.php";
$q = $_POST['model'];
$q = addslashes($q);
$rs=mysqli_query($link,"SELECT DISTINCT(`engineModel`) FROM `aircraftData` WHERE `aircraftModel` = '$q' ORDER BY engineModel");
echo '<option value="0">Engine Model</option>';
while($data = mysqli_fetch_row($rs)){
$sa=$data[0];
echo '<option value="'.$sa.'">'.$sa.'</option>';
?>
<?php } ?>

If you want to send the make and model on the ajax call to get the engine something like this should work. Make the call to get the model as you do, then also add the make to the ajax request data to get the engine.
Note: not sure if this is a typo $('#marke')
$(document).ready(function(){
$('#marke').change(function() {
//make id
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "include/getph.php",
data: dataString,
cache: false,
success: function(html) {
$('#model').html(html);
}
});
});
});
$(document).ready(function() {
$('#model').change(function(){
//make id
var id = $('#marke option:selected').val();
//model id
var id1=$(this).val();
var dataString = 'id1='+ id1 + '&id=' + id;
$.ajax({
type: "POST",
url: "include/getph2.php",
data: dataString,
cache: false,
success: function(html) {
$('#engine').html(html);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

echo js using php to append more options to select input

Okay so I'm having that JS :
<script>
$('#building').change(function () {
var selectedValue = $(this).val();
$.ajax({
url: 'getunits.php',
type: "POST",
async:false,
contentType: "application/x-www-form-urlencoded;charset=utf-8",
data:{
building: selectedValue,
},
success: function (result) {
var e = document.getElementById('div1');
e.innerHTML = result;
eval(document.getElementById('runscript').innerHTML);
}
});
});
</script>
<div id="div1">
</div>
And that in the PHP :
$selectunits = mysqli_query($con,"SELECT * FROM `units` WHERE `building`='".$building."'");
echo '<script type="text/javascript" id="runscript">';
while($rowunits = mysqli_fetch_assoc($selectunits))
{
//echo '<option value="'.$rowunits["ID"].'">'.$rowunits["unit_number"].'</option>';
echo '$("#unit").append("<option value="'.$rowunits["ID"].'">'.$rowunits["unit_number"].'</option>");';
}
echo'</\script>';
All I'm trying to do is after I select from the first select, an Ajax goes to that URL and fills up the 2nd select with different data. So what I was able to do is do a loop in the PHP to create the required JS to fill up.

Unable to change image onChange function on ajax success return

Hi I'm new to this javavascript/ajax. I am trying to create a dropdown that dynamically changes the images by the different options as shown in this Fiddle here but the change function does not seem to be working.
I made sure that I am able to get the data from pictureList but the image source did not change successfully as the fiddle.
$('#selectVariant').change(function () {
var sku = $('#selectVariant :selected').val();
var sessionId="<?php echo $sessionId; ?>";
var dataString='sku='+ sku +'&sessionId='+sessionId;
$.ajax({
type:"post",
url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
data:dataString,
cache:false,
dataType: "JSON",
success: function(data){
var pictureList = {};
//example of my data list
//var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
//'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
//};
$.each(data.productVariantImages,function(i, productVariantImages){
pictureList[data.sku] = this.imagePath;
});
console.log(pictureList);
$('.content img').attr({"src":[pictureList[this.value]]});
}
});
return false;
});
However, when I do test it outside the ajax post, it is able to run.
Instance of this is change in ajax success function scope.
In this line $('.content img').attr({"src":[pictureList[this.value]]}); this
is not the instance of selectVariant element.
The usual practice for this is declare a variable that and use that variable in other scope. try the below code.
$('#selectVariant').change(function () {
var sku = $('#selectVariant :selected').val();
var sessionId="<?php echo $sessionId; ?>";
var dataString='sku='+ sku +'&sessionId='+sessionId;
var that = this;
$.ajax({
type:"post",
url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
data:dataString,
cache:false,
dataType: "JSON",
success: function(data){
var pictureList = {};
//example of my data list
//var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
//'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
//};
$.each(data.productVariantImages,function(i, productVariantImages){
pictureList[data.sku] = this.imagePath;
});
console.log(pictureList);
$('.content img').attr({"src":[pictureList[that.value]]});
}
});
return false;
});

Pass values from JQUERY to PHP then output to INPUT in FORM

i need to get a value from the a form then send it to php using jquery then output the result a dropdown select menu
get the value of using jquery
<input id="search" name="search" type="text">
send it to php and perform a query
<select id="farmertype" name="farmertype" >
<option value="" > - PLEASE SELECT FARM -</option>
//// output here as options
</select>
my php file farm.php
<?php
include_once("../init.php");
$q = ($_POST["search"]);
$db->query("SELECT * FROM farmers ");
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
echo "<option value='$idno'>$idno</option>";
}
}
?>
the jquery part is so messy this is where i really need help
$("#search").click(function() {
search = $(this).attr('#search');
$.ajax({
type: 'GET',
url: 'farm.php',
data: "#search=" + search,
});
});
try this, it will help you.
JQuery:
$("#search").click(function() {
search = $(this).val();
$.ajax({
type: 'POST',
url: 'farm.php',
data: {searchValue:search},
success:function(result) {
console.log(result);
}
});
});
PHP:
<?php
include_once("../init.php");
$q = ($_POST["searchValue"]);
$db->query("SELECT * FROM farmers");
$result = [];
while ($line = $db->fetchNextObject()) {
$idno = $line->idno;
$result = "<option value='$idno'>$idno</option>";
}
print_r($result);
?>
what is the purpose of your variable $q?
Your jquery can be like :
$("#search").click(function() {
search = $('#search').val();
$.ajax({
type: 'GET',
url: 'farm.php',
data: {search : search},
success: function(html){
alert(html);
}
});
});
$("#search").click(function() { /* I think you should use keyUp or use click on a button, nobody clicks an input box */
var search = $(this).val();
$.ajax({
method: 'POST', //
url: 'farm.php',
data: {'search' : search},
success: function(data){
alert(data);
}
});
});

Passing array and other data through ajax

This is my javascript function....
But my php controller getting all values but not the array not sure why ? Need help.....
Thanks in advance :)
function submitForm(){
var id = $('#id').val();
var supplier_id = $('#supplier_id').val();
var description = $('#description').val();
var numofpro = $('#numofpro').val();
var product_id = new Array();
for(var i=0;i<numofpro;i++){
product_id[i] = $('#product_id'+(i+1)).val();
}
var payment_mode = $('#payment_mode').val();
//description = description.replace(new RegExp('\r?\n','g'), '<br />');
$.ajax({
url: "<?= base_url(); ?>edit/save_purchase", //The url where the server req would we made.
data: "id="+id+"&supplier_id="+supplier_id+"&description="+description+"&product_id="+product_id+"&payment_mode="+payment_mode,
dataType: "html", //Return data type (what we expect).
beforeSend:function(){
//alert("asds");
},
success: function(data) {
//alert("Edited");
alert(data);
}
});
}
because you pass a string, not an array :) try it:
$.ajax({
url: "<?= base_url(); ?>edit/save_purchase",
type: "POST"
data: {id : id, supplier_id : supplier_id, description : description, product_id : product_id, payment_mode : payment_mode},
dataType: "json",
beforeSend:function(){
//alert("asds");
},
success: function(data) {
//alert("Edited");
alert(data);
}
});
in you php use :
$arr = json_decode($_POST);
//some php code
//some $result;
// if $result arr then
echo json_encode($result);
// else
echo json_encode(array('data' => $result))
hope this helps...
You need to first turn that array into a string in JS. Before sending it, do this:
JSON.stringify(product_id);
Once you receive it in PHP, you need to decode it.
$decoded = json_decode($_POST['product_id'])

Getting php with js with ajax

It won't give me the value from $scoresArray in php to data_response in js
If I log (obj) it returns nothing.
I have this in JS
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (obj) {
stageRef.$("txtTopscorePunt").html(obj.score[0]);
stageRef.$("txtTopscorePunt2").html(obj.score[1]);
stageRef.$("txtTopscorePunt3").html(obj.score[2]);
}
});
This in php:
function GetScores(){
$query = "SELECT * FROM topscores ORDER BY Scores DESC LIMIT 3";
$result = mysql_query($query);
$scoresArray = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$scoresArray[$i]['score'] = $row['score'];
$i++;
}
echo json_encode($scoresArray);
}
You don't need to JSON.parse(str) with dataType:json -- it's already parsed.
In addition, your selectors are wrong. If you want to select an ID, you need the # character.
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (obj) { // not 'complete'
console.log(obj);
$("#txtTopscorePunt").html(obj.score[0]);
$("#txtTopscorePunt2").html(obj.score[1]);
$("#txtTopscorePunt3").html(obj.score[2]);
}
});
http://api.jquery.com/jQuery.ajax/
update the code to this:
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (data_response) {
console.log(data_response);
var response = data_response;
var response_str = JSON.stringify(response);
alert(response_str); // don't do this if the returned is too much
console.log(response_str); // use your browser console to view the results
}
});
Once you have done this, can you post the results of alert or console log.
Also, in the results does it start with "[" or "{"?
From the results we should be able to help you with the correct way to access your JSON object.
Regards.

Categories

Resources