Why JQuery Ajax is sending GET instead of POST

2104 Views

Why JQuery Ajax is sending GET instead of POST

JQuery Ajax is sending GET instead of POST

 Its a very common problem which is faced by most of the new programer. In Ajax code new learner use (type: "POST") yet the sending request gone through GET instead of POST. 

Let's see how the problem can be short out.   

 <?php
	$conn = mysqli_connect("localhost","root","","test");
	if (!$conn) {
		die("Connection failed: " . mysqli_connect_error());
	}
	
	if(isset($_POST['add'])){
		$firstname=$_POST['firstname'];
		$lastname=$_POST['lastname'];
		
		mysqli_query($conn,"insert into `user` (firstname, lastname) values ('$firstname', '$lastname')");
	}
?>
<!DOCTYPE html>
<html lang = "en">
	<head>
		<title>JQuery Ajax is sending GET instead of POST</title>
	</head>
<body>
<br>
<form>
    
	<label>Firstname:</label>
	<input type  = "text" id = "firstname">

	<label>Lastname:</label>
	<input type  = "text" id = "lastname">

	<button type = "submit" id="addnew">Add</button>
    
</form>
<script src = "js/jquery-3.1.1.js"></script>	
<script type = "text/javascript">
	$(document).ready(function(){
		$(document).on('click', '#addnew', function(){
		$firstname=$('#firstname').val();
		$lastname=$('#lastname').val();				
			$.ajax({
				type: "POST",
				url: "test.php",
				data: {
					firstname: $firstname,
					lastname: $lastname,
					add: 1,
				},
				success: function(){
					showUser();
				}
			});
		});
	});
	
</script>
</body>
</html>

Above code produce General header status with GET request instead we use (type: "POST") in our ajax code.

Request URL: http://localhost/demo/test.php?
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade

This is not heappen becouse of Ajax code. Our Ajax code is right but the problem in our HTML code. In the above code we use a form with a button which is use to send the form data. If we see the attribute of our button then we find it uses two attribute (i.e.: type="submit" id="addnew").

 <button type = "submit" id="addnew">Add</button>

Button type = "submit" have properties to send any form data instentely to the HTTP Header. Bydefault it send data by GET request if you not deffine any method type in form attribute.

So for resolving the problem we just have to change button type = "button" instead of type = "submit".

 <button type = "button" id="addnew">Add</button>

If we chenge button type = "button" then we see the code produce General header status with POST request.

Request URL: http://localhost/demo/test.php
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade

By this way we can fixed the problem of "JQuery Ajax is sending GET instead of POST".