Ajax调用php脚本返回404错误

时间:2022-06-30 04:20:26

I'm a WordPress designer, I developed a contact form for one of my themes that's validated via jQuery.

我是一名WordPress设计师,我为我的一个主题开发了一个联系表单,通过jQuery验证。

Please check the code below, then read the notes beneath.

请检查下面的代码,然后阅读下面的注释。

$('.submitemail') .click(function() {

    //VALIDATION CODE GOES HERE

    if ( /*VALIDATED SUCCESSFULLY*/ ) {


        $.ajax({
            type: 'POST',
            url: templatePath+'/lib/scripts/sendEmail.php',
            data: 'visitorname=' + visitorname + '&visitoremail=' + visitoremail + '&visitormessage=' + visitormessage,

            success: function(contactResults) {
                //SUCCESS CODE
            }

        });
    }
});

Notes:

笔记:

  • sendEmail.php is a correct script that sends email using PHPmailer class.
  • sendEmail.php是一个使用PHPmailer类发送电子邮件的正确脚本。
  • templatePath variable has the value of the full template path which looks like this: http://somedomain.com/wp-content/themes/themename
  • templatePath变量具有完整模板路径的值,如下所示:http://somedomain.com/wp-content/themes/themename
  • The jQuery code above is located in lib/scripts/jfunctions.js (same directory of the php script)
  • 上面的jQuery代码位于lib / scripts / jfunctions.js(php脚本的相同目录)
  • The whole process (ajax and php) works perfectly as expected in many servers, (tested in two servers by me and other servers by my theme users).
  • 整个过程(ajax和php)在许多服务器中完美地工作,(由我和其他服务器在我的主题用户的两台服务器中测试)。

The Problem:

问题:

In SOME servers, the success handler is not triggered while the ajax call to sendEmail.php is actually passed successfully and the php script is processed and email is sent.

在某些服务器中,当成功传递对sendEmail.php的ajax调用并处理php脚本并发送电子邮件时,不会触发成功处理程序。

When I check with firebug to see why the success handler is not triggered, firebug shows "not found 404 error", It's like a false alarm.

当我用firebug检查为什么没有触发成功处理程序时,firebug显示“找不到404错误”,这就像是一个误报。

Possible causes:

可能的原因:

I think some servers is configured to block such ajax calls.

我认为有些服务器被配置为阻止这样的ajax调用。

What might be the cause for this weird issue? How to fix it?

这个奇怪的问题可能是什么原因?怎么解决?

Thanks in advance.

提前致谢。

@nowk: sendEmail.php code is:

@nowk:sendEmail.php代码是:

<?php 
// Code for loading WordPress environment goes here //

$themeName_optionTree = get_option('option_tree');

$name = trim($_POST['visitorname']);
$email = $_POST['visitoremail'];
$message = $_POST['visitormessage'];


$site_owners_email = $themeName_optionTree['owner_email'];
$site_owners_name = $themeName_optionTree['owner_name'];
$email_subject = $themeName_optionTree['email_subject'];
$success_message = '<p class="success-box">' . $themeName_optionTree['success_message'] . '</p>';

if (strlen($name) < 2) {
    $error['name'] = 1; 
}

if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
    $error['email'] = 1;    
}

if (strlen($message) < 2) {
    $error['message'] = 1;
}

if (!$error) {

    require_once('PHPMailer_v5.1/class.phpmailer.php');

    $mail = new PHPMailer(true);

    try {
        $mail->From = $email;
        $mail->FromName = $name;
        $mail->Subject = $email_subject;
        $mail->AddAddress($site_owners_email, $site_owners_name);
        $mail->Body = $message;
        $mail->Send();
        echo $success_message;
    } catch (phpmailerException $e) {
        echo '<p class="warning-box">' . $e->errorMessage() . '</p>';
    } catch (Exception $e) {
        echo '<p class="warning-box">' . $e->getMessage() . '</p>';
    }
}
?>

Please note that the above code executes perfectly even when ajax returns 404, weird huh!.

请注意,即使ajax返回404,上面的代码也能完美执行,很奇怪吧!

4 个解决方案

#1


26  

Since the server sends a 404 (for god knows what reason), there are two ways to fix/circumvent this:

