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!
Related
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
// });
}); });
Following is my auto suggest code created using jquery
$(document).ready(function(){
$(".input_search").keyup(function()
{
var finder = $(this).val();
var queryString = 'key_wrd='+ finder;
if(finder==''){//check if search is empty}
else
{
$.ajax({
type: "POST",
url: "searcher.php",
data: queryString,
cache: false,
success: function(html)
{
$(".display_found_query_cont").fadeIn();
$(".display_found_query-window").append(html);
}
});
}return false;
});
});
This code closes the suggest window and clears the enterse text
$(document).mouseup(function (e)
{
var search_res_container = $(".display_found_query_cont");
if (!search_res_container.is(e.target)&& search_res_container.has(e.target).length === 0)
{
search_res_container.fadeOut().html();
$(".search_field").val('');
}
});
what do i want to do ?
I want the results displayed to be cleared when the text entered is erased
So how do i do that?
try this code:
if(finder=='')
{
//check if search is empty
$(".display_found_query-window").html('');
}
As per your comment, you want to replace the old content with new result. So just chnage the below line in your ajax success.
$(".display_found_query-window").html(html);
In a JS file I am performing this function:
$(function() {
$(".button").click(function() {
//get the button's ID (which is equal to its row's report_id)
var emergency = this.id;
var button = this.attributes['name'].value;
var dataString = 'reportid=' + emergency;
alert(dataString);
if (button == "clockin") {
$.ajax({
type: "POST",
url: "/employeetimeclock.php",
data: dataString,
success: function() {
window.location = "/employeetimeclock.php";
}
});
} else if (button == "closereport") {
var r = confirm("Are you sure you want to close this report?\nThis action CANNOT be undone!");
if (r == true) {
$.ajax({
type: "POST",
url: "/closeemergencyreport.php",
data: dataString,
success: function() {
alert("Report Successfully Closed!");
window.location = "/closeemergencyreport.php";
},
error: function() {
alert("An error has occured, the report was not closed");
}
});
} else {
alert("Report was not closed.");
}
}
});
});
For the else if (to closeemergencyreport.php) the code in that php script is as follows:
<?php
require_once("models/config.php");
require_once("models/header.php");
require_once("models/dbconnect.php");
$reportid = $_POST['reportid'];
var_dump($_POST);
$sql = "UPDATE emergency_report SET report_closed = '1' WHERE report_id IN ( $reportid )";
//execute and test if succesful
$result = mysql_query($sql) or die(mysql_error());
if($result){
} else{
}
?>
I've done this same exact thing on 3 other pages and it works flawlessly however this is giving me trouble where on that php script the VAR_DUMP is saying it's returning an empty array. I've been reading and rereading the code for about an hour and a half now so I think i'm burnt out and need to have an outside view. Ive been all over the site and no one has had a solution that worked for me.
I know it's posting because fire bug is showing this on the form's page that the javascript is run on:
http://i.imgur.com/hItdVU1.png (sorry cant post images yet)
So I'm creating this form validator with PHP and jQuery.
The PHP code will check through the form and then return an array with fields that contain errors. Example: {"email":1,"password":1}
But now I have concerns regarding if no errors were to be found. The problem here is that I've included "return false" in the end of the code to prevent page redirection. I've read that this is bad code practice but not found another way that works as intended.
The second problem is how to pass the o-array into the $('input').each function. Right now it will say that all forms are valid since nothing was passed. If I use $.post instead of $.ajax this scope problem doesn't appear for some reason.
jQuery:
$(function() {
$('#register').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
type: 'GET',
url: url,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0) {
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
return false;
});
});
Fist, why are you submitting a form when you really don't want to?! Use a button instead and make the AJAX request from its click handler.
$('#registerButton').click(function() {
var form = $('#register')
var data = form.serialize();
$.ajax(...);
});
"The second problem is how to pass the o-array into the $('input').each"
What is the problem here? If you have an each() inside a success callback, you can use the data parameter that is passed to the callback (or o in your case) in that each().
Try this
$(function() {
$('#submit_button_id').click(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
var ret = true;
$.ajax({
type: 'GET',
url: url,
async: false,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0)
ret = false;
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
if(ret==true){
$('#register').submit();
}
});
});
still looking for a solution but not find yet, I have a function to manage different forms on same/differents pages
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
after loaded the page and form with an input type="button" named SEND
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
$('form.standard').submit();
});
all the values reach a php page via POST that made all the things (validating, insert in db, update log...) and answer with 'OK' if all OK (so the form in the modal window is substituted with custom message and fade out) or... if there is an error, php answer with some text that js popups with an alert keeping the modal window open with the form.
It's all ok BUT, if php answer with an error, with second click of button SEND the post is sent 2 times.
And if I make another error on second send, and click again the send button, the post values is sent three time... and so on.
What can I do? Where is my error?
thanks.
Try excluding submit block:
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
//$('form.standard').submit(function(event){
// event.preventDefault();
//change 'this' to form.standard
var modalWin = $('form.standard').parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
// }
and after loaded page:
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
//excluding submit event
// $('form.standard').submit();
});
Because $.ajax {} with type:"Post" is already a submit process and then when script call submit then it re-submit.
Hope this right and help
Is it possbile that somewhere in your code you bind the submit event to the form everytime you get the data back from the ajax-request?
I can't check this in the code you submitted here.
Create a global variable as flag
var flag = 0;
and check this flag while posting and reset it after completed
function formStantardAction(correctAnswer,addCustomData){
**if(flag == 1){
return false;
}
flag = 1;**
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
**flag = 0;**
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
I put some custom code at the beginning of your submit function - basically if a submit is in progress nothing should be done, but otherwise return an error message as usual.
var submitting = false; //initialise the variable, this needs to be out of the function!
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
if (submitting) {
return false; //if a submit is in progress, prevent further clicks from doing anything
} else {
submitting = true; //no submit in progress, but let's make one now
}
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}