Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to post using AngularJS & PHP

I'm running an AngularJS app.

I've ran in locally before and I could post to the local server.

Now I'm trying it on the live server and I get the following error:

Unable to create Reservation.

This error is posted from the create.php page, whenever it's unable to post to the server.

Anyone know what's wrong with my code?

create.php page

  <?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection
include_once '../config/database.php';

// instantiate reservation object
include_once '../objects/reserve.php';

$database = new Database();
$db = $database->getConnection();

$reservation = new Reservation($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

// set product property values
$reservation->name = $data->name;
$reservation->eMail = $data->eMail;
$reservation->phoneNumber = $data->phoneNumber;
$reservation->colorScooter = $data->colorScooter;
$reservation->amountScooters = $data->amountScooters;
$reservation->inputDate = $data->inputDate;
$reservation->returnDate = $data->returnDate;
$reservation->category_id = $data->category_id;
$reservation->created = date('Y-m-d H:i:s');

// create the reservation
if($reservation->create()){
    echo '{';
        echo '"message": "Reservation was created."';
    echo '}';
}

// if unable to create the reservation, tell the user
else{
    echo '{';
        echo '"message": "Unable to create Reservation."';
    echo '}';
}
?>

EDIT 02-08-18

It seems it's not setting the property values.

    // set product property values
$reservation->name = $data->name;
$reservation->eMail = $data->eMail;
$reservation->phoneNumber = $data->phoneNumber;
$reservation->colorScooter = $data->colorScooter;
$reservation->amountScooters = $data->amountScooters;
$reservation->inputDate = $data->inputDate;
$reservation->returnDate = $data->returnDate;
$reservation->category_id = $data->category_id;
$reservation->created = date('Y-m-d H:i:s');

I can see this when running the opening the create.php live vs locally

locally

<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>24</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>27</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>28</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>29</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>30</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>31</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>32</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>33</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>34</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api2\reserve\update.php</b> on line <b>35</b><br />
{"message": "Unable to update reservation."}

Live

 {"message": "Unable to update reservation."}

It seems on live it's not looking for the property values

Running on HP 7.0 (7.0.28)

added:

ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);

and now got the following displayed

Trying to get property of non-object in /var/www/vhosts/128/313118/webspace/httpdocs/e-citywheels.com/new/api2/reserve/create.php on line 32

EDIT ADDED RESERVE.PHP

<?php
class Reservation{

    // database connection and table name
    private $conn;
    private $table_name = "reservations";

    // object properties
    public $id;
    public $name;
    public $eMail;
    public $phoneNumber;
    public $colorScooter;
    public $amountScooters;
    public $inputDate;
    public $returnDate;
    public $category_name;
    public $created;

    // constructor with $db as database connection
    public function __construct($db){
        $this->conn = $db;
    }

    // read reservations
    function read(){

        // select all query
        $query = "SELECT
                    c.name as category_name, p.id, p.name, p.eMail, p.phoneNumber,  p.colorScooter, p.amountScooters, p.inputDate, p.returnDate, p.category_id, p.created
                FROM
                    " . $this->table_name . " p
                    LEFT JOIN
                        categories c
                            ON p.category_id = c.id
                ORDER BY
                    p.created DESC";

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // execute query
        $stmt->execute();

        return $stmt;
    }
    // create product
    function create(){

        // query to insert record
        $query = "INSERT INTO
                    " . $this->table_name . "
                SET
                    name=:name, eMail=:eMail, phoneNumber=:phoneNumber, colorScooter=:colorScooter, amountScooters=:amountScooters, inputDate=:inputDate, returnDate=:returnDate,category_id=:category_id, created=:created";

        // prepare query
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->name=htmlspecialchars(strip_tags($this->name));
        $this->eMail=htmlspecialchars(strip_tags($this->eMail));
        $this->phoneNumber=htmlspecialchars(strip_tags($this->phoneNumber));
        $this->colorScooter=htmlspecialchars(strip_tags($this->colorScooter));
        $this->amountScooters=htmlspecialchars(strip_tags($this->amountScooters));
        $this->inputDate=htmlspecialchars(strip_tags($this->inputDate));
        $this->inputDate=htmlspecialchars(strip_tags($this->returnDate));
        $this->category_id=htmlspecialchars(strip_tags($this->category_id));
        $this->created=htmlspecialchars(strip_tags($this->created));

        // bind values
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":eMail", $this->eMail);
        $stmt->bindParam(":phoneNumber", $this->phoneNumber);
        $stmt->bindParam(":colorScooter", $this->colorScooter);
        $stmt->bindParam(":amountScooters", $this->amountScooters);
        $stmt->bindParam(":inputDate", $this->inputDate);
        $stmt->bindParam(":returnDate", $this->returnDate);
        $stmt->bindParam(":category_id", $this->category_id);
        $stmt->bindParam(":created", $this->created);

