I am using a form to collect values to add a new player to my created database. To do this I am required to have an HTML page (this is where the form is held) a Javascript file with an ajax call to post and a php file to connect to the database.
However when I fill in the form and click submit, instead of showing me the newly added player it will just show me my Javscript code on the browser. I am not too sure where the error is, as I have kept everything lower space both in the form and database.
Here is my form code linking to the JS file:
<h2>Add a Player:</h2>
<form action="api2.js" method="post">
<input type="text" name="firstname" placeholder="First Name" /><br>
<input type="text" name="lastname" placeholder="Last Name" /><br>
<input type="text" name="team" placeholder="Team" /><br>
<input type="submit" value="submit" />
</form>
and here is my JS file:
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'api.php/players',
data:JSON.stringify(nhl),
success: showResponse,
error: showError
});
function showResponse(responseData) {
console.log(responseData);
}
function showError() {
alert("Sorry, there was a problem to add new staff!" );
}
});
function Player(firstname, lastname, team){
this.firstname = firstname;
this.lastname = lastname;
this.team = team
}
$('form').on('#submit', function(event){
event.preventDefault();
var player = new Player(firstname, lastname, team);
var firstname = $('.firstname').val();
var lastname = $('.lastname').val();
var team = $('.team').val();
});
and lastly my php file:
//Add Player
function addPlayer() {
$request = Slim::getInstance()->request();
$nhl = json_decode($request->getBody());
$sql = "insert into nhl (lastname, firstname, team) values (:lastname, :firstname, :team)";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("lastname", $nhl->lastname);
$stmt->bindParam("firstname", $nhl->firstname);
$stmt->bindParam("team", $nhl->team);
$stmt->execute();
$nhl->Player_Id = $db->lastInsertId();
$db = null;
responseJson(json_encode($nhl),201);
} catch(PDOException $e) {
responseJson( '{"error":{"text":'. $e->getMessage() .'}}',500);
}
}
I have tried changing the form action to the php file but it will either show a 404 error or if I link it straight to the api.php/players it will show me this error:
{"error":{"text":SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'lastname' cannot be null}}`
Any help or guidance would be greatly appreciated.
$nhl?