I’m having a problem trying to implement an AJAX request into a pre-existing website that I didn’t create.
I have no problems sending the data to PHP as a GET request, however POST requests and trying to access $_FILES is returning null.
Here is the AJAX:
var someData = 'test';
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
data: ({someData}),
success: function(data) {
console.log(data);
}
});
PHP:
<?php echo json_encode($_POST['someData']); ?>
I believe the cause of the issue might lie within the htaccess file or be related to some other redirect that is in place on the site. This website was built by a past staff member at the company, and I’ve had this same problem using AJAX POST with several other sites built by them.
As changing from POST to GET works fine I don’t think there is any problem with my very simple code.
Is there some way I can test if the data is going missing due to a redirect, or could there be some other cause?
2
Answers
I have managed to figure this out, there is a 302 redirect in place for all .php extetensions to a url without the extension. There was also an error in my code.
Changing the URL in the AJAX to "post-data" without the .php extension allows me to see $_POST in PHP.
My other problem with not being able to access files came down to the way I was trying to send FormData with AJAX.
My original code to do this was:
The problem being that you can't send FormData and other variables at the same time. Instead I have to append my other data to the FormData:
First check the browser dev tools ctr+shift+J and see if there is a redirect. If not then
You need to set your datatype to json and depending on what version of JQUERY you are using you might have to use “type” instead of “method” if your JQUERY version < 1.9.0
PHP code:
If that doesnt work then make sure your URL is absolutely correct. No extra slashes or spaces.