        // execute query
        if($stmt->execute()){
            return true;
        }

        return false;

    }
    // used when filling up the update product form
    function readOne(){

        // query to read single record
        $query = "SELECT
                    c.name as category_name,  p.id, p.name, p.eMail, p.phoneNumber,  p.colorScooter, p.amountScooters, p.inputDate, p.returnDate, p.category_id, p.created
                FROM
                    " . $this->table_name . " p
                    LEFT JOIN
                        categories c
                            ON p.category_id = c.id
                WHERE
                    p.id = ?
                LIMIT
                    0,1";

        // prepare query statement
        $stmt = $this->conn->prepare( $query );

        // bind id of product to be updated
        $stmt->bindParam(1, $this->id);

        // execute query
        $stmt->execute();

        // get retrieved row
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        // set values to object properties
        $this->name = $row['name'];
        $this->eMail = $row['eMail'];
        $this->phoneNumber = $row['phoneNumber'];
        $this->colorScooter = $row['colorScooter'];
        $this->amountScooters = $row['amountScooters'];
        $this->inputDate = $row['inputDate'];
        $this->returnDate = $row['returnDate'];
        $this->category_id = $row['category_id'];
        $this->category_name = $row['category_name'];
    }

    // update the product
    function update(){

        // update query
        $query = "UPDATE
                    " . $this->table_name . "
                SET
                    name = :name,
                    eMail = :eMail,
                    phoneNumber = :phoneNumber,
                    colorScooter = :colorScooter
                    amountScooters = :amountScooters,
                    inputDate = :inputDate,
                    returnDate = :returnDate,
                    category_id = :category_id
                WHERE
                    id = :id";

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->name=htmlspecialchars(strip_tags($this->name));
        $this->eMail=htmlspecialchars(strip_tags($this->eMail));
        $this->phoneNumber=htmlspecialchars(strip_tags($this->phoneNumber));
        $this->colorScooter=htmlspecialchars(strip_tags($this->colorScooter));
        $this->amountScooters=htmlspecialchars(strip_tags($this->amountScooters));
        $this->inputDate=htmlspecialchars(strip_tags($this->inputDate));
        $this->inputDate=htmlspecialchars(strip_tags($this->returnDate));
        $this->category_id=htmlspecialchars(strip_tags($this->category_id));
        $this->id=htmlspecialchars(strip_tags($this->id));





        // bind new values
        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":eMail", $this->eMail);
        $stmt->bindParam(":phoneNumber", $this->phoneNumber);
        $stmt->bindParam(":colorScooter", $this->colorScooter);
        $stmt->bindParam(":amountScooters", $this->amountScooters);
        $stmt->bindParam(":inputDate", $this->inputDate);
        $stmt->bindParam(":returnDate", $this->returnDate);
        $stmt->bindParam(':category_id', $this->category_id);
        $stmt->bindParam(':id', $this->id);

        // execute the query
        if($stmt->execute()){
            return true;
        }

        return false;
    }

    // delete the product
    function delete(){

        // delete query
        $query = "DELETE FROM " . $this->table_name . " WHERE id = ?";

        // prepare query
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->id=htmlspecialchars(strip_tags($this->id));

        // bind id of record to delete
        $stmt->bindParam(1, $this->id);

        // execute query
        if($stmt->execute()){
            return true;
        }

        return false;

    }

    // search products
    function search($keywords){

        // select all query
        $query = "SELECT
                    c.name as category_name, p.id, p.name, p.eMail, p.phoneNumber,  p.colorScooter, p.amountScooters, p.inputDate, p.returnDate, p.category_id, p.created
                FROM
                    " . $this->table_name . " p
                    LEFT JOIN
                        categories c
                            ON p.category_id = c.id
                WHERE
                    p.name LIKE ? OR p.description LIKE ? OR c.name LIKE ?
                ORDER BY
                    p.created DESC";

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // sanitize
        $keywords=htmlspecialchars(strip_tags($keywords));
        $keywords = "%{$keywords}%";

        // bind
        $stmt->bindParam(1, $keywords);
        $stmt->bindParam(2, $keywords);
        $stmt->bindParam(3, $keywords);

        // execute query
        $stmt->execute();

        return $stmt;
    }

    // read products with pagination
    public function readPaging($from_record_num, $records_per_page){

        // select query
        $query = "SELECT
                    c.name as category_name, p.id, p.name, p.eMail, p.phoneNumber,  p.colorScooter, p.amountScooters, p.inputDate, p.returnDate, p.category_id, p.created
                FROM
                    " . $this->table_name . " p
                    LEFT JOIN
                        categories c
                            ON p.category_id = c.id
                ORDER BY p.created DESC
                LIMIT ?, ?";

        // prepare query statement
        $stmt = $this->conn->prepare( $query );

        // bind variable values
        $stmt->bindParam(1, $from_record_num, PDO::PARAM_INT);
        $stmt->bindParam(2, $records_per_page, PDO::PARAM_INT);

        // execute query
        $stmt->execute();

        // return values from database
        return $stmt;
    }

    // used for paging products
    public function count(){
        $query = "SELECT COUNT(*) as total_rows FROM " . $this->table_name . "";

        $stmt = $this->conn->prepare( $query );
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        return $row['total_rows'];
    }

}

