简体   繁体   English

PHP 单选按钮总是给出相同的值

[英]PHP Radio Button always gives same value

I'm trying to make a simple php radio button that has either a 'yes' or 'no' option, and I want to put the selected option in an email.我正在尝试制作一个简单的 php 单选按钮,该按钮具有“是”或“否”选项,并且我想将所选选项放在 email 中。 Everything seems to work except no matter what I do I always get the 2nd radio option (in this case 'no')一切似乎都有效,除了无论我做什么,我总是得到第二个单选选项(在这种情况下为“否”)

Here's my code, I've followed every related question and tutorial I can find but I'm a complete beginner with php and coding in general.这是我的代码,我已经按照我能找到的所有相关问题和教程进行操作,但我是 php 和一般编码的完整初学者。 Been at this problem for 7 hours today so any help is appreciated.今天在这个问题上待了 7 个小时,因此感谢您的帮助。

**I am building the site from a themeforest template, I'm barely a coder **我正在从主题森林模板构建网站,我几乎不是编码员

HTML code HTML代码

<form class="contact-form" action="php/send-email-moving-help.php" method="post" novalidate>
  <div class="helper-form-box">
    <div class="row">
      <div class="column width-6">
        <input type="text" name="fname" class="form-fname form-element large" placeholder="First Name*" tabindex="1" required>
      </div>
      <div class="column width-6">
        <input type="text" name="lname" class="form-lname form-element large" placeholder="Last Name*" tabindex="2" required>
      </div>
      <div class="column width-12">
        <input type="email" name="email" class="form-email form-element large" placeholder="Email Address*" tabindex="3" required>
      </div>
      <div class="column width-6">
        <input type="tel" name="telephone" class="form-telephone form-element large" placeholder="Phone*" tabindex="4" required>
      </div>
      <div class="column width-6 pt-10">
        <div class="field-wrapper radio-input">
          <p>Can we text you?&nbsp; &nbsp; &nbsp; </p>
          <input id="radio-1" class="form-element radio" name="radio-group-1" type="radio" value="yes">
          <label for="radio-1" class="radio-label">Yes</label>
          <input id="radio-2" class="form-element radio" name="radio-group-1" type="radio" value="no">
          <label for="radio-2" class="radio-label">No</label>
        </div>
      </div
    </div>
  </div
</form

PHP code PHP代码

$recipient = "my@email.address";

if($recipient === '') {
    returnAndExitAjaxResponse(
        constructAjaxResponseArray(
            FALSE,
            'RECIPIENT_IS_NOT_SET',
            array('error_message'=> 'RECIPIENT email address is not set. Please configure the script.')
        )
    );
}

// Check for empty required field
if(!isset($_POST["email"]) || !isset($_POST["fname"]) || !isset($_POST["message"])) {
    returnAndExitAjaxResponse(
        constructAjaxResponseArray(
            FALSE,
            'MISSING_REQUIRED_FIELDS',
            array('error_message'=> 'MISSING_REQUIRED_FIELDS should not be occurred.')
        )
    );
}

$fname  = filter_var($_POST["fname"], FILTER_SANITIZE_STRING);
$lname  = filter_var($_POST["lname"], FILTER_SANITIZE_STRING);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$telephone = $_POST["telephone"];
$radio = $_POST['radio-group-1'];

$email_content = "First Name: $fname\n";
$email_content .= "Last Name: $lname\n";
$email_content .= "Email: $email\n";
$email_content .= "Phone: $telephone\n";
$email_content .= "Can Recieve Texts: $radio\n\n";

// Check if sent
try {
$sendmailResult = mail($recipient, $subject, $email_content, $headers);
if( $sendmailResult === TRUE ) {
    returnAndExitAjaxResponse(
        constructAjaxResponseArray(
            TRUE
        )
    );
} else {
    returnAndExitAjaxResponse(
        constructAjaxResponseArray(
            FALSE,
            'ERROR_AT_PHPMAIL',
            array('error_information'=> error_get_last() )
        )
    );
}
} catch (Exception $_e) {
    returnAndExitAjaxResponse(
        constructAjaxResponseArray(
            TRUE,
            'ERROR_AT_PHPMAIL',
            array('error_message'=> $_e->getMessage())
        )
    );
}

/*
Construct ajax response array
Input: Result (bool), Message (optional), Data to be sent back in array
*/

function constructAjaxResponseArray ($_response, $_message = '', $_json = null) {
$_responseArray = array();
$_response = ( $_response === TRUE ) ? TRUE : FALSE;
$_responseArray['response'] = $_response;
if(isset($_message)) $_responseArray['message'] = $_message;
if(isset($_json)) $_responseArray['json'] = $_json;

return $_responseArray;
}

/*
Returns in the Gframe ajax format.
Input: data array processed by constructAjaxResponseArray ()
Outputs as a html stream then exits.
*/

function returnAndExitAjaxResponse ($_ajaxResponse) {
if(!$_ajaxResponse){
    $_ajaxResponse = array('response'=>false,'message'=>'Unknown error occurred.');
}
header("Content-Type: application/json; charset=utf-8");
echo json_encode($_ajaxResponse);
die();
}

JS that might be related可能相关的 JS

