Javad Javad - 1 month ago 17
jQuery Question

why my jQuery ajax POST does not work by GET works fine?

I have written a jquery ajax with

POST
but it didn't work. After hours of searching I found out that by changing to
GET
maybe the problem would solve. Fortunately it worked, but there still remains the question why
POST
does not work. Here is my code:

<html>
<head>
<title>Hello this is my title</title>
<script type = "text/javascript"
src = "jquery.js"></script>

<script>
$(document).ready(function() {
$("#driver").click(function(event){
debugger;
$.ajax({
type: "POST",
url: "login.php",
data: { name:"Zara" },
dataType: "text",
success: function(data) {
$('#stage').html(data);},
error: function(j,t,e) {
$('#stage').text('An error occurred= ' + j + " *** " + t + " *** " + e);
}
});
});
});
</script>
</head>

<body>

<p>Click on the button to load login.php file −</p>

<div id = "stage" style = "background-color:wheat;">
STAGE
</div>

<input type = "button" id = "driver" value = "Load Data" />

</body>
</html>





and this is the PHP Code:




if( empty($_REQUEST['name'] )) {
$_REQUEST['name'] = "Error";
}

$name = $_REQUEST['name'];
echo "Welcome ". $name;


After running this code it says "not found". I've searched the entire web, jquery official website and all similar questions on stackoverflow, but none of them worked for me!

=========

edit



this is the request header:




Host: localhost:63342
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0
Accept: text/plain, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:63342/untitled2/index.php?_ijt=qgukfccd8om4ruh3e8fv7v8rds
Content-Length: 9
Cookie: Phpstorm-ed364c84=959e64e3-228a-4a78-904d-cc31d3f1a3e0
Connection: keep-alive





and this is request body:

name=Zara





this is the response:

<!doctype html>
<title>404 Not Found</title>
<h1 style="text-align: center">404 Not Found</h1>
<hr/><p style="text-align: center">
PhpStorm 2016.2.1</p>

Answer

An AJAX request requires a webserver. It will not just run on your local laptop which explains why the POST did not do anything.

In order to fix this you can install a webserver with PHP on your laptop. WAMP and XAMPP are two packages which come to mind.

Comments