简体   繁体   English

Jquery Ajax 表单提交给 PHP 返回空响应

[英]Jquery Ajax form submit to PHP returns empty response

I'm trying to submit a form to PHP with Ajax so I don't have to reload the page.我正在尝试使用 Ajax 向 PHP 提交表单,因此我不必重新加载页面。 But when I click the Submit button, PHP post array is empty and I can't get any values when accessing values like: $google_recaptcha = $_POST['recaptcha']?? '';但是,当我单击提交按钮时,PHP 帖子数组为空,并且在访问以下值时无法获取任何值: $google_recaptcha = $_POST['recaptcha']?? ''; $google_recaptcha = $_POST['recaptcha']?? '';

Any suggestions?有什么建议么?

$(document).ready(() => {
    $("#appointment-form").on('submit', e => {
        e.preventDefault();
        console.log('Event triggered!');

        const name = $("#name").val();
        const email = $("#email").val();
        const phone = $("#phone").val();
        const company = $("#company").val();
        const service = $("#service").val();
        const country = $("#country").val();
        const day = $("#day").val();
        const timing = $("#timing").val();
        const message = $("#message").val();
        const csrfToken = $('input[name="csrf_token"]').val();

        $.ajax({
            type: 'post',
            url: 'private/shared/appointment_process.php',
            data: {
                name: name,
                email: email,
                phone: phone,
                company: company,
                service: service,
                country: country,
                day: day,
                timing: timing,
                message: message,
                csrfToken: csrfToken,
                recaptcha: grecaptcha.getResponse()
            },
            success: (result) => {
                console.log('Got response back');
                console.log(result);
                if (result === "Success") {
                    $("#form-success").html('Message has been sent!');
                    $("#form-success").show();
                } else {
                    $("#form-error").html(result);
                    $("#form-error").show();
                }
            }
        });

    });
});

PHP Code PHP 代码

<?php

require_once('../initialize.php');

$google_recaptcha = $_POST['recaptcha']  ?? '';
$name = h($_POST['name']  ?? '');
...

Form code表格代码

<form action="" method="post" id="appointment-form" class="login-form sign-in-form" data-toggle="validator">
    <div class="text_box row">
        <div class="col-lg-6">
            <input type="text" name="name" id="name" placeholder="Your Name *">
        </div>
        <div class="col-lg-6">
            <input type="email" name="email" id="email" placeholder="Your Email">
        </div>
    </div>
    <div class="text_box row">
        <div class="col-lg-6">
            <input type="text" name="phone" id="phone" placeholder="Mobile Number *">
        </div>
        <div class="col-lg-6">
            <input type="text" name="company" id="company" placeholder="Company">
        </div>
    </div>

    <div class="text_box row col-13">
        <select name="service" id="service" class="selectpickers col-12 col-lg-6 col-md-6 col-sm-6" style="margin: 5px;">
            <option value="">Select Service</option>
            <?php for ($i = 0; $i < count($services); $i++) { ?>
                <option value="<?php echo $i; ?>"><?php echo $services[$i]; ?></option>
            <?php } ?>
        </select>
        <select name="country" id="country" class="selectpickers col-12 col-lg-6 col-md-6 col-sm-6">
            <option value="">Select Country</option>
            <?php for ($j = 0; $j < count($countries); $j++) { ?>
                <option value="<?php echo $j; ?>"><?php echo $countries[$j]; ?></option>
            <?php } ?>
        </select>
    </div>
    <div class="text_box row col-13">
        <select name="day" id="day" class="selectpickers col-12 col-lg-6 col-md-6 col-sm-6" style="margin: 5px;">
            <option value="">Select a day</option>
            <?php for ($k = 0; $k < count($days); $k++) { ?>
                <option value="<?php echo $k; ?>"><?php echo $days[$k]; ?></option>
            <?php } ?>
        </select>
        <div class="help-block with-errors text-danger mt-2"></div>

        <select name="timing" id="timing" class="selectpickers col-12 col-lg-6 col-md-6 col-sm-6">
            <option value="">Select a time</option>
            <?php for ($h = 0; $h < count($timings); $h++) { ?>
                <option value="<?php echo $h; ?>"><?php echo $timings[$h]; ?></option>
            <?php } ?>
        </select>
    </div>

    <div class="form-group text_box">
        <textarea name="message" id="message" placeholder="Description..."></textarea>
    </div>
    <?php echo csrf_token_tag(); ?>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    <div class="g-recaptcha" data-sitekey="6Lf2c6gZAAAAABMI2STA9ciP9_kYr6dNV_uDeoD_"></div>
    <div class="d-flex justify-content-between align-items-center">
        <button type="submit" id="btn-submit" class="btn_three mt-4">Send Now</button>
    </div>
