I am learning AJAX and I am trying to log all the data parameters in the console in case of success and in case of a failure to throw an alert. My code works and I can successfully dump the data I send, but nothing shows up in the console, even though I explicitly put console.log within the Javascript to register that.
this is my code.
Html page
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>Send JSON</h2>
<form action="postrequest.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="text" name="param1"/>
<input type="text" name="param2"/>
<input type="text" name="param3"/>
<button type="submit">Submit</button>
</form>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var param1 = $("#param1").val();
var param2 = $("#param2").val();
var param3 = $("#param3").val();
$.ajax({
url : 'postrequest.php',
contentType: "application/json",
dataType: "json",
type : 'POST',
data: JSON.stringify({
param1: param1,
param2: param2,
param3: param3
}),
success: function(data) {
console.log(data);
},
error: function (data) {
alert(data.param3);
}
});
});
});
</script>
</html>
postrequest.php
<?php
var_dump( $_POST);
What am I doing wrong?
2
Answers
I think the root cause is that the page is reloading once you hit submit. Hence you cannot see anything in the console. Try the following steps.
Error 1: Remove the form tag. It will work because it contains action=”postrequest.php”. You are doing 2 things at the same time.
Error 2: You are writing
var param1 = $("#param1").val();
Where is the param1, param2,param3 you defined?Error 3: You are giving the jquery link, you don’t have closed the script tag.
Error 4: You are sending the
data
in ajax and outputting the ajax response again with the same variableError 5: Ajax error block you have created is wrong.
postrequest.php page