Reputation: 180
Could someone please help me? I have this 500 error when making a post request... Can't understand what it is
NOTE: If i run this api on from a rest client Chrome Extension it works Otherwise i get the following error...
The application could not run because of the following error: Details Type: ErrorException Code: 8 Message: Trying to get property of non-object Line:114
Routes:
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/events','getEvents');
$app->get('/events/:year/:month', 'getMonth');
$app->get('/events/:year/:month/:day','getAllAfter');
$app->post('/events', 'addEvent');
$app->run();
This is My Function:
function addEvent() {
$app = \Slim\Slim::getInstance();
$request = $app->request();
$body = $request->getBody();
$event = json_decode($body);
//Line 114
$submited_date = $submited_date = $event->{'date_submit'} .' '.$event->{'time_submit'};
$sql = "INSERT INTO events (edate, title, performers, address) VALUES (:edate, :title, :performers, :address)";
try {
$conx = getconx();
$stmt = $conx->prepare($sql);
$stmt->bindParam("edate", $submited_date);
$stmt->bindParam("title", $event->etitle);
$stmt->bindParam("performers", $event->performers);
$stmt->bindParam("address", $event->address);
$stmt->execute();
$event->id = $conx->lastInsertId();
$conx = null;
$result = array("status"=>"success","events"=>$event);
echo json_encode($result);
} catch(PDOException $e) {
$result = array("status"=>"error","message"=>'Exception: ' . $e->getMessage());
echo json_encode($result,JSON_PRETTY_PRINT);
}
}
This is the json sent:
{
"date":"24 March, 2014",
"date_submit":"2014-03-24",
"time":"4:00 PM",
"time_submit":"16:00:00",
"etitle":"Event Title",
"performers":"david",
"address":"Place"
}
jquery code: fixed by using JSON.stringify(); to the data before sending request
function addEvent(jsondat) {
console.log('addEvent');
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL,
dataType: "json",
data: JSON.stringify(jsondat); ,
success: function(data, textStatus, jqXHR){
alert(Event created successfully');
},
error: function(jqXHR, textStatus, errorThrown){
alert('addEvent error: ' + textStatus);
}
});
}
jQuery(document).on('ready', function() {
jQuery('form#myForm').bind('submit', function(event){
event.preventDefault();
var form = this;
var pson = ConvertFormToJSON(form);
//document.write(JSON.stringify(pson));
addEvent(pson);
});
});
Upvotes: 1
Views: 9507
Reputation: 180
The problem was found and it wasn't in my index.php it was in the ajax request... This was fixed by using JSON.stringify() to my serialized array.
That's why just in the rest client worked because the json there was sent correctly... Thanks to Matt from slim framework support http://help.slimframework.com/discussions/problems/6789-not-able-to-handle-post-request
Upvotes: 2