简体   繁体   English

jQuery POST无法使用输入类型复选框

[英]Jquery POST not working with input type checkbox

I have build an subscription form which is working fine in php, I have now applied jquery to it to avoid page refresh. 我已经建立了一个可以在php中正常工作的订阅表单,现在我将jquery应用于它,以避免页面刷新。

HTML form HTML表格

<input name="newsletter" type="checkbox" id="checkbox" value="true">
<input name="offer" type="checkbox" id="checkbox" value="true">

PHP PHP

<?php
if(isset($_POST['newsletter']) && isset($_POST['newsletter'])==true){
    $newsletter = true;
} else {
    $newsletter = false;
}

if(isset($_POST['offer']) && isset($_POST['offer'])==true){
    $offer = true;
} else {
    $offer = false;
}

echo 'type1='.$newsletter;    
echo 'type2='.$offer;

$query = "UPDATE $table SET type1='$newsletter', type2='$offer' WHERE id=$id"; 
$result = mysqli_query($connection, $query) or trigger_error(mysqli_error($connection), E_USER_ERROR);

jQuery jQuery的

    var newsletter = false;
    var offer = false;
    var newsletterval = $("input[name='newsletter']").is(':checked');
    var offerval = $("input[name='offer']").is(':checked');

    if(newsletterval){
        newsletter=true;
    };

    if(offerval){
        offer=true;
    };

    $.post('../../subscribe.php', {newsletter:newsletter, offer:offer}, function(data){
        alert(data);            
    });

When usig php its working fine I can change subscription type, but jquery not working here it doesent change anything and I get alert from post data as type1=1type2=1 no matter what checkbox I check or uncheck. 当usig php正常工作时,我可以更改订阅类型,但jquery在这里不起作用,它的确没有更改任何内容,无论我选中或取消选中哪个复选框,我type1=1type2=1type1=1type2=1从发布数据中获取警报。

Please see and suggest any possible way to do this with jquery. 请查看并建议使用jquery的任何可能方法。

Thanks 谢谢

I guess you are trying something like this: 我猜您正在尝试这样的事情:

if(newsletterval){
    // use the string representation 'true' rather than a boolean value
    newsletter='true';
};

if(offerval){
    // use the string representation 'true' rather than a boolean value
    offer='true';
};

$.post('../../subscribe.php', {newsletter:newsletter, offer:offer}, function(data){
    alert(data);            
});

php code: php代码:

<?php

if(isset($_POST['newsletter']) 
  // Check the value of `$POST['newsletter']` rather than using isset() twice
  && $_POST['newsletter'] === 'true'){
    $newsletter = true;
}

... ...

HTTP transfers requests as strings therefore Javascripts true != PHP's true you need to use a string in PHP 'true' or 'false' HTTP将请求作为字符串传输,因此Javascripts true != PHP的true您需要在PHP中使用字符串'true''false'

As PHP will equate a string of any value to true your current code is looking for a boolean true which it will always find and so you will always execute the truthy parts of your if blocks and never the else blocks 由于PHP会将任何值的字符串等同为true,因此您当前的代码正在寻找一个布尔值true ,它将始终找到它,因此您将始终执行if块的真实部分,而永远不会执行else

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM