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']);
Related
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; }
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?
I am using jQuery & ajax to save a entire form in session which is being generated.
when I press the search button the
onclick="updateContentdata();
is called. which is doing following.
function updateContentdata() {
var updateSearchContent = $('#savelistdata').html();
var rowNumb = rowCount;
var inFileds = JSON.stringify(field_options);
// var inputValue = $('inptval_' + rowCount).val();
$.ajax({
type: "POST",
url: "<?= $HOMEPAGE_ROOT; ?>/ajax_listuser.php",
data: {
rowNum: rowNumb,
field_options: inFileds,
html: updateSearchContent
},
success: function (data) {
$('#searchusers').submit();
},
error: function (req, status, error) {
console.log(error)
}
});
}
ajax_listuser.php
<?php
session_start();
if(isset($_POST['html']) && isset($_POST['rowNum'])){
$_SESSION['searchContent'] = $_POST['html'] ;
$_SESSION['rowNumber'] = $_POST['rowNum'] ;
$_SESSION['field_options'] = $_POST['field_options'];
}
?>
Form is being saved in the session but I want to keep form values in the session. but it only keeping the form.
So basically I need
<input class="form-control" type="text" id="inptval_2" name="search_input_value[]" value="71347">
instead of
<input class="form-control" type="text" id="inptval_2" name="search_input_value[]">
Create this function first:-
function getHtml(div){
div.find("input, select, textarea").each(function () {
var $this = $(this);
if ($this.is("[type='radio']") || $this.is("[type='checkbox']")) {
if ($this.prop("checked")) {
$this.attr("checked", "checked");
}
} else {
if ($this.is("select")) {
$this.find(":selected").attr("selected", "selected");
} else {
$this.attr("value", $this.val());
}
}
});
return div.html();
}
and then modify your funciton:-
function updateContentdata() {
var updateSearchContent = getHtml($('#savelistdata'));
var rowNumb = rowCount;
var inFileds = JSON.stringify(field_options);
// var inputValue = $('inptval_' + rowCount).val();
$.ajax({
type: "POST",
url: "<?= $HOMEPAGE_ROOT; ?>/ajax_listuser.php",
data: {
rowNum: rowNumb,
field_options: inFileds,
html: updateSearchContent
},
success: function (data) {
$('#searchusers').submit();
},
error: function (req, status, error) {
console.log(error)
}
});
}
You will probably have to put those values back in the form, since the value="123" is not part of the html when someone fills the form. Iterate over the values you have and find the corresponding form-element, and set its value
I need to use the select2 object in my form. This is my form
http://i.stack.imgur.com/jVILq.jpg
There are many select html objects.
For instance If I would like to change the Customers select box into a Select2 object I have written this little snipped of code posted at jsfiddle.net but I cannot create a copy of this function for each select because it too difficult to maintain.
How have I to abstract it?
I have posted a sample here: http://jsfiddle.net/GcJgU/7/
I have already found a potential solution from the user Flip but it is not complete because I need to apply this JQuery object to all the input hidden html objects in the page.
This is an example:
$(".select2").select2({
ajax: {
url: $(this).attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = $(this).attr("field-id");
var fieldname = $(this).attr("fields-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
formatResult: function (object, container, query) {
console.log(object);
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = $(element).attr("field-id");
var fieldname = $(element).attr("fields-data");
$.ajax($(element).attr("url-searchid") + "/term/" + id, {
dataType: "json"
}).done(function (items) {
var data = {
id: items[0][fieldid],
text: items[0][fieldname]
};
callback(data);
});
}
});
Seems that $(this).attr("url-search") is not read and the search process doesn't start. I don't understand why.
Thanks guys
function select2Factory(select2) {
return {
minimumInputLength: 3,
ajax: {
url: select2.attr("callback-url"),
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var $this = $(this);
var id = select2.attr("field-id");
var fieldname = select2.attr("field-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var fieldname = select2.attr("field-data");
$.ajax("/admin/customers/searchbyid/term/" + id, {
dataType: "json"}).done(function(items) {
var data = {id: items[0][fieldid], text: items[0][fieldname] };
callback(data);
});
}
}
}
$el = $("#customer_id");
$el.select2(select2Factory($el));
I have solved in this way thanks to Flip:
http://jsfiddle.net/GcJgU/10/
HTML:
<input type="hidden" id="customer_id" title="" required="1" class="form-control select2 select2-offscreen" url-searchid="/admin/customers/searchbyid" url-search="/admin/customers/search" fields-data="lastname firstname ( company )" field-id="customer_id" value="12" name="customer_id" tabindex="-1">
JQUERY:
function select2Factory(select2) {
return {
ajax: {
url: select2.attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = item[mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
results.push({
id: item[id],
text: output
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
$.ajax(select2.attr("url-searchid") + "/term/" + id, {
dataType: "json"}).done(function(items) {
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = items[0][mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
var data = {id: items[0][fieldid], text: output };
callback(data);
});
}
};
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();