Below is jQuery code to pass form data to a php file. I'm using a very simple file just to test this. The jQuery code returns success and failure messages, but the failure message is the one that fires. It looks like the problem is in the php file, or in the data encoding.
This is the php file echo_test.php:
<?php
$str = "Hello world!";
echo $str;
?>
This is the jQuery code that sends html form data to the php file:
<form>
<!-- form fields omitted for brevity -->
<div class="btn_div">
<button href="google.com" class="btn_joinnow" id="btn_submit" style="color:rgb(255,255,255)">Click to submit data</button>
</div>
</form>
$("#btn_submit").on("click", function(event) {
event.preventDefault();
var datastring = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
});
console.log("Okay, I'm starting");
return $.ajax({
type: "POST",
url: "echo_test.php",
data: { post: datastring },
success: function (response) {
console.log(response);
},
error: function (error) {
console.log("Okay, I failed" + error);
}
});
});
(The data [ title: 'foo', body: 'bar', userId: 1 ] are just placeholders.)
The dev console reports: Okay, I failed[object Object] so it didn't work.
The dev console also says:
XML Parsing Error: no root element found Location: (file location) Line Number 4, Column 1:
Is the problem with jQuery or PHP?
Thanks for any ideas.
<?), hence the error. If you're running windows, research how to setup an XAMPP server locally