由于服务器发送404(上帝知道是什么原因),有两种方法可以解决/规避这个问题:

  1. Ignore the HTTP response code and change success to complete in the jQuery ajax call, so that the handler is executed when the request is done no matter the server response. You know the server response (it always works). The HTML should still be available in the jQuery complete handler.
  2. 忽略HTTP响应代码并在jQuery ajax调用中更改成功以完成,以便在请求完成时执行处理程序,无论服务器响应如何。您知道服务器响应(它始终有效)。 HTML应该仍然可以在jQuery完整处理程序中使用。
  3. Overwrite the 404 that something sends on the server (probably something Wordpress) by executing (before printing any output): header('HTTP/1.1 200 OK'). Since the script is executed, this will overwrite the crazy 404 and jQuery will receive that 200 and execute the success handler.
  4. 通过执行(在打印任何输出之前)覆盖事物在服务器上发送的404(可能是Wordpress):header('HTTP / 1.1 200 OK')。由于脚本被执行,这将覆盖疯狂的404,jQuery将接收200并执行成功处理程序。

You could try both =) I'm pretty sure the first one will work (but that's not so clean). I'm also pretty sure the 2nd will work, but I don't know Wordpress well enough to make promises =)

你可以试试两个=)我很确定第一个会起作用(但那不是那么干净)。我也很确定第二个会工作,但我不知道Wordpress是否足以做出承诺=)

#2


2  

I'm guessing it's because Wordpress already has an AJAX mechanism built in and it stops you from implementing it on your own. This page explains how to add AJAX to plugins:

我猜这是因为Wordpress已经内置了一个AJAX机制,它阻止你自己实现它。本页介绍如何向插件添加AJAX:

http://codex.wordpress.org/AJAX_in_Plugins

http://codex.wordpress.org/AJAX_in_Plugins

Here's a snippet from the page:

这是页面的一个片段:


Ajax on the Administration Side

Since Ajax is already built into the core WordPress administration screens, adding more administration-side Ajax functionality to your plugin is fairly straightforward, and this section describes how to do it.

由于Ajax已内置于核心WordPress管理屏幕中,因此向插件添加更多管理端Ajax功能非常简单,本节将介绍如何执行此操作。

Here's a short example. All this will be in one file.

这是一个简短的例子。所有这些都将在一个文件中。

First, add some javascript that will trigger the AJAX request:

首先,添加一些将触发AJAX请求的javascript:

<?php
add_action('admin_print_scripts', 'my_action_javascript');

function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    var data = {
        action: 'my_action',
        whatever: 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    $.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});
</script>
<?php
}

Then, set up a PHP function that will handle that request:

然后,设置一个将处理该请求的PHP函数:

<?php 

    add_action('wp_ajax_my_action', 'my_action_callback');

    function my_action_callback() {
    global $wpdb; // this is how you get access to the database

    $whatever = intval( $_POST['whatever'] );

    $whatever += 10;

    echo $whatever;

    die(); // this is required to return a proper result
}

That's it! You will need to add a few details, such as error checking and verifying that the request came from the right place ( using check_ajax_referer() ), but hopefully the example above will be enough to get you started on your own administration-side Ajax plugin. NOTE: Since Version 2.8, The javascript global variable ajaxurl can be used in case you want to separate your javascript code from php files into javascript only files. This is true on the administration side only.

而已!您需要添加一些细节,例如错误检查和验证请求来自正确的位置(使用check_ajax_referer()),但希望上面的示例足以让您开始使用自己的管理端Ajax插件。注意:从版本2.8开始,可以使用javascript全局变量ajaxurl,以防您想将javascript代码与php文件分离为仅javascript文件。仅在管理方面这是事实。

#3


1  

As seen here https://cooltrainer.org/fixing-false-404-headers-on-external-pages-including-wp-blog-header-php/ this solution tested and works well:

如此处所示https://cooltrainer.org/fixing-false-404-headers-on-external-pages-including-wp-blog-header-php/此解决方案经过测试并运行良好:

require_once("path/to/wp-config.php");
$wp->init();
$wp->parse_request(); 
$wp->query_posts();
$wp->register_globals(); 
$wp->send_headers();

#4


0  

Without digging into the problem, you might check that the ajax request is actually going where you think it is going. There could be several things going on here, such as the server is set up to redirect any requests to /wp-content/ somewhere else.

在不深入研究问题的情况下,您可能会检查ajax请求是否真正按照您认为的方式进行。这里可能会发生一些事情,例如服务器设置为将任何请求重定向到/ wp-content /其他地方。

Capture some header information using firebug, and perhaps livehttp headers.

使用firebug捕获一些头信息,也许还有livehttp头。

#1


26  

Since the server sends a 404 (for god knows what reason), there are two ways to fix/circumvent this:

由于服务器发送404(上帝知道是什么原因),有两种方法可以解决/规避这个问题:

  1. Ignore the HTTP response code and change success to complete in the jQuery ajax call, so that the handler is executed when the request is done no matter the server response. You know the server response (it always works). The HTML should still be available in the jQuery complete handler.
  2. 忽略HTTP响应代码并在jQuery ajax调用中更改成功以完成,以便在请求完成时执行处理程序,无论服务器响应如何。您知道服务器响应(它始终有效)。 HTML应该仍然可以在jQuery完整处理程序中使用。
  3. Overwrite the 404 that something sends on the server (probably something Wordpress) by executing (before printing any output): header('HTTP/1.1 200 OK'). Since the script is executed, this will overwrite the crazy 404 and jQuery will receive that 200 and execute the success handler.
  4. 通过执行(在打印任何输出之前)覆盖事物在服务器上发送的404(可能是Wordpress):header('HTTP / 1.1 200 OK')。由于脚本被执行,这将覆盖疯狂的404,jQuery将接收200并执行成功处理程序。

You could try both =) I'm pretty sure the first one will work (but that's not so clean). I'm also pretty sure the 2nd will work, but I don't know Wordpress well enough to make promises =)

你可以试试两个=)我很确定第一个会起作用(但那不是那么干净)。我也很确定第二个会工作,但我不知道Wordpress是否足以做出承诺=)

#2


2  

I'm guessing it's because Wordpress already has an AJAX mechanism built in and it stops you from implementing it on your own. This page explains how to add AJAX to plugins:

我猜这是因为Wordpress已经内置了一个AJAX机制,它阻止你自己实现它。本页介绍如何向插件添加AJAX:

http://codex.wordpress.org/AJAX_in_Plugins

http://codex.wordpress.org/AJAX_in_Plugins

Here's a snippet from the page:

这是页面的一个片段:


Ajax on the Administration Side

Since Ajax is already built into the core WordPress administration screens, adding more administration-side Ajax functionality to your plugin is fairly straightforward, and this section describes how to do it.

由于Ajax已内置于核心WordPress管理屏幕中,因此向插件添加更多管理端Ajax功能非常简单,本节将介绍如何执行此操作。

Here's a short example. All this will be in one file.

这是一个简短的例子。所有这些都将在一个文件中。

First, add some javascript that will trigger the AJAX request:

首先,添加一些将触发AJAX请求的javascript:

<?php
add_action('admin_print_scripts', 'my_action_javascript');

function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    var data = {
        action: 'my_action',
        whatever: 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    $.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});
</script>
<?php
}

Then, set up a PHP function that will handle that request:

然后,设置一个将处理该请求的PHP函数:

<?php 

    add_action('wp_ajax_my_action', 'my_action_callback');

    function my_action_callback() {
    global $wpdb; // this is how you get access to the database

    $whatever = intval( $_POST['whatever'] );

    $whatever += 10;

    echo $whatever;

    die(); // this is required to return a proper result
}

That's it! You will need to add a few details, such as error checking and verifying that the request came from the right place ( using check_ajax_referer() ), but hopefully the example above will be enough to get you started on your own administration-side Ajax plugin. NOTE: Since Version 2.8, The javascript global variable ajaxurl can be used in case you want to separate your javascript code from php files into javascript only files. This is true on the administration side only.

而已!您需要添加一些细节,例如错误检查和验证请求来自正确的位置(使用check_ajax_referer()),但希望上面的示例足以让您开始使用自己的管理端Ajax插件。注意:从版本2.8开始,可以使用javascript全局变量ajaxurl,以防您想将javascript代码与php文件分离为仅javascript文件。仅在管理方面这是事实。

#3


1  

As seen here https://cooltrainer.org/fixing-false-404-headers-on-external-pages-including-wp-blog-header-php/ this solution tested and works well:

如此处所示https://cooltrainer.org/fixing-false-404-headers-on-external-pages-including-wp-blog-header-php/此解决方案经过测试并运行良好:

require_once("path/to/wp-config.php");
$wp->init();
$wp->parse_request(); 
$wp->query_posts();
$wp->register_globals(); 
$wp->send_headers();

#4


0  

Without digging into the problem, you might check that the ajax request is actually going where you think it is going. There could be several things going on here, such as the server is set up to redirect any requests to /wp-content/ somewhere else.

在不深入研究问题的情况下,您可能会检查ajax请求是否真正按照您认为的方式进行。这里可能会发生一些事情,例如服务器设置为将任何请求重定向到/ wp-content /其他地方。

Capture some header information using firebug, and perhaps livehttp headers.

使用firebug捕获一些头信息,也许还有livehttp头。