Check/uncheck checkbox depend on data come from database - javascript

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');
}
});
}

Related

Javascript addClass or removeClass not working in subclass after ajax call

I have an ajax script that inserts a value if it is not in the database and removes the value if it is already there, and returns 1 or 0 accordingly, based on the return value it adds or removes a class in the existing button.
I have tried with find() to take the subclass value but still it is not working.
<form method="post" class="wish" action="process.php">
<input type='hidden' id='value' name='value' value='1'>
<button type="submit" class="card-fox list active" >fan</button>
</form>
This line has active I want it to be added if it is not there and remove if it is there.
below is the ajax:
$(document).ready(function (e) {
$(".wish").on('submit', (function (e) {
e.preventDefault();
$.ajax({
url: "process.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
if (data == 1) {
$(".list", this).addClass("active");
}
if (data == 2) {
$(".list", this).removeClass("active");
}
},
error: function (e) {}
});
}));
});
the problem is that although the ajax script is being executed and everything else is working, the active class is neither adding or removing.
Use:
$(".wish").find('button').addClass("active");
$(".wish").find('button').removeClass("active");
Or:
//when form is submit, make a copy of this
let self = this;
//send ajax
//in success ajax
$(self).find('button').addClass("active");
Greetings!
The this in your ajax success function is not the form.
You can set the context of the ajax call to the for to address this.
$.ajax({
context: this, //<- this this is the form, and tells jQuery to set the this of its callbacks to the form

Laravel - AJAX POST Array of Choices from Checkboxes

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)

How to POST Jquery Ajax When a hidden input value change

How to post an AJAX Request when a hidden input value change ?.
The value in hidden input is always change because of Jquery autocomplete.
I tried $("#id_pt_asal").change(function(event){ but nothing post on console log.
is there any way how to do it ?
Here the HTML
<input type="hidden" name="id_pt_asal" id="id_pt_asal" value="" />
Here the AJAX script
$(document).ready(function() {
$("#id_pt_asal").change(function(event) {
var formData = {
'id_pt_asal': $('input[name=id_pt_asal]').val()
};
$.ajax({
type: 'POST',
url: '<?=base_url()?>akademik/prodi_pindah',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
if (data.hasil_prodi == true) {
$("#id_prodi_asal").html(data.html);
}
})
event.preventDefault();
});
});
First thing you need to get element of Jquery autocomplete. I assume your jquery autocomplete input given id is txt
$(document).ready(function(){
$("#txt").on("keypress",function(){
//$("#id_pt_asal").val($(this).val());
$("#id_pt_asal").trigger('change');
});
$("#id_pt_asal").on("change",function(event){
console.log(event);
//ajax call
});
});

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
?>

checkbox on change ajax call

I have one checkbox. I want when I checked the checkbox so I get the 1 and then update a mysql query through that get value.
I also want if I unchecked the checkbox so I get a value 0 so then I again update the mysql query. Help me. it should be done with ajax call. code will be in PHP.
HTML code
<input type="checkbox" name="action1" id="action1" title="Action 1" value="1" onclick="return Populat_Industry('set_home_vid.php');"/>
ajax call
<script>
function Populat_Industry(url){
var value=$(#action1).val();
$.ajax({
type: "POST",
url: url,
async: true,
data: "value="+value,
success: function(msg){
//alert('Success');
if(msg !='success'){
//alert('Fail');
}
}
});
}
</script>
PHP code
if($_POST['action1']=='1'){
$query= mysql_query("UPDATE homevideos SET is_active = '1
}
else{
mysql_query("UPDATE homevideos SET is_active = '0')
echo 'success';
Ajax call is async. you cannot use return with it this way. Write checkbox change event in jquery and send ajax call.
Do like this:
HTML:
<input type="checkbox" name="action1" id="action1" title="Action 1" value="1"/>
JQUERY:
$("#action1").change(function () {
var value = $(this).val();
$.ajax({
type: "POST",
url: "set_home_vid.php",
async: true,
data: {
action1: value // as you are getting in php $_POST['action1']
},
success: function (msg) {
alert('Success');
if (msg != 'success') {
alert('Fail');
}
}
});
});
HTML :
<input type="checkbox" name="action1" id="action1" title="Action 1" value="1" url="set_home_vid.php" />
JQuery:
<script>
$("#action1").change(function(){
var value = $(this).val();
var url = $(this).attr("url");
$.ajax({
type: "POST",
url: url,
data: "value="+value, //POST variable name value
success: function(msg){
if(msg =='success'){
alert('Success');
}
else{
alert('Fail');
}
}
});
});
</script>
PHP:
if($_POST['value']==1){ //as used variable name "value" in ajax post data
$query= mysql_query("UPDATE homevideos SET is_active = 1"); //query was incomplete and missing ";"
echo 'success';
}
else{
mysql_query("UPDATE homevideos SET is_active = 0); // missing ";"
echo 'success';
}
Maybe you could use the .is jquery method
something like this:
$("#i").bind("change",function(){
if($(this).is(":checked"))
// set value for ajax
else
// set another value for ajax
// ajax code here
});
You forgot to put quotes around your call to get the input value:
var value=$("#action1").val()

Categories

Resources