contactForm: function() {
            $(ia).submit(function(a) {
                a.preventDefault();
                var b = $(this),
                    c = b.parent().find(Y),
                    d = b.find(X),
                    e = b.find('input[type="email"]'),
                    f = b.find(Z),
                    g = b.find(_),
                    h = b.attr("action"),
                    i = b.attr("method"),
                    j = [],
                    k = encodeURIComponent(b.find("textarea[name=message]").val() + "\n"),
                    l = [];
                b.find("input:not([type=submit]),select,textarea").each(function(a, b) {
                    var c = $(b),
                        d = c.attr("name");
                    if (c.hasClass("form-aux") && d) {
                        var e = c.data("label") || d,
                            f = c.find("option:selected").text(),
                            g = c.val();
                        !g && c.is("select") ? g = e == f ? "Not selected" : c.find("option:selected").text() : "checkbox" != c.attr("type") || c.prop("checked") || (g = "Not checked"), l.push({
                            name: d,
                            label: encodeURIComponent(e),
                            value: encodeURIComponent(g)
                        })
                    } else d && "message" != d && j.push(d + "=" + encodeURIComponent(c.val()))
                });
                for (var m = 0; m < l.length; m++) {
                    var n = encodeURIComponent("\n") + l[m].label + "%3A%20" + l[m].value;
                    k += n
                }
                j.push("message=" + k), j = j.join("&");
                var o = !1,
                    p = !1,
                    q = !1;
                if (ja = ja.split(".").join(""), d.removeClass(ja), d.each(function() {
                        ($(this).attr("required") || $(this).children().attr("required")) && ($(this).is(":checkbox") ? $(this).is(":checkbox:checked") || (o = !0, $(this).addClass(ja)) : $(this).children().is("select") ? $(this).children().val() == $(this).children().find("option:selected").text() && (o = !0, $(this).addClass(ja)) : $(this).val() || (o = !0, $(this).addClass(ja)), o && c.hide().text(oa).fadeIn(200))
                    }), o || (p = !0), e.val() && !Oa.isValidEmail(e.val()) ? (c.hide().text(pa).fadeIn(200), e.addClass(ja)) : q = !0, "" !== f.val()) return !1;
                if (o && e.val() && !Oa.isValidEmail(e.val()) && c.hide().text(oa + " " + pa).fadeIn(200), p && q) {
                    var r = $(g).val();
                    $(g).css({
                        width: $(g).outerWidth() + "px"
                    }).val(la).attr("disabled", !0), c.hide().text(ka).fadeIn(200), $.ajax({
                        url: h,
                        type: i,
                        data: j,
                        dataType: "json"
                    }).done(function(a) {
                        try {
                            if (a.response === !0) c.text(ma), c.delay(1500).fadeOut(200), d.val("");
                            else {
                                var b = "undefined" == typeof a.json.error_message ? "There is a possibility that your message was not sent. Please check up the server or script configuration." : a.json.error_message;
                                c.hide().text(na + " " + b).fadeIn(200)
                            }
                        } catch (b) {
                            console.log("error in parsing returned ajax data: " + b), console.log(a), c.hide().text("Error occurred. Please see the console for details.").fadeIn(200)
                        }
                    }).fail(function(a, b, d) {
                        console.log("Error occured in processing your request:"), console.log(a), console.log("Text status"), console.log(b), console.log("Error thrown"), console.log(d), console.log("Servre response"), console.log(a.status), console.log("Response Text may contain error output from PHP"), console.log(qXHR.responseText), c.hide().text(na + " (Please see the console for error details.)").fadeIn(200)
                    }).always(function() {
                        $(g).css({
                            width: ""
                        }).val(r).attr("disabled", !1)
                    })
                }
            })
        },
        isValidEmail: function(a) {
            var b = new RegExp(/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i);
            return b.test(a)
        },

The reason is that in your JavaScript you are collecting all the <input> elements and create the object to send.原因是在您的 JavaScript 中,您正在收集所有<input>元素并创建要发送的 object。 in this line:在这一行:

b.find("input:not([type=submit]),select,textarea").each(function(a, b) {

Then you have 2 elements with same name for your radio button and the one with "No" value is the second one.然后,您的单选按钮有 2 个具有相同名称的元素,而具有“否”值的元素是第二个元素。 if you check your request parameters in the inspector window, you can see both of the values "Yes" and "No" are sending, but because "No" is the second one, your php is using it as the value.如果您在检查器 window 中检查您的请求参数,您可以看到两个值“是”和“否”都在发送,但是因为“否”是第二个,所以您的 php 使用它作为值。 So in your JavaScript, you have to get only the selected radio button and checkbox(if any) element, not all of them.因此,在您的 JavaScript 中,您必须只获取选定的单选按钮和复选框(如果有)元素,而不是全部。

You only need to change the line I mentioned earlier and exclude all checkbox and radio button elements and then include only checked checkbox and radio button elements like this:您只需要更改我之前提到的行并排除所有复选框和单选按钮元素,然后仅包括选中的复选框和单选按钮元素,如下所示:

b.find("input:not([type=submit],[type=checkbox],[type=radio]),select,textarea,:radio:checked,:checkbox:checked").each(function(a, b) {

You need to give each radio button a unique name.您需要给每个单选按钮一个唯一的名称。 Because each have the name 'radio-group-1' the second option will override the first.因为每个都有名称“radio-group-1”,所以第二个选项将覆盖第一个。

You can put them in an if statement.您可以将它们放在 if 语句中。

if($_POST(['radio-group-1') == 1 {
  $radio = "Yes";
} elseif($_POST['radio-group-2') == 1 {
  $radio = "No";
}

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

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