-1

I am creating a booking system for a university project and I am trying to add an author to the table 'authors' for some reason when I add a field it returns as NULL in my database and undefined on my html page? Can anyone help me with this I have shown my HTML, Javascript and php code below. Can anyone help me with this and guide me in the right direction. I have a feeling it is something to do with my names eg. authors or author Thanks in advance.

HTML

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="w3.js"></script>
    <script src="https://scm.ulster.ac.uk/zhiwei.lin/js/jquery.tmpl.min.js"></script>
</head>
<body>

    <div id="authors">
        <ul id="authors_list"></ul>
    </div>

    <div class="mainArea">
        <label>Author:</label>
        <input type="text" id="author" name="name" required>


        <button id="btnSave">Save</button>
        <button id="btnUpdate">Update</button>
    </div>

    <p>Click Here to Delete Last Author
        <button id="btnDelete">Delete</button></p>
</body>
</html>

Js

$(document).ready(function(){

   $.ajax({
        type: 'GET',
        dataType: "json",
        url: "api.php/authors",
        success: showAllAuthors,
        error: showError
    }); 

});

function showAllAuthors(responseData) {
    $.each(responseData.authors,function(index,authors){
        $("#authors_list").append("<li type='square'> author:"+authors.author+"");
        $("#authors_list").append("</li>");
    });
}
function showError(){
    alert("Sorry, there was a problem!");
}

$(document).ready(function(){
    $("#btnSave").click(function(){


            $.ajax({
            type: 'POST',
            dataType: "json",
            url: "api.php/authors",
            data:{author: $("#author").val()},                
            data:JSON.stringify(authors),
            success: showResponse,
            error: showError
        });
    });
});

function authors(Author){
    this.author=Author;

}

function showResponse(responseData) {
    console.log(responseData);
}

function showError() {
    alert("Sorry, there was a problem!");
}

$(document).ready(function(){

   $.ajax({
        type: 'GET',
        dataType: "json",
        url: "api.php/authors/12",
        success: showResponse,
        error: showError
    }); 

});

$(document).ready(function(){
    $("#btnUpdate").click(function(){

        $.ajax({
            type: 'PUT',
            dataType: "json",
            url: "api.php/authors/12",
            data:{author: $("#author").val()},                
            data:JSON.stringify(authors),
            success: alert("Updated!")
        });
    });
});

$(document).ready(function(){
    $("#btnDelete").click(function(){
        $.ajax({
            type: 'DELETE',
            dataType: "json",
            url: "api.php/authors/13",
            data:{author: $("#author").val()},                
            data:JSON.stringify(authors),
            success: alert("Deleted!")
        });
    });
});

PHP

<?php

require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
use Slim\Slim;
$app=new Slim();
$app->get('/authors','getAuthors');
$app->post('/authors','addAuthor');
$app->get('/authors/:id','getAuthor');
$app->put('/authors/:id','updateAuthor');
$app->delete('/authors/:id', 'deleteAuthor');
$app->run();

function deleteAuthor($id) {
    $sql = "DELETE FROM authors WHERE id=:id";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $db = null;
        responseJson("Deleted",200);

    }catch(PDOException $e) {
        responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
    }
}

function updateAuthor($id) {
    $request = Slim::getInstance()->request();
    $body = $request->getBody();
    $authors = json_decode($body);
    $sql = "UPDATE authors SET author=:author WHERE id=:id";
    try { 
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("author", $authors->author);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $db = null;
        responseJson("Updated",200);
    } catch(PDOException $e) { 
        responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
    }
}

function getAuthor($id) {
    $sql = "SELECT * FROM authors WHERE id=:id";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $authors = $stmt->fetchObject();
        $db = null;
        responseJson(json_encode($authors),200);
    } catch(PDOException $e) {
            responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
    }
}

function getAuthors(){

    $sql = "select * FROM authors ORDER BY id";

    try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $authors = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        responseJson('{"authors":'.json_encode($authors).'}',200);
    }catch(PDOException $e){
        responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
    }            
}

function addAuthor(){

    $request = Slim::getInstance()->request();
    $authors=json_decode($request->getBody());
    $sql= "INSERT INTO authors (author) 
    VALUES (:author)";

    try {

        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("author", $authors->author);
        $stmt->execute();
        $authors->id=$db->lastInsertId();
        $db = null;
        responseJson(json_encode($authors),201);
    }catch(PDOException $e) {

        responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
    }
}


function getConnection(){
    $dbhost="localhost";
    $dbuser="B00657229";
    $dbpass="9wz7Fr9J";
    $dbname="B00657229";
    $dbh= new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser,$dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    return $dbh;    
}

function responseJson($responseBody,$statusCode){
    $app = Slim::getInstance();
    $response = $app->response();
    $response['Content-Type']='application/json';
    $response->status($statusCode);
    $response->body($responseBody);

}


?>
sorak
  • 2,607
  • 2
  • 16
  • 24
Niamh Flannery
  • 81
  • 1
  • 2
  • 8

1 Answers1

-1

There seems to be a mistake in your js code:

$(document).ready(function(){
    $("#btnSave").click(function(){


        $.ajax({
        type: 'POST',
        dataType: "json",
        url: "api.php/authors",
        data:{author: $("#author").val()},              
        data:JSON.stringify(authors),
        success: showResponse,
        error: showError
    });
});

you set data two times, one time with {author: $("#author").val()} and other time with JSON.stringify(authors) i don't think you need the second one, but I did not test this.

darkė
  • 47
  • 6