I have a page that has a bunch of tick boxes, these are identified with a name="a number".
When a button is clicked, I have an JavaScript function that creates a new array with the numbers of the boxes ticked. This gets sent to a page 'test.php'.
It returns:
Array
(
[data] => [null,"47284","47282","47281","47280","47279","47278","47277","47276","47269"]
)
When I try and explode this array I get an array to string conversion error.
What am I doing wrong?
I need to get these numbers separated so I can do an SQL query for each.
JavaScript code:
<script>
var selected = new Array();
function showMessage() {
var selected = Array();
$('input:checked').each(function() {
selected.push($(this).attr('name'));
});
var answer = confirm('Are you sure you want to send these emails again?');
if(answer) {
var jsonString = JSON.stringify(selected);
$.ajax({
url: "../../test.php",
type: "POST",
data: {data : jsonString},
success: function(data){
alert(data);
}
})
}
}
</script>
<SCRIPT language="javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectallsent").click(function () {
$('.yes').prop('checked', this.checked);
});
$("#selectallprogress").click(function () {
$('.no').prop('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".yes").click(function(){
if($(".yes").length == $(".yes:checked").length) {
$("#selectallsent").prop("checked", "checked");
} else {
$("#selectallsent").removeAttr("checked");
}
});
$(".no").click(function(){
if($(".no").length == $(".no:checked").length) {
$("#selectallprogress").prop("checked", "checked");
} else {
$("#selectallprogress").removeAttr("checked");
}
});
});
</script>
test.php code:
<?
print_r($_POST);
?>
I know that I need to do something more on the test.php page but I would like to know what that is.
Two things you need to do ....
First one is to not stringify the selected object (jquery will deal with this for you)
function showMessage() {
var selected = Array();
$('input:checked').each(function() {
selected.push($(this).attr('name'));
});
var answer = confirm('Are you sure you want to send these emails again?');
if(answer) {
$.ajax({
url: "../../test.php",
type: "POST",
data: {data : selected},
success: function(data){
alert(data);
}
})
}
}
Then on the PHP side you can just access the values via
print_r($_POST["data"]);
This will be an array of your inputs.
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!
How can I load data from my PHP response via ajax into a panel?
My PHP outputs correctly and I can see a table in the response, but I can;t get it to build the data on my webpage.
Here is my jquery/ajax so far. It passed the value to PHP correctly and PHP builds the table via its echo, but what am I missing for AJAX to display the table?
PHP:
<?php
foreach ($lines as $value) {
echo "<input name='data[]' value='$value'><br/>";
}
?>
JQUERY:
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
$('#panel').load(result);
}
})
return false;
});
});
The answer to this was two fold.
I was attempting to append to my main div, which apparently can't happen. I created a new empty div and was able to load the results there.
Beyond that, the comments to change .load(results) to .html(results) were needed.
The correct jquery code is below.
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
console.log(result);
$('#test').html(result);
}
})
return false;
});
});
move your function from:
$.ajax({...,success: function(){...}});
to
$.ajax({..}).done(function(){...});
if it doesn't work, try to add async:false into the ajax object...
$.ajax({...,async:false}).done(function(){...});
Hope it helps... =}
I am trying to send my values using ajax from original page to the page one and then to page 2 this is my code but it seems to be not working.
This is the code on the original page here I have only given the script as I am just using the click event of my div to send the values
<script>
function displayRecords(numRecords, pageNum,x,catg) {
$.ajax({
type: "GET",
url: "button.php",
data: {
show:numRecords,
pagenum:pageNum,
val12:x,
catg12:catg,
},
cache: false,
success: function(data) {
$("#tabs1-html").html(data);
}
});
}
function changeDisplayRowCount(numRecords) {
displayRecords(numRecords, 1);
}
$(document).ready(function() {
$('.tab12').click(function(){
var catg=$('#cat').val();
var x =$(this).val();
displayRecords(5,1,x,catg);
});
});
</script>
now for the code on my page 1
here
<script type="text/javascript">
function get_data(no,x,catg) {
$.ajax({
type:'post',
url:'question_call.php',
data:{
row_no:no,
X:x,
category:catg,
},
success:function(response) {
document.getElementById("pagination_div").innerHTML=response;
}
});
}
$(document).ready(function() {
$('#tota_page_div').click(function(){
var catg = $category.val();
var x = $X.val();
get_data(no,x,catg);
});
});
</script>
and these are the values where i saved the previous ones
$X = $_GET['val12'];
$category = $_GET['catg12'];
Now when I try to use print_r on my page 2 it only shows row_no not catg12 and val12
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){
}
});
I have created a button on my website when it is clicked, I sent data on some php file using ajax and return the results. The code I am using is below,
My Goal :
When that button is clicked for the first time. I want to send the data on some php file using ajax and return the results, and
When it is clicked for the second time, I just want to hide the content, and
When it is clicked for the third time, I just want to show the container without calling the ajax again.
jQuery:
$(function() {
$('#click_me').click(function(){
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
});
});
Html :
<input type="button" id="click_me" value="Click Me"/>
<div id="container"></div>
The jQuery way would be like this:
$(function() {
$('#click_me').one('click', function() {
$.ajax({
// ... other params ...,
success: function(result) {
$('#container').html(result).show('fast');
$('#click_me').click(function() {
$('#container').toggle('fast');
});
});
});
});
});
http://api.jquery.com/one/
http://api.jquery.com/toggle/
You can use the counter
http://forum.jquery.com/topic/making-a-number-counter
(function () {
var count = 0;
$('table').click(function () {
count += 1;
if (count == 2) {
// come code
}
});
})();
JQuery Mouse Click counter
Working Example of your code :-
http://jsfiddle.net/2aQ2g/68/
Something like this should do the trick...
$("#click_me").click(function(){
var $btn = $(this);
var count = ($btn.data("click_count") || 0) + 1;
$btn.data("click_count", count);
if ( count == 1 ) {
$.ajax({
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php"
})
}
else if ( count == 2 ) {
$('#container').hide('fast');
}
else {
$('#container').show('fast');
$btn.unbind("click");
}
return false;
});
One way to do it would be to add a class call count using jQuery every time the user clicks on the button (http://api.jquery.com/addClass/) and you can get the count value in the handler and based on that you can handle the click appropriately.
You can do this by defining a simple variable counting the clicks.
$(function() {
var clickCount = 1; //Start with first click
$('#click_me').click(function(){
switch(clickCount) {
case 1: //Code for the first click
// I am just pasting your code, if may have to change this
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
break;
case 2:
//code for second click
break;
case 3:
//Code for the third click
break;
});
clickCount++; //Add to the click.
});