Toggle Checkbox and send query in background to update database - php

As soon as someone toggles a checkbox. I want a the value sent to a php page for it to update it in my database.
HTML:
<div class="form-group">
<div class="tg-optionbox">
<span>Promotional Video</span>
<span class="tg-iosstylcheckbox">
<input type="checkbox" id="video" name="video" value="video">
<label for="video"></label>
<div id="echo2"></div>
</span>
</div>
</div>
JQUERY:
$(document).ready(function(){
$("input[type=checkbox]").click(function () {
$.ajax({
type: "POST",
url: "get/update-feature.php",
data: {
value: $('input:checkbox:checker').val()
},
success: function(data) {
$('#echo2').html(data);
}
});
});
});
PHP:
<?
$sent_value = $_POST['value'];
if(isset($sent_value)){
//update database
echo "updated";
}else{
//update database
}
?>
Currently, my jquery doesn't work. How I need it:
They click the orange checkbox toggle
Jquery recognises this and sends the checkbox value to my php page
my php page gets the value and puts it in the database

instead of echo use "return true" if success else false in php code
$(document).ready(function(){
$("#video").click(function () {
$.ajax({
type: "POST",
url: "get/update-feature.php",
data: {
value: $('input[type=checkbox]').val()
},
success: function(data) {
$('#result').html(data);
}
});
});
});
<div class="form-group">
<div class="tg-optionbox">
<span>Promotional Video</span>
<span class="tg-iosstylcheckbox">
<input type="checkbox" id="video" name="video" value="video">
<label for="video"></label>
<div id="echo2"><p id="result"></p></div>
</span>
</div>
</div>
The error is in $('input:checkbox:checker').val() so the value is not sent to php file and the success method expects a return value in php. We need to use "return" instead of "echo"

Hope this can help you.
HTML: Not Changed
<div class="form-group">
<div class="tg-optionbox">
<span>Promotional Video</span>
<span class="tg-iosstylcheckbox">
<input type="checkbox" id="video" name="video" value="video">
<label for="video"></label>
<div id="echo2"></div>
</span>
</div>
</div>
JavaScript: Changed
Replaced: value: $('input:checkbox:checker').val() by: value: $(this).prop("checked") ? 1 : 0
You have to send the value of the clicked checkbox. So you must use $(this).
To get the value of the checkbox use .prop("checked"). If the returned value is true, then it is checked. If it is false, then it is not checked.
So if the checkbox is checked, 1 is sent. If not, 0 is sent
$(document).ready(function(){
$("input[type=checkbox]").click(function () {
$.ajax({
type: "POST",
url: "get/update-feature.php",
data: {
value: $(this).prop("checked") ? 1 : 0
},
success: function(data) {
$('#echo2').html(data);
}
});
});
});
PHP: Changed
If the value is equal to 1 or value equal to 0
<?php
$sent_value = $_POST['value'];
if(isset($sent_value)){
if ($sent_value == 1) {
echo "Checked" ;
}
else {
echo "Un Checked" ;
}
}
else{
echo "Error" ;
}
?>

Use .change() event handler :
$('input:checkbox').change(function () {
var name = $(this).val();
var check = $(this).attr('checked');
//Your Ajax code
});

Related

How to select radio button and label with jquery