Added 11-08-2018

Adding var_dump($product); results in showing that the variable $product does return the table and $data is actually where to problem lies.

result of var_dump($product);

 ["table_name":"Product":private]=>
  string(8) "products"
  ["id"]=>
  NULL
  ["name"]=>
  NULL
  ["email"]=>
  NULL
  ["phone"]=>
  NULL
  ["amount"]=>
  NULL
  ["description"]=>
  NULL
  ["pickup"]=>
  NULL
  ["back"]=>
  NULL
  ["category_id"]=>
  NULL
  ["category_name"]=>
  NULL
  ["created"]=>
  NULL

Current status

If I open the create.php file it does create a product, but If i use the form I get the error Unable to create product.

Also when I open the create.php file I get the following error message:

<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>37</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>38</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>39</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>40</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>41</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>42</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>43</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>C:\xampp\htdocs\api\product\create.php</b> on line <b>44</b><br />

It seems it can't find the "name" properties.

I've got the idea whats causing the issue,

factory

// create product
factory.createProduct = function($scope){
    return $http({
        method: 'POST',
        data: {
            'name' : $scope.name,
            'email' : $scope.email,
            'phone' : $scope.phone,
            'amount' : $scope.amount,
            'description' : $scope.description,
            'pickup' : $scope.pickup,
            'back' : $scope.back,
            'category_id' : 1
        },
        url: 'http://localhost/api/product/create.php'

    });
};

my controller

// create new product
$scope.createProduct = function(){

    productsFactory.createProduct($scope).then(function successCallback(response){

        // tell the user new product was created
        $scope.showToast(response.data.message);

        // refresh the list
        $scope.readProducts();

        // close dialog
        $scope.cancel();

        // remove form values
        $scope.clearProductForm();

    }, function errorCallback(response){
        $scope.showToast("Unable to create record.");
    });
}

product.php

    // create product
function create(){

    // query to insert record
    // $query = "INSERT INTO " . $this->table_name . 
    // "(name, email, phone, amount, description, pickup, back, created, modified)" .
    // " VALUES(:name, :email, :phone, :amount, :description, :pickup, :back, :created, :modified)";

    $query = "INSERT INTO
                " . $this->table_name . "
            SET
                name=:name, email=:email, phone=:phone, amount=:amount, description=:description, pickup=:pickup, back=:back, category_id=:category_id, created=:created";

    // prepare query
    $stmt = $this->conn->prepare($query);

    // sanitize
    $this->name=htmlspecialchars(strip_tags($this->name));
    $this->email=htmlspecialchars(strip_tags($this->email));
    $this->phone=htmlspecialchars(strip_tags($this->phone));
    $this->amount=htmlspecialchars(strip_tags($this->amount));
    $this->description=htmlspecialchars(strip_tags($this->description));
    $this->pickup=htmlspecialchars(strip_tags($this->pickup));
    $this->back=htmlspecialchars(strip_tags($this->back));
    $this->category_id=htmlspecialchars(strip_tags($this->category_id));
    $this->created=htmlspecialchars(strip_tags($this->created));

    // bind values
    $stmt->bindParam(":name", $this->name);
    $stmt->bindParam(":email", $this->email);
    $stmt->bindParam(":phone", $this->phone);
    $stmt->bindParam(":amount", $this->amount);
    $stmt->bindParam(":description", $this->description);
    $stmt->bindParam(":pickup", $this->pickup);
    $stmt->bindParam(":back", $this->back);
    $stmt->bindParam(":category_id", $this->category_id);
    $stmt->bindParam(":created", $this->created);

    // execute query
    if($stmt->execute()){
        return true;
    }

    return false;

}

