I have a function which makes a ajax call and gets a list of vehicle make.
var car_make_list_target_id = 'car_make';
var make_year_list_select_id = 'years';
var car_model_list_target_id = 'car_model';function get_car_model(){
var car_model_initial_target_html = '<option value="">--Select Model--</option>';
//Grab the chosen value on first select list change
var selectvalue = $('#car_make').val();
alert('first alert ' + selectvalue);
var yearvalue = $('#' + make_year_list_select_id).val();
//Display 'loading' status in the target select list
$('#' + car_model_list_target_id).html('<option value="">Loading Car Models</option>');
if(selectvalue === ""){
//Display initial prompt in target select if blank value selected
$('#' + car_model_list_target_id).html(car_model_initial_target_html);
} else{
//Make AJAX request, using the selected value as the GET
$.ajax({
url: 'get_model.php?make=' + selectvalue + '&year=' + yearvalue,
success: function(output){
//alert(output);
$('#' + car_model_list_target_id).html(output);
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status + " " + thrownError);
}
});
}
I also have a php if loop to see is session isset. Now I want to display these values within the drop down list if the session is set.
if(isset($_SESSION['vehicle_info'])){
echo '<script>'
.'$("#states option[value=' . $_SESSION['vehicle_info']['state'] . ']").attr("selected","selected");'
.'$("#years option[value=' . $_SESSION['vehicle_info']['year'] . ']").attr("selected","selected");'
. ' $("#years").prop("disabled", false);'
. ' $("#car_make").prop("disabled", false);'
. ' $("#car_model").prop("disabled", false);'
. 'get_car_make();//This works'
. 'get_car_model();//This does not work unless I debug javascript'
. '</script>';
}
The issue is unless I set a breakpoint within the get_car_model on the following lines
var selectvalue = $('#car_make').val();
alert('first alert ' + selectvalue);
the var selectvalue is blank, but if I leave the breakpoint it will alert the value of the option and will display correctly. I have been beating my head for the last 4 hours and I have not been able to figure this out. Is this normal browser behavior or am I missing something? Any input will be great.
Related
I'm trying to recieve data in JSON from online php code, I'm getting undefined error
The website i'm retrieving from is https://www.orba.com.ng/getemployees.php
I'm using jQuery
localStorage['serviceURL'] = "https://www.orba.com.ng/";
var serviceURL = localStorage['serviceURL'];
var scroll = new iScroll('wrapper', { vScrollbar: false, hScrollbar:false, hScroll: false });
var employees;
$(window).load(function() {
setTimeout(getEmployeeList, 100);
});
function getEmployeeList() {
$('#busy').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#busy').hide();
$('#employeeList li').remove();
employees = JSON.parse(data.items);
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="img/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
$(document).ajaxError(function(event, request, settings, thrownError) {
$('#busy').hide();
alert("Failed: " + thrownError.error);
});
I'm getting error code undefined
It was a CORS issue, Quite easy to fix. Search on google
Here there is my code which insert a row in ajax, it's working perfectly.
I need to display the new row that the user inserted inside my select multiple without reload the page but i don't know how to do ..
Thank you for you help
Ajax call :
$('#insertForm').on('click', function(){
var form_user = $('input[name=form_user]').val();
var form_intitule = $('input[name=form_intitule]').val();
var form_organisme = $('input[name=form_organisme]').val();
var form_date = $('input[name=form_date]').val();
var form_benefice = $('textarea[name=form_benefice]').val();
var form_dispositif = $('#form_dispositif').val();
var form_entpro_ActionAutre = $('input[name=entpro_ActionAutre]').val();
$.ajax({
type: "GET",
url: "lib/function.php?insertForm="+insertForm+"&form_user="+form_user+"&form_intitule="+form_intitule+"&form_organisme="+form_organisme+"&form_date="+form_date+"&form_benefice="+form_benefice+"&form_dispositif="+form_dispositif+"&form_entpro_ActionAutre="+form_entpro_ActionAutre,
dataType : "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success:function(data){
}
});
});
My select multiple in function.php :
$displayFormation = $bdd->prepare('SELECT * FROM FORMATION WHERE form_id_user = :idSalarie ORDER BY form_date DESC');
$displayFormation->bindParam(':idSalarie', $_POST['idSalarie']);
$displayFormation->execute();
$data['formation'] .='
<div class="form-group">
<label for="nomSalarie" class="col-sm-1 control-label" id="nameSelect">Formations</label>
<div class="col-sm-11">
<select name="listeFormation[]" id="listeFormation" class="form-control" multiple>';
while($ligne = $displayFormation->fetch()){
$data['formation'] .='<option value="'. $ligne['form_id'].'">'.$ligne['form_intitule']. " [" . $ligne['form_organisme'] . "]". " [Année : " . dateAnglaisVersFrancaisAnnee($ligne['form_date']) . "]" . " [Bénéfices : " . $ligne['form_benefice'] . "]" . " [Dispositif : " . $ligne['form_dispositif'] . "]".'</option>';
}
$data['formation'] .='
</select>
</div>
</div>';
I am going to make some guesses and also some suggestions. Without knowing what your resulting data is going to be, it's hard to answer fully.
My working example and tests: https://jsfiddle.net/Twisty/053q24dh/
Here is the JQuery I would advise:
$('#insertForm').on('click', function() {
var form_user = $('input[name=form_user]').val();
var form_intitule = $('input[name=form_intitule]').val();
var form_organisme = $('input[name=form_organisme]').val();
var form_date = $('input[name=form_date]').val();
var form_benefice = $('textarea[name=form_benefice]').val();
var form_dispositif = $('#form_dispositif').val();
var form_entpro_ActionAutre = $('input[name=entpro_ActionAutre]').val();
$.ajax({
type: "GET",
url: "lib/function.php",
data: {
"insertForm": insertForm,
"form_user": form_user,
"form_intitule": form_intitule,
"form_organisme": form_organisme,
"form_date": form_date,
"form_benefice": form_benefice,
"form_dispositif": form_dispositif,
"form_entpro_ActionAutre": form_entpro_ActionAutre,
},
dataType: "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success: function(data) {
// Asumming the page returns the following HTML, or something similar:
// <option value="9">Title [Organize] [Année : 02/02/16] [Bénéfices : 1] [Dispositif : 1]</option>
$("#listeFormation").append(data);
}
});
});
Again, this assumes that the HTML that is being returned to data is a single option tag to be appended to the select object. It looks like your PHP in the Post is looking for POST and your ajax is making a GET, so I am assuming they are different PHP Scripts. If they are not, you need to make sure the PHP knows how to respond properly and is not sending back too much data.
Also, I noticed that insertForm is not defined in this code snippet. If it's defined globally, that's fine, otherwise you need to define it within the scope of this function.
I have a form that will contain a html table which allows users can add or delete rows from it. That will works fine .
/*add row*/
function add_Items(itemtypeid, itemid, reqqty) {
var mode = 1;
var pstSettings = {
url: 'ajax_Items/' + itemid + '/' + mode
callback: function (data) {
var dyntd = "";
var hidval = "";
var $response = $(data);
var resitmname = $response.filter('#Item_Name').text();
var resitmdesc = $response.filter('#Item_Descrip').text();
dyntd = "<td><label>" + itemid + "</label></td>";
dyntd += "<td><label>" + resitmname + "</label></td>";
dyntd += "<td><label>" + resitmdesc + "</label></td>";
dyntd += "<td><label>" + reqqty + "</label></td>";
hidval += '<input type="hidden" name="itemid" value=' + itemid + ' />';
hidval += '<input type="hidden" name="reqitem" value=' + reqqty + ' />';
dyntd += '<td>' + hidval + '<input type="button" name="min" class="minus" value="-" />';
$('.item-result-table tr:last').after('<tr>' + dyntd + '</tr>');
}
};
post_Call(pstSettings);
}
}
/* delete row */
$(document).ready(function () {
$('.item-result-table').delegate('.minus', 'click', function (e) {
$(this).parent().parent().remove();
});
});
But now my problem is how to submit the html table in a form, because of all are html tags not input type tags . I have added a hidden tag . But it also creates problem that it only takes the first element , others are ignored. Is any other method existing to submit this html table data?
The reason you are only getting one input is because you defined it wrong, you need to define it as array:
<input type="hidden" name="itemid[]" value=' + itemid + ' />
<input type="hidden" name="reqitem[]" value=' + reqqty + ' />'
and then in PHP:
$_POST['itemid'][0];
I think that you could use the $.ajax jquery function. You can serialize all your inputs in the form like this:
$("#btn_submit").on('click', function() {
$.ajax({
url: $(this).closest("#div_content").find("#form").attr( 'action' ),
type: 'post',
data: $(this).closest("#div_content").find("#form").serialize(),
}).done( function(msg) {
//console.log("ok");
}).fail( function(jqXHR, textStatus) {
//console.log("fail");
});
});
With the "serialize" you can send all the variables and on the controller you can read the variables with $_POST and the name of the input.
I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);
I have four variables I'm trying to pass via AJAX to be processed by some PHP on the same page: newJudgeName, newJudgeSection, newJudgeStatus, and originalJudgeName. The success function echos them out and they're the correct values, it's just the newJudgeStatus variable is not being picked up by my PHP. I've switched newJudgeStatus with newJudgeName in the data line on the AJAX request and then the value is sent just fine (I can see it in the db under Judge Name)... it's only when it's in the original spot in the ajax request that it doesn't work. I'm completely new to Ajax. Any help would be much appreciated.
AJAX:
$.ajax({
type: "POST",
url: "test.php",
data: 'newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus + '&originalJudgeName=' + originalJudgeName,
success: function(){
alert('newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName);
}
});
PHP:
if(isset($_POST['newJudgeName'])){
$newJudgeName = $_POST['newJudgeName'];
$newJudgeSection = $_POST['newJudgeSection'];
$newJudgeStatus = $_POST['newJudgeStatus'];
$originalJudgeName = $_POST['originalJudgeName'];
$judgeID = judgeNametoID($originalJudgeName);
$con = mysql_connect("-","-","-");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else {
// connected to database successfully
}
mysql_select_db("cm", $con);
$query = ("UPDATE `casemanagers`.`judges` SET `Name`='$newJudgeName' , `Section`='$newJudgeSection', `Active`='$newJudgeStatus' WHERE `judgeID`='$judgeID';");
$result = mysql_query($query);
mysql_close($con);
}
You have an errant space in your data string:
'&newJudgeStatus =' + newJudgeStatus +
---------------^^^^
// Should be
'&newJudgeStatus=' + newJudgeStatus +
You should send the data this way:
$.ajax({
type: "POST",
url: "test.php",
data: {
'newJudgeName' : newJudgeName,
'newJudgeSection' : newJudgeSection,
'newJudgeStatus' : newJudgeStatus,
'originalJudgeName' : originalJudgeName
},
success: function(){
alert('newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName);
}
});
Instead of manual processing, I'll recommend to put all these inside a form & use following code to send data:
$('#id_of_the_form').serialize();
instead of buggy:
newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName ...
See http://api.jquery.com/serialize/