I have a problem with my radio button.
Since i styled my radio buttons, the function is not working as it should.
I've heard somewhere that i have to change something in my jquery, but i dont know what.
Can someone help me?
here is the Html code
<div class="form-group">
<div class="form-check">
<input class="form-check-input" name="state" data-order="<?php echo $obj->order_id; ?>" value="1" type="radio" id="gridCheck1"
<?php if($obj->status == '1'){ echo 'checked'; } else { ''; } ?> >
<label class="form-check-label" for="gridCheck1">
Koude producten
</label>
</div>
</div>
Script
$(document).ready(function(){
$('#gridCheck1,#gridCheck2,#gridCheck3').click(function() {
if(this.checked){
$.ajax({
type: "POST",
url: 'change_state.php',
data: {
state: $(this).attr('value'),
order_id: $(this).data('order'),
}, //--> send id of checked checkbox on other page
success: function(data) {
$('#container').html(data);
},
error: function() {
//alert('it broke');
},
complete: function() {
setInterval(function() {
location.reload();
}, 1000);
}
});
}
});

Jquery Radio button value not changing

Need some help, ive searched google and have no luck.
I am trying to update my radios-button's value in the div class "size-number". That value I want use it within the ajax request below. When i inspect element, the radio-button has the updated value of the button available but when i console.log it in jquery, it gives me the same initial value, despite which i pick. Ive tried setting the radio-buttons to checked="checked". Also i believe its a matter of the default value. Ive also tried input validation within jquery. In addition, ive attempted to reference the input ("input[name='radiobten']:checked") in jquery as well. any suggestions would very appreciated!
$(".size-number").click(function(){
var modelid = $("#modelval").attr('value');
console.log(modelid);
$.ajax({
url: '"Example API"',
data: [],
dataType: 'json',
type: "GET",
success: function(res){
var newarr = (res).filter(function(indx){
return indx.model_cat_id == modelid
});
console.log(newarr)
$('modelselect').slideToggle(200).html(res);
}});
});
<?php foreach ($brands as $brand){ ?>
<div class="search-select">
<i class="fas fa-chevron-down"></i>
<a href="/<?php echo $brand->full_slug.$urlSize; ?>">
<?php echo $brand->name; ?></a>
</div>
<?php
$slugCurrent = $brand->slug;
foreach ($models as $model){
if($model->brand_id == $brand->id){
if(is_null($model->model_cat_id)){?>
<div class="size-number" style="display: none;">
<?php echo $model->name; ?><input type="radio" id="modelval" name="radiobten" value="<?php echo $model->id?>"/>
</div>
<?php
}
}
}
}?>
You cannot have multiple element with same id i.e : modelval. This will always give you value of first radio button no matter which button you choose.Instead use class to get value of radio button.So ,onclick of div you can use $(this).find("yourclassname").attr('value') to get value of that particular button only.
Demo Code :
$(".size-number").click(function() {
//div->find closest modelval->value
var modelid = $(this).find(".modelval").attr('value');
console.log(modelid);
$.ajax({
url: '"Example API"',
data: [],
dataType: 'json',
type: "GET",
success: function(res) {
var newarr = (res).filter(function(indx) {
return indx.model_cat_id == modelid
});
console.log(newarr)
$('modelselect').slideToggle(200).html(res);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="size-number" >
Abc<input type="radio" class="modelval" name="radiobten" value="1"/>
</div>
<div class="size-number" >
Xyz<input type="radio" class="modelval" name="radiobten" value="2"/>
</div>

Ajax html input value appears empty

I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};

My PHP script for ajax is returning blank value

sbms.php
<?php
header('Access-Control-Allow-Origin: *');
if(isset($_POST['signup']))
{
$id = $_POST['val'];
echo $id;
}
?>
index.html
<form>
<label class="item-input">
<span class="input-label">ID</span>
<input type="text" id="cid">
</label>
<label class="item-input">
<button class="button button-block button-positive" id="signup">Submit</button>
</label>
</form>
<div class="card">
<div class="item item-text-wrap">
<p id="res"></p>
</div>
</form>
ajax script:-
$(document).ready(function(){
$('#signup').click(function(){
var data = $('#cid').val();
$.ajax({
type : "POST",
data : val,
url : 'http://127.0.0.1/ionic/sbms.php',
crossDomain : true,
success : function (data) {
alert(data);
}
});
});
});
I am just trying to a dummy response from the server but the response I get is totally blank. I am not able to figure out the problem
You're not sending a signup value, you're just sending in an unnamed value so your PHP script is not entering the if condition. Try changing your ajax call to this:
$.ajax({
type : "POST",
data : { val: val, signup: true }
url : 'http://127.0.0.1/ionic/sbms.php',
crossDomain : true,
success : function (data) {
alert(data);
}
});

Cancel submit jquery

This is a part of the code from a form requesting data to check if the email alredy exist. The thing is, the program is supposed to return 0 if there is no any mail like this. It dont work properly, because the program keep sending the data, even if the mail is not correct.
If you want more info, or i am missing something let me know. Thanks in advance.
$(document).ready(function () {
$("#enviar").click(function(e) {
e.preventDefault();
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = false;
}else{
$("form").unbind('submit').submit();
}
}
});
if (error){
return false;
}
});
});
And here is my compruebaEmail.php
<?php require_once('connections/vinoteca.php'); ?>
<?php
mysql_select_db($database_vinoteca, $vinoteca);
$user = $_POST['b'];
if(!empty($user)) {
comprobar($user);
}
function comprobar($b) {
$sql = mysql_query("SELECT * FROM usuarios WHERE email = '".$b."'");
$contar = mysql_num_rows($sql);
if($contar == 0){
echo 0;
}else{
echo 1;
}
}
?>
And here goes the POST
<form method="POST" name="form1" action="validarUsu.php">
<div class="row">
<span class="center">Email</span>
</div>
<div class="row">
<input type="text" name="email" id="email2" value="" size="32" />
</div>
<div class="row">
<span class="center">Contraseña</span>
</div>
<div class="row">
<input type="password" name="password" id="id2" value="" size="32" />
</div>
<div class="row">
<span id="error"> </span>
</div>
<div class="row">
<input type="submit" value="Acceder" id="enviar" size="20">
</div>
<div class="row">
Recuperar contraseña
</div>
</form>
The problem is you're returning false from your Ajax function. You need to return false from your click function. Give this a try:
$("#enviar").click(function() {
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = true;
}
}
});
if (error)
return false;
});
If all you want is canceling the submitting event, then :
Either :
1 - Add the event arg to your click handler :
$("#enviar").click(function(event){
2 - use event.preventDefault(); when you want to cancel the submit message :)
or change the "return false;" location so that it will be triggered in the "click" handler scope and note the "success" scope e.g with a boolean that would represent if there is an error (EDIT : that is Styphon' solution)
Documentation here : http://api.jquery.com/event.preventdefault/

Categories