I'm creating a basic website with a button that, when clicked, makes a jquery Ajax call to a php script that echoes something back.
things I've tried:
I've looked at Call php function from JavaScript to make sure I wasn't just making a syntax error, but that didn't help.
I've changed the dataType
part of my jquery call to script
, html
, json
, and text
, but it just wound up returning the entire code in some cases (e.g. just alerting test.php without executing it) and throwing an error:
XML Parsing Error: no root element found
Location: file:///Users/jonathansekela/Documents/Projects/sz12-library/php/test.php
Line Number 9, Column 3
in the case of json
, the error:
error: parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
From what I can tell, whenever I try to get jQuery to execute some PHP with a simple Ajax call, it doesn't execute the PHP, instead simply treating it like pure xml and returning the entire thing as a string back to my function without doing any of the php.
The end-goal:
when pressed, the button in the html will call a js function that makes an Ajax call to a php script. The php script then connects to a mysql database, does some stuff, returns, some other stuff, and gives that other stuff back to the jQuery call so it can put some results back on the html screen. Literally basic proof-of-concept level stuff, except for the one part where my computer doesn't think that the php is actually php.
What am I missing here? Any and all suggestions welcome. I will add any extra information if requested.
index.html:
<div class = "row">
<div class="col-xs-12 btn btn-default button" onclick="test();">
test ajax
</div>
</div>
js/index.js:
var test = () => {
$("#button-text").html("test clicked");
$.ajax({
type: "POST",
data: {
user: 1,
first: "jonny",
last: "test"
},
url: "php/test.php",
dataType: "html",
success: function(result) {
alert("success: "+result);
},
error: function(xhr, status, error) {
alert("error: "+status + ': ' + error);
}
});
}
php/test.php:
<?php
function test() {
$user = $_POST['user'];
$first = $_POST['first'];
$last = $_POST['last'];
echo "your data: ".$user." + ".$first." + ".$last;
}
test();
?>