Jquery: Option selected not work in rendered select list - php

I had a countries/state chained select box pulled from database (rendered select list), however I want the specific option value remain selected when the page is redirected back by certain action. The user input fields are temporarily stored in SESSION, all fields is able to retained the value, excepted Country and State field.
I couldn't find these pulled option tag (which is rendered) appeared in view-sources, but I can view it in Chrome console and Firebug, thus I believe jquery cannot find the particular option value to perform the action, whereas when I hard-code the options, the below script is working:
Append options
function ajaxCall() {
this.send = function(data, url, method, success, type) {
type = type||'json';
var successRes = function(data) {
success(data);
};
var errorRes = function(e) {
console.log(e);
alert("Error found \nError Code: "+e.status+" \nError Message: "+e.statusText);
};
$.ajax({
url: url,
type: method,
data: data,
success: successRes,
error: errorRes,
dataType: type,
timeout: 60000
});
}
}
function locationInfo() {
//var rootUrl = "http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/api.php";
var rootUrl = jsbaseurl + '/inc/api-get-location.php';
var call = new ajaxCall();
/* disabled get cities
this.getCities = function(id) {
$(".cities option:gt(0)").remove();
var url = rootUrl+'?type=getCities&stateId=' + id;
var method = "post";
var data = {};
$('.cities').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
$('.cities').find("option:eq(0)").html("Select city");
if(data.tp == 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.cities').append(option);
});
$(".cities").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
*/
this.getStates = function(id) {
$(".states option:gt(0)").remove();
$(".cities option:gt(0)").remove();
var url = rootUrl+'?type=getStates&countryId=' + id;
var method = "post";
var data = {};
$('.states').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
$('.states').find("option:eq(0)").html("Select state");
if(data.tp === 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.states').append(option);
});
$(".states").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getCountries = function() {
var url = rootUrl+'?type=getCountries';
var method = "post";
var data = {};
$('.countries').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
$('.countries').find("option:eq(0)").html("Select country");
console.log(data);
if(data.tp === 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.countries').append(option);
});
$(".countries").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
}
$(function() {
var loc = new locationInfo();
loc.getCountries();
$(".countries").on("change", function(ev) {
var countryId = $(this).val();
if(countryId !== ''){
loc.getStates(countryId);
}
else{
$(".states option:gt(0)").remove();
}
});
/* Disabled city
$(".states").on("change", function(ev) {
var stateId = $(this).val();
if(stateId != ''){
loc.getCities(stateId);
}
else{
$(".cities option:gt(0)").remove();
}
});
*/
});
Jquery to retain selected option
<script>
$(document).ready(function(){
localStorage.setItem('selCountry', '<?php echo $cust_country_code ?>');
$('.countries').find('option').each(function(i,e){
if($(e).val() == localStorage.getItem('selCountry')){
$('.countries').prop('selectedIndex',i);
}
});
});
</script>
**the $cust_country_code is return countries id that
HTML - Options is rendered from db + jquery.
<select name="co_country" class="countries">
<option value="">Select Country</option>
<!-- HARDCODED FOR TEST, WORKING!
<option value="111">Brazil</option>
<option value="142">Germany</option>
<option value="123">Austria</option>
<option value="145">Japan</option>
-->
</select>
I was included $(document).ready() in order jquery to run while DOM is loaded, but no luck, any workaround?

Related

How to set selected value of jQuery chosen?

<script>
$(document).ready(function () {
$("#state").change(function () {
var stateId = $("#state").val()
phpurl = "sample_url" + stateId;
$.ajax({
url: phpurl,
success: function (data) {
$("#district").html(data).trigger("chosen:updated");
},
error: function(data) {
}
});
});
});
</script>
Above is my code to generate district based on state, and it works fine. I just want set the value what is selected by user. At present the selected value is cleared after selecting a state and submit.
You can use a global to hold selected value
var selectedDistrict = 0;
$("#district").change(function () {
selectedDistrict = $("#district").val();
});
then do:
$("#district")
.html(data)
.trigger("chosen:updated")
.val(selectedDistrict)
.trigger("chosen:updated");
in your ajax success.
Means your code will become:
<script>
var selectedDistrict = 0;
$(document).ready(function () {
$("#district").change(function () {
selectedDistrict = $("#district").val();
});
$("#state").change(function () {
var stateId = $("#state").val()
phpurl = "sample_url" + stateId;
$.ajax({
url: phpurl,
success: function (data) {
$("#district").html(data)
.trigger("chosen:updated")
.val(selectedDistrict)
.trigger("chosen:updated");
},
error: function(data) {
}
});
});
});
</script>

