I am working on a multiple selection using chosen jquery. the values are already stored on an array. But im having problem with the AJAX post to send the values of the array to the controller. I already looked over the internet for solutions, spent so much time on reading articles here but non of it solves my problem. Please help.
Here is my code:
$(document).ready(function(){
var status = [];
var method = $(this).attr('data-method'); // confirm(status);
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
$("#test").chosen().change(function(e, params){
console.clear()
$("#test :selected").each(function(i,selected)
{
status[i] = $.trim($(selected).text());
// status.push($(this).val());
})
console.log(status);
var new_var = JSON.stringify(status);
// $('.statusArray').click(function(e){
$.ajax({
type: "POST",
url: "<?php echo site_url('request/buyer') ?>",
data: { data: new_var }
}).done(function(data) {
console.log(data);
alert( "Data Send:");
}).fail(function() {
alert( "Data Not Send" );
});
e.preventDefault();
enter code here
// });
}); });
Related
I'm working on my first php/SQL database project and my goal is to store an array of checkbox values into a database.
On clicking the submit on the checkbox form, i am trying to post the array of checkbox values from my jquery doc to index.php
The success response is my index.php page, which i think is correct, so it all seems correct for me and i'm having a hard time figuring why
My array is generated from a series of .push() calls that update to determine when a box is checked it not and only submitted when i click my form submit, which should trigger the ajax post.
var checkArr =
[
{id: "CB1", val: "checked"},
{id: "CB3", val: ""},
{id: "CB5", val: ""},
{id: "CB4", val: "checked"},
{id: "CB2", val: ""}
];
//SUBMIT CHECKBOX VALUES TO PHP
$('#submitCheck').on('click', function(){
$.ajax({
url: 'index.php',
type: 'POST',
data: {checkArr:checkArr},
cache: false,
success: function(response){
alert("ok");
console.log(response);
}
});
});
Here however when i check to see if the post worked i only return 'is not set'.
if(isset($_POST['checkArr'])){
$arr = $_POST['checkArr'];
echo $arr;
} else {
echo 'Is not set';
}
I know there are many similar questions but i haven't found a solution in any of them unfortunately.
I found one thread that mentioned it might be redirecting me before the post can be processed so i removed the action from my form and nothing changed. I tried to stringify my output as json and still the same problem (even if stringify is redundant because of jquery).
Edit: Full code snippet
var checkArr = [];
//COLOUR ITEMS ON PAGE LOAD
$(document).ready(function(){
var box = $(':checkbox');
if(box.is(':checked')){
box.parents("li").removeClass('incomplete');
box.parents("li").addClass('complete');
} else {
box.parents("li").removeClass('complete');
box.parents("li").addClass('incomplete');
}
});
//DELETE ITEM
$(document).on('click','.delete', function(){
console.log('DELETED');
var id = $(this).attr('id')//get target ID
var item = $(this).closest('li');//targets the li element
//AJAX
$.ajax({
url: 'delete.php',
type: 'POST',
data: { 'id':id },
success: function(response){
if(response == 'ok') {
item.slideUp(500,function(){
item.remove();
});
} else if(response == 'error') {
console.log("error couldn't delete");
} else {
console.log(response);
}
}
});
});
//CREATE ARRAY OF CHECKBOX VALUES
$('#checkform').on('click','.boxcheck', function(){
var check = $(this).prop("checked");
var val = "";
var tempId = $(this).attr('id');
if(check === true){
val = "checked";
console.log(val);
var tempArr = {
"id": tempId,
"val": val
};
checkArr.push(tempArr);
} else if (check === false){
val = "";
console.log(val);
for (var i = checkArr.length - 1; i >= 0; --i) {
if (checkArr[i].id == tempId) {
checkArr[i].id = tempId;
checkArr[i].val = val;
}
}
}
console.log(checkArr);
});
//CHANGE COLOUR OF ITEMS
$(':checkbox').change(function(){
var current = $(this);
if(current.is(':checked')){
current.parents("li").removeClass('incomplete');
current.parents("li").addClass('complete');
} else {
current.parents("li").removeClass('complete');
current.parents("li").addClass('incomplete');
}
});
//SUBMIT CHECKBOX VALUES TO PHP
$('#submitCheck').on('click', function(e){
e.preventDefault();
console.log(checkArr);
$.ajax({
url: 'index.php',
type: 'POST',
data: {checkArr:checkArr},
cache: false,
success: function(response){
alert("ok");
}
});
});
I tried your code and it's working perfectly for me.
Now the only thing I can think of is your url in your ajax request. make sure you are really submitting to index.php.
You can use JSON.stringify() to submit the array from ajax to php
Posting here to update just in case anyone has a similar problem, the code itself was correct(sort of), after a lot of digging and asking around, it turns out the local server i was using, XAMPP, had too small a POST upload limit hence the empty array on the php side, increasing the php.ini upload limit from 2mb to 10mb finally fixed it!
I want to display the values in datatable. How to retrieve the object value in ajax success function..
AJAX
$(function(){
$(document).on("click", "#submits", function(e) {
e.preventDefault();
var password = $("#password").val();
alert(password);
$.ajax({
type: "POST",
url: "db/add.php",
data: "password="+password,
success: function(results){
alert( "Data Saved: " + results );
var obj = JSON.parse(results);
}
});
e.preventDefault();
});
});
</script>
Perhaps you can try this -
$("#submits").bind("click", function(e) {
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "db/add.php",
data : "password="+password,
success : function(results) {
alert("Data Saved: "+results);
var userInfo = JSON.parse(results);
//Output the data to an HTML element - example...
$(".user-name").html(userInfo.patient_name);
}else{
console.log('No user info found');
}
},
error : function(a,b,c) {
console.log('There was an error getting user info.');
}
});
});
//HTML element for data
<p class="user-name"></p>
I've added an HTML element you can simply output the data to. Not sure how you'd like the data to be output but this is simply an example.
Just some quick notes on your code from your original post -
You must set the dataType to json when working with/parsing json. See Documentation.
Once you assign your data to a variable, you need to access that data by declaring the variable and then the data name, such as obj.patient_name.
I've done the best I can to help.
Good luck.
Try this code :
$(results.patient_password).each(function(i,v){
console.log(v.id);
});
use data-type:json,
in your jquery
i have a footer.php file and i already wrote the code in ajax which is blow here when i alert data variable then i got id but in success function i didn't get anything .olease somebody help me
© Copyright 2013-2015 Khan's
Boutique
<script>
jQuery(window).scroll(function(){
var vscroll = jQuery(this).scrollTop();
jQuery('#logotext').css({
"transform" : "translate(0px, "+vscroll/2+"px)"
});
jQuery('#back-flower').css({
"transform" : "translate("+0+vscroll/5+"px, -"+vscroll/12+"px)"
});
jQuery('#fore-flower').css({
"transform" : "translate(0px, -"+vscroll/2+"px)"
});
});
function detailsmodal(id){
var data = 'id='+ id;
//alert(data);
jQuery.ajax({
url: '/boutique/includes/detailsmodal.php',
method:"post",
data : data,
success: function(data){
//alert(data);
jQuery('body').append(data);
jQuery('#details-modal').modal('toggle');
},
error: function(){
alert("something went wrong!");
}
});
};
</script>
</body>
</html>`
Your var data should be like this :
var data = {
id: id
}
And in success, the data is the returned to the ajax where the ajax request is sent.
i really struggle to get the POST value in the controller .i am really new to this..Please someone share me some light..being in the dark for long hours now.
i had a checkboxes and need to pass all the ids that had been checked to the controller and use that ids to update my database.i don't know what did i did wrong, tried everything and some examples too like here:
sending data via ajax in Cakephp
found some question about same problem too , but not much helping me( or maybe too dumb to understand) . i keep getting array();
please help me..with my codes or any link i can refer to .here my codes:
my view script :
<script type="text/javascript">
$(document).ready(function(){
$('.checkall:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$('#button').click( function (event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
var value = memoData.join(", ")
//alert("value are: " + value);
//start
$.ajax({
type:"POST",
traditional:true;
data:{value_to_send:data_to_send},
url:"../My/deleteAll/",
success : function(data) {
alert(value);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});
//end
} ); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
my controller :
public function deleteAll(){
if( $this->request->is('POST') ) {
// echo $_POST['value_to_send'];
//echo $value = $this->request->data('value_to_send');
//or
debug($this->request->data);exit;
}
}
and result of this debug is:
\app\Controller\MyController.php (line 73)
array()
Please help me.Thank you so much
How about this:
Jquery:
$(document).ready(function() {
$('.checkall:button').toggle(function() {
$('input:checkbox').attr('checked','checked');
$('#button').click(function(event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
//start
$.ajax({
type: 'POST',
url: '../My/deleteAll/',
data: {value_to_send: memoData},
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});//end ajax
}); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
In controller:
public function deleteAll()
{
$this->autoRender = false;
if($this->request->is('Ajax')) { //<!-- Ajax Detection
$elements = explode(",", $_POST['value_to_send']);
foreach($elements as $element)
{
//find and delete
}
}
}
You need to set the data type as json in ajax call
JQUERY CODE:
$.ajax({
url: "../My/deleteAll/",
type: "POST",
dataType:'json',
data:{value_to_send:data_to_send},
success: function(data){
}
});
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; }