</form>

During a lengthy chat with the OP it was determined that they are using mod-rewrite to hide the .php extensions on each file.在与 OP 的长时间交谈中,确定他们正在使用 mod-rewrite 隐藏每个文件上的.php扩展名。

This is happening due to removing the PHP extensions from the URL I guess with the url rewriting in the htaccess这是由于从 URL 中删除了 PHP 扩展我猜想在 htaccess 中重写 url

Given that is the case the change in the AJAX call should be focused on the URL.鉴于这种情况,AJAX 调用中的更改应集中在 URL 上。 Change this:改变这个:

url: 'private/shared/appointment_process.php',

to this:对此:

url: 'private/shared/appointment_process',

And your AJAX should work properly.您的 AJAX 应该可以正常工作。

You need to use data: {recaptcha: grecaptcha.getResponse()} to POST it correctly.您需要使用data: {recaptcha: grecaptcha.getResponse()}正确发布它。

Here you go:这里是 go:

$(document).ready(() => {
    $("#appointment-form").on('submit', e => {
        e.preventDefault();
        console.log('Event triggered!');

        var name = $("#name").val();
        var email = $("#email").val();
        var phone = $("#phone").val();
        var company = $("#company").val();
        var service = $("#service").val();
        var country = $("#country").val();
        var day = $("#day").val();
        var timing = $("#timing").val();
        var message = $("#message").val();
        var csrfToken = $('input[name="csrf_token"]').val();

        $.ajax({
            type: 'post',
            url: 'private/shared/appointment_process.php',
            data: {"name": name, "email": email, "phone": phone, "company": company, "service": service, "country": country, "day": day, "timing": timing, "message": message, "csrfToken": csrfToken, "recaptcha": grecaptcha.getResponse()},
            success: (result) => {
                console.log('Got response back');
                console.log(result);
                if (result === "Success") {
                    $("#form-success").html('Message has been sent!');
                    $("#form-success").show();
                } else {
                    $("#form-error").html(result);
                    $("#form-error").show();
                }
            }
        });

    });
});

Isn't the data field supposed to be formatted like this with type POST..数据字段不应该像这样格式化为POST ..

I thought query strings were only used with GET...我认为查询字符串仅与 GET 一起使用...

$.ajax({
    type: 'post',
    url: 'private/shared/appointment_process.php',
    data: {
       "name" : name,
       "email" : email,
       "phone" : phone,
       "company" : company
    },
    success: (result) => {
        console.log('Got response back');
        console.log(result);
        if (result === "Success") {
            $("#form-success").html('Message has been sent!');
            $("#form-success").show();
        } else {
            $("#form-error").html(result);
            $("#form-error").show();
        }
     }
 });

You need to pass the data in a different way Like,您需要以不同的方式传递数据,例如,

$.ajax({
        url: 'URL',
        type: 'POST',
        data: { Parameter1: "Value", Parameter2: "Value"} ,
        success: function (response) {
            alert(response.status);
        },
        error: function () {
            alert("error");
        }
    }); 

In Your PHP if you try the code如果您尝试代码,请在您的 PHP 中

<?php
echo $_POST['Parameter1'];
?>

Will return the Value of the Parameter1 Send form the ajax request将返回 Parameter1 的值 从 ajax 请求中发送

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

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