jQuery use ajax and json to switch page with button

Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }

Thickbox not getting values of textbox using Jquery

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

Passing a variable from php to ajax - weird, nothing works

I am having great difficulty passing a variable from a PHP file to .js files
The code in the PHP file I used is this:
<script>
jQuery(document).ready(function(){
var uid = <?php echo (intval($uid)); ?>;
//var uid = <?php echo(intval($_SESSION['uid'])); ?>.val();
});
</script>
The variable value should be passed into the .js file to refresh just a certain div on the page (not the whole page) after a form submission is performed.
This is the .js file and the corresponding code starts at "// refresh the monitor list div":
$(function() {
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var domain = $("input#domain").val();
if (domain == "") {
$("label#domain_error").show();
$("input#domain").focus();
return false;
}
var com_domain = $("input#com_domain").val();
if (com_domain == "") {
$("label#com_domain_error").show();
$("input#com_domain").focus();
return false;
}
var cemail = $("input#cemail").val();
var port = $("select#port").val();
var active = $("input#active").val();
var uid = $("input#uid").val();
var main = $("select#main").val();
var dataString = 'cemail='+ cemail + '&domain=' + domain + '&com_domain=' + com_domain + '&active=' + active + '&main=' + main + '&port=' + port;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "user_add.php",
data: dataString,
success: function() {
$('#monitor_form').append("<div id='message'></div>");
$('#monitor_form form')[0].reset();
$('#message').html("<img id='checkmark' src='images/tick.png' /><b> Monitor sucessfully added!</b>")
.hide()
.fadeIn(500, function() {
$('#message').append("");
});
setTimeout("$('#message').hide().remove();", 6000);
var dataString2 = 'ajax=1&uid=' + uid;
$.ajax({
type: "GET",
url: "monpanel.php",
data: dataString2,
success: function(html_data){
$('#list_monitors').html(html_data);
}
});
//document.onkeydown = showDown;
}
});
return false;
});
});
function showDown(evt) {
event = (evt)? evt : ((event)? event : null);
if (evt) {
if (event.keyCode == 8 && (event.srcElement.type!= "text" && event.srcElement.type!= "textarea" && event.srcElement.type!= "password")) {
// When backspace is pressed but not in form element
cancelKey(evt);
}
else if (event.keyCode == 116) {
// When F5 is pressed
cancelKey(evt);
}
else if (event.keyCode == 122) {
// When F11 is pressed
cancelKey(evt);
}
else if (event.ctrlKey && (event.keyCode == 78 || event.keyCode == 82)) {
// When ctrl is pressed with R or N
cancelKey(evt);
}
else if (event.altKey && event.keyCode==37 ) {
// stop Alt left cursor
return false;
}
}
}
function cancelKey(evt) {
if (evt.preventDefault) {
evt.preventDefault();
return false;
}
else {
evt.keyCode = 0;
evt.returnValue = false;
}
}
/*function mycallbackfunc(v,m,f) {
if (v == 'Cancel') {
$.prompt('The action was ' + v + 'ed');
}
else {
$.prompt('Monitor ' + v + 'd successfully');
}
}*/
// ask for validation on monitor delete, pause, resume request
$(document).ready(function(){
$(".error").hide();
alert("Stage 0! -> uid="+uid.toString());
$("#mondelpau").validate({
debug: false,
rules: {
act: "required",
uid: "required",
sid: "required"
},
/*messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
},*/
submitHandler: function(form) {
// do other stuff for a valid form
//$.post('delpaures.php', $("#mondelpau").serialize(),
alert("Stage 1! -> uid="+uid.toString());
$.ajax({
async: false,
type: "POST",
url: "delpaures.php",
data: $("#mondelpau").serialize(),
success: function(data) {
$('#monadiv').html(data);
//$('#results').html(data);
//alert (data);return false;
// refresh the monitor list div
//$('#list_monitors').load(dataString8);
//var uid = $("input#uid").val();
//var dataString8 = 'ajax=1&uid=' + $("input#uid").val();
var dataString8 = 'ajax=1&uid=' + uid; // .val()
//var dataString8 = 'ajax=1&uid=19';
alert("Stage 2! -> uid="+uid.toString());
$.ajax({
async: false,
type: "GET",
dataType: "html",
url: "monpanel.php",
data: dataString8,
success: function(html_data){
alert("Stage 3!");
$("#list_monitors").css("background-color","#FF0000");
$("#list_monitors").html(html_data);
}
});
}
});
}
});
});
Needless to say I have tried everything, even renaming .js file to .php and redirecting to them with .htaccess, but that doesn't work either.
The reason you cannot access the variable in your js file is that the variable 'uid' is defined in a different scope than the js file. Its the same thing as:
if(true) {
var a = 1;
}
if(true) {
// b will be undefined since 'a' was defined in another scope
var b = a;
}
// so
jQuery(document).ready(function({
// this is one scope
var a = 1;
});
jQuery(document).ready(function({
// this is another scope and b will be undefined
var b = a;
});
You need to store the uid in a hidden field like:
<intput type="hidden" id="hidUid" value="<?php echo (intval($uid)); ?>"/>
And then inside the scope of your javascript ($(document).ready)
var uid = $("#hidUid").val();

Post array of multiple checkbox values

Why is only one value of the "db" checkbox values array being sent to the server side script?
JQUERY:
$(".db").live("change", function() {
$(this).add($(this).next("label")).add($(this).next().next("br")).remove().insertAfter(".db:last + label + br");
var url = "myurl.php";
var db = [];
$.each($('.db:checked'), function() {
db.push($(this).val());
});
if(db.length == 0) {
db = "none";
}
$.post(url, {db: db}, function(response) {
$("#dbdisplay").html(response);
});
return true;
});
HTML:
<input type="checkbox" name="db[]" class="db" value="track"/><label for="track">track</label></br>
<input type="checkbox" name="db[]" class="db" value="gps"/><label for="gps">gps</label></br>
<input type="checkbox" name="db[]" class="db" value="accounting"/><label for="accounting">accounting</label></br>
Edit: I ended up answering my own question, but does anyone have documentation (or an explanation) of why this is necessary? It was difficult for me to find the exact answer (thus the posthumous post).
I agree with #jjclarkson. Just to add, instead of pushing your ids to an array, you can use $.map:
$(".db").live("change", function() {
$(this).add($(this).next("label")).add($(this).next().next("br")).remove().insertAfter(".db:last + label + br");
var url = "myurl.php";
var db = $('.db:checked').map(function(i,n) {
return $(n).val();
}).get(); //get converts it to an array
if(db.length == 0) {
db = "none";
}
$.post(url, {'db[]': db}, function(response) {
$("#dbdisplay").html(response);
});
return true;
});
You need to have the square brackets to specify an array [] on the submitted variable name.
{'db[]': db}
$(".db").live("change", function() {
$(this).add($(this).next("label")).add($(this).next().next("br")).remove().insertAfter(".db:last + label + br");
var url = "myurl.php";
var db = [];
$.each($('.db:checked'), function() {
db.push($(this).val());
});
if(db.length == 0) {
db = "none";
}
$.post(url, {'db[]': db}, function(response) {
$("#dbdisplay").html(response);
});
return true;
});
var checkeditems = $('input:checkbox[name="review[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
$.ajax({
type: "POST",
url: "/index.php/openItems/",
data: "ids=" + checkeditems,
success: function(msg) { $(".mainContainer").html(msg); }
});
$('input[name="mycheckboxes"]:checked').map(function(){
return $(this).val();
}).get().join(",");
then explode in PHP
$mycheckboxes = explode(',',$_GET['mycheckboxes']);

Categories