Create.php

<?php


// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

// get database connection
include_once '../config/database.php';

// instantiate product object
include_once '../objects/product.php';

$database = new Database();
$db = $database->getConnection();

$product = new Product($db);

// get posted data
$data = json_decode(file_get_contents("php://input"));

echo $data;

var_dump($data);

var_dump($product);


print_r($data);

var_dump($product->name);

// set product property values
$product->name = $data->name;
$product->email = $data->email;
$product->phone = $data->phone;
$product->amount = $data->amount;
$product->description = $data->description;
$product->pickup = $data->pickup;
$product->back = $data->back;
$product->category_id = $data->category_id;
$product->created = date('Y-m-d H:i:s');



var_dump($product->name);
var_dump($data->name);

echo is_array($product->name) ? 'Array' : 'not an Array';

echo json_last_error();
// create the product
if($product->create()){
    echo '{';
        echo '"message": "Product was created."';
    echo '}';
}

// if unable to create the product, tell the user
else{
    echo '{';
        echo '"message": "Unable to create product."';

    echo '}';
}


?>

Update 08-12-2018

Running the createproduct() it does post it into create.php

I checked it with google chrome's inspector network tab.

{name: "test", email: "test", phone: "test", amount: "test", description: "test", pickup: "test",…}
amount
:
"test"
back
:
"test"
description
:
"test"
email
:
"test"
name
:
"test"
phone
:
"test"
pickup
:
"test"

it also returns code:200

which according to this link means:

200 OK This response code indicates that the request was successful.

201 Created This indicates the request was successful and a resource was created. It is used to confirm success of a PUT or POST request.

It seems it's not creating new resources and nothing has been posted.

like image 497
Salman Avatar asked Aug 02 '18 18:08

Salman


3 Answers

Why do you use php://input? Is there a reason why you are not using $_POST to access the posted data? If a POST-Request hits php the global associative array $_POST gets created. Each index will match one of your name-attributes from your form and contain its value.

The errors displayed could come from this approach because php://input can be anything, so $data can be. If that's the case you try to assign values ($reservation->name = $data->name;) out of an object which is actually not an object.

// get posted data
$data = json_decode(file_get_contents("php://input"));

// set product property values
$reservation->name = $data->name;
$reservation->eMail = $data->eMail;
$reservation->phoneNumber = $data->phoneNumber;
$reservation->colorScooter = $data->colorScooter;
$reservation->amountScooters = $data->amountScooters;
$reservation->inputDate = $data->inputDate;
$reservation->returnDate = $data->returnDate;
$reservation->category_id = $data->category_id;
$reservation->created = date('Y-m-d H:i:s');

clarify the datatype of $data and make sure it stays the same no matter what. (try using var_dump instead of echo or print_r, grants additional information)

like image 141
netzding Avatar answered Sep 22 '22 15:09

netzding


make sure to check all variable values and array values before doing any transaction. You can validate them at any point you want by using

isset() 

and

is_array()

So, you will get clear idea about whic one is not set at the right place. So you will be able to trace it very clearly. Otherwise you will waste your time by tracing the problem.

like image 22
LahiruTM Avatar answered Sep 24 '22 15:09

LahiruTM


  1. Check what you get on file_get_contents("php://input") (var_dump)
  2. In factory.createProduct you have url: 'http://localhost/api/product/create.php'. Is this what you want? Calling from remote to localhost? Souldn't you use '/api/product/create.php'?
like image 20
arczinosek Avatar answered Sep 23 '22 15:09

arczinosek