Laravel - AJAX POST Array of Choices from Checkboxes - javascript

I have an AJAX Post that I'm trying to fix, but with a multitude of checkboxes on the input, I'm getting stuck.
At the moment, say I've this:
<input type="checkbox" name="billToEmail[]" value="email1#email.com">email1#email.com
<input type="checkbox" name="billToEmail[]" value="email2#email.com">email2#email.com
And I've a button called "Send Notifications", which starts the following script:
<script>
$('.modal-footer').on('click', '.sendNotificationNow', function() {
$.ajax({
type:'POST',
url: '/shipments/sendNotifications',
data: {
'billTo': $('.billToEmail:checked').val(),
'shipTo': $('.shipToEmail:checked').val(),
'shipFrom': $('.shipFromEmail:checked').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#sentNotifications').modal('show');
toastr.error('Validation error - Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
toastr.success('Successfully Sent Notifications!', 'Success Alert', {timeOut: 5000});
$('div.notificationssent').fadeOut();
$('div.notificationssent').load(url, function() {
$('div.notificationssent').fadeIn();
});
}
},
});
});
</script>
Now, I'm sure my issues are popping up near the top, where I'm trying to "translate" the multiple values into the data variables. Should I be putting something besides .val()?
I've a few more fields like this that I need to work on with the multiple checkboxes but if I can get some help for the billToEmail alone, I'm sure I can fix the remainder.

First, you don't need the [] sign. So, your checkbox html will look like this :
<input type="checkbox" name="billToEmail" value="email1#email.com">email1#email.com
<input type="checkbox" name="billToEmail" value="email2#email.com">email2#email.com
Second, you need to push selected value on checkbox into javascript array variable using foreach :
var billToEmail= [];
$("input:checkbox[name=billToEmail]:checked").each(function(){
billToEmail.push($(this).val());
});
Third, you need to convert javascript array into string using JSON.stringify().
billToEmails= JSON.stringify(billToEmail);
Then after that, pass the billToEmails variable into your data in AJAX. So, it will look like this :
var dataString = "billTo="+billToEmails+"&shipTo="+$('.shipToEmail:checked').val()+"&shipFrom="+$('.shipFromEmail:checked').val()+"&_token="$('input[name=_token]').val();
$.ajax({
type:'POST',
url: '/shipments/sendNotifications',
data: dataString,
In order to PHP can fetch the array, you need to decode the billToEmails string first using json_decode in your controller.
$variable = json_decode($request->billTo,true);

Try this-
billtoemail = $('input[name='billToEmail[]']:checked").map(function () {
return this.value;
}).get();
or
billtoemail= new Array();
$("input[name='billToEmail[]']").each(function(){
billtoemail.push(this.value);
});
Now send this variable billtoemail like other variable in your ajax. In your controller you can get all the values by a simple foreach($request->billTo as $billtoemail)

Related

Post to PHP backend from javascript code

I have tried other answers but none have worked. The javascript code is supposed to submit a list of product id's to a php page. When products are selected, the submit button triggers the submit function.
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
console.log(ids);
//send the ids to api
bundle = [];
$('.bundle-list').empty();
$('.total').html('No item in bundle');
$('.submit').addClass('hide');
}
I have tried inserting this line in the function
document.getElementByID("test").value = bundle;
and a hidden tag within the form but can't get the var to submit to PHP
<input type="hidden" id="test" name="test" visibility="hidden"></input>
Where should the position of the hidden element be relative to the JS code? and any other methods of retrieving the ID's?
Either by $.post or $.get variable you can send data to PHP file, but i think you want to save pids in hidden field, but you are not update its value on submit. like
$('#test').html('YOUR DATA')
Try this..
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
$.ajax({
url: 'YOUR_URL HERE',
type: 'POST',
data: { qry: ids },
success: function(data) {
///WHEN SUCCESS
}
},
error: function(e) {
}
});
}

Send variable from Javascript to PHP using AJAX post method

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>

Delete function not working properly - Ajax

I have a pm system and I would like for all checked messages to be deleted. So far, it only deletes one at a time and never the one selected. Instead it deletes the one with the youngest id value. I'm new to ajax and all help is appreciated.
Here's my function:
function deletePm(pmid,wrapperid,originator){
var conf = confirm(originator+"Press OK to confirm deletion of this message and its replies");
if(conf != true){
return false;
}
var ajax = ajaxObj("POST", "php_parsers/pm_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "delete_ok"){
_(wrapperid).style.display = 'none';
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action=delete_pm&pmid="+pmid+"&originator="+originator);
}
You may need to modify your form in order to do this. You have to pass the checkboxes to your PHP script as an array through ajax.
<input type='checkbox' name='pm[]' value='1'>1<br>
<input type='checkbox' name='pm[]' value='2'>2<br>
<input type='checkbox' name='pm[]' value='3'>3<br>
With the checkboxes like this, PHP can handle an array as such:
$_POST['pm'];
You will need to modify your ajax script to be able to send the array, and probably change your PHP script to loop thru the array value it receives. It's probably expecting an integer (a single ID) and you are about to send it an array.
Revised Ajax Method:
$("#submit").on('click',function(e) {
e.preventDefault();
var data = {
'pmIds': $("input[name='pm[]']").serializeArray(),
'action' : 'delete_pm',
'originator' : 'whatever'
};
$.ajax({
type: "POST",
url: 'php_parsers/pm_system.php',
data: data,
success: function(result) {
window.console.log('Successful');
},
});
})

Check/uncheck checkbox depend on data come from database

I am trying to check or uncheck a checkbox depending on the data from mysql database. I use nusoap webservice/webclient to read data and data value can be 1 or 0.
My code is:
<input name="check1" type="checkbox" id="check1" class="sag">
<script>
function control() {
$.ajax({
type: "POST",
url: "check.php",
data: {
checkdata: 1
},
success: function(asd) {
if (asd == '1') {
document.getElementById('check1').setAttribute("checked", true);
alert('data is 1');
} else {
document.getElementById('check1').removeAttribute("checked");
alert('data is 0');
}
}
});
}
</script>
<body onload="control()">
With this code i can get data from database correctly and alert() works fine. But these codes don't add checked attribute to checkbox. How can i change check status of checkbox according to the data come from database on load of the page?
Since you are already using jQuery why don't you use jQuery methods to set the required values.
function control(){
$.ajax({
type: "POST",
url: "check.php",
data: {checkdata: 1},
success: function(asd){
$('#check1').prop("checked", asd == '1');
}
});
}

I need to get a variable between jQuery function and AJAX

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.

Categories

Resources