简体   繁体   中英

jQuery AJAX return 404 error

I try to use AJAX to send form data to server, but it returns me 404 all the time. Here is my code:

$(function() {
    var dataString ='Name: '+conditionName+"&Desc: "+conditionDescription+'&Condition: '+condition;
    //alert (dataString);return false;
    $.ajax({
        type: "POST",
        url: "saveCondition.php",
        data: dataString,
        success: function(response) {
                 alert ('Data saved: '+dataString);
        },
        error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
        }
    });
    return false;
});

"saveCondition.php" is in same folder as .js file I use WAMP server on local machine.

UPDATE:

when I changed path to "saveCondition.php" relative to the HTML page, I got error 500

The JavaScript file is being called from an HTML page. Thus, the URL parameter must be relative to the HTML page .

Try editing your URL parameter to the following: "MyJavaScriptFolderNameHere/saveCondition.php"

The path of the URL requested by the AJAX is relative to the root of the page you're currently on, ie if your page is in the root directory (let's call it index.html) along with your AJAX script (data.php), and your jQuery script is in the js directory, you would use 'data.php' as the URL. If your data.php script is in the js directory, your URL would need to be 'js/data.php'.

Be careful using relative paths. It's always best to use absolute paths, in case your script is used from a different directory, other than the path it was originally developed within.

You mention a 500 response code. This indicates that the PHP script you're requesting is in fact erroring out.

In order to find out the cause of the error, either check your error logs or place the below code into the PHP script. The error will then be output in the HTTP response body.

ini_set('display_errors', 'on');
error_reporting(E_ALL);

Make sure the location of saveCondition.php is correctly mentioned.

It seems your html page path is something like " http://example.com/folder1/page1 " and your saveCondition.php is located at http://example.com/saveCondition.php

In this case, ajax code is interpreting the url as http://example.com/folder1/saveCondition.php which is incorrect.

Try: '/saveCondition.php'

if you are getting a 404 it because js isn't pointing to the PHP script correctly. To call saveconditions like you're doing it should be in the same folder as the script in which you are adding the js, not the js itself. I think it's better if you change the URL to be completely relative to the site URL, for example if your PHP script is in public_html/ajax/saveconditions.php, set the Ajax URL to /ajax/saveconditions.php.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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