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);
});
});
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
Related
I have an API that requires a string parameter. I want to take the query parameter to the controller and process there. I tried $ajax_data = Input::get('query'); but it didnt work. Searched the same question but cant find a decent answer. Current error is $ajax_data is empty.
My ajax request:
const sendAPIRequest = function (csrf, f) {
$.ajax({
async: false,
url: 'api/apitest',
method: 'get',
data:{
query:"select?facet=on&q=*:*&rows=1&json.facet={Categories:{type:terms,field:price,limit:3}}"
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + tkid);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('X-CSRF-TOKEN', csrf.trim());
},
success: function (data) {
f(data);
},
error: function(xhr) {
//Do Something to handle error
}
});
};
My Controller API part:
public function apitest(){
$ajax_data = Input::get('query');
$user_type = UserAuthorizationHelper::user_authorization();
if ($user_type == Authorities::EDIT_ORGANISATIONS) {}
$query = new GuzzleHttp\Client();
try {
$response = $query->request('GET',SolrController::$url.$ajax_data);
} catch (GuzzleHttp\Exception\GuzzleException $e) {}
$data = $response->getBody()->getContents();
return response()->json(json_decode($data));
}
You are having a problem in this line:
$ajax_data = Input::get('query');
When you are making a request, Request object is sent with the data.
So, instead of Input replace it with Request's object, and you will get the desired output.
Something like this:
// Don't forget to import the Request's namespace
public function apitest(Request $request)
{
$ajax_data = $request->get('query');
// ... Rest of your code
}
I'm new to php and stuck in my tracks here, so any help is appreciated. I've written a few functions in a JS file to render and update a gallery view for a WordPress template I made. From the updateGallery() function, I make an AJAX call after pressing a submit button on the page, but am receiving a "parsererror."
Arguments(3) [{…}, "parsererror", SyntaxError: Unexpected token A in JSON at position 0 at parse (<anonymous>)
at Ut (https://…, callee: ƒ, Symbol(Symbol.iterator): ƒ]
I tried the code for the API request directly in my WP template to render a response and it worked as expected, but when I try to incorporate my script I get the error and I can't figure out what's causing it.
JS
function updateGallery() {
var county = $("#county").val();
jQuery(".galleryGrid").fadeOut("fast", function() {
console.log("ajax request");
jQuery(".galleryGrid").html("").hide();
$.ajax({
type : "GET",
dataType : "JSON",
url : ajax.url,
data : {
action: "get_gallery_data",
county_id : county
},
error: function(response, error) {
console.log(arguments);
alert("Failed because: " + error);
},
success : function(response) {
if(response.type === "success") {
console.log("Success")
renderGrid(response.data);
}
}
});
});
}
PHP
add_action("wp_ajax_nopriv_get_gallery_data", "get_gallery_data");
add_action("wp_ajax_get_gallery_data", "get_gallery_data");
function get_gallery_data() {
$county_id = $_REQUEST[county_id];
$base_api_url = "https://some.api.com/";
$filters = array(
"field" => "field_153",
"operator" =>"is",
"value" => $county_id
);
$filters_url = rawurlencode(json_encode($filters));
$api_url = $base_api_url."?filters=".$filters_url;
$request = wp_remote_get($api_url, array(
"headers" => array(
"Application-Id" => "5xxxxxx",
"REST-API-KEY" => "0xxxxxx",
),
));
$body = wp_remote_retrieve_body($request);
$output = json_decode($body, true);
echo $output;
die();
};
$output = json_decode($body, true);
//Change
$output = json_encode($body, true);
Hi I'm having a problem with my code, I've checked it multiple times but can't seem to locate it. I'm working with HTML, JS, Slim framework and PHP and getting my data from mysql.
Any help would be appreciated!
JS
$(document).ready(function(){
$("#edit").click(function(){
var coach=new Coach(
$("#CoachFirstName").val(),
$("#CoachLastName").val(),
$("#CoachExperienceYrs").val(),
$("#CoachPastTeam").val());
$.ajax({
type:'PUT',
dataType:"json",
url:"db.php/coachs/1",
data:JSON.stringify(coach),
success: showResponse,
error: showError
});
}); });
function Coach(CoachFirstName, CoachLastName, CoachExperienceYrs, CoachPastTeam){
this.CoachFirstName=CoachFirstName;
this.CoachLastName=CoachLastName;
this.CoachExperienceYrs=CoachExperienceYrs;
this.CoachPastTeam=CoachPastTeam;
} function showResponse(responseData) {
console.log(responseData); }
function showError() {
alert("Error while updating" );
};
PHP - SLIM
$app->put('/coachs/:id', 'updateCoach');
function updateCoach($id){
$request = Slim::getInstance()->request();
$coach = json_decode($request->getBody());
$sql = "UPDATE coach SET CoachFirstName=:CoachFirstName, CoachLastName=:CoachLastName, CoachExperienceYrs=:CoachExperienceYrs, CoachPastTeam=:CoachPastTeam WHERE CoachID=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("CoachFirstName",$coach->CoachFirstName);
$stmt->bindParam("CoachLastName",$coach->CoachLastName);
$stmt->bindParam("CoachExperienceYrs",$coach->CoachExperienceYrs);
$stmt->bindParam("CoachPastTeam",$coach->CoachPastTeam);
$stmt->bindParam("id",$id);
$stmt->execute();
$coach = $stmt->fetchObject();
$db = null;
responseJson(json_encode($coach),200);
}catch(PDOException $e){
responseJson('{"error":{"text":'.$e->getMessage().'}}', 500);
}
}
Within my application I have an Ajax function that adds information to a database. Everything worked perfectly until I added in 2 more parameters which was location and username.
It still works with everything else but it doesn't add those last 2 into the database. The names of within the database is location and username. assignedUsername and storeLocation are set else where in the code.
Ajax:
$("#send").click(function(){
$.ajax({
type: 'POST',
contentType: "application/json",
data: orderFood(),
url: rootURL + "/orderFood",
dataType: "json",
success: function(data)
{
alert(assignedUsername);
alert("Data Added");
$.mobile.changePage("#mainMenu");
},
error: function(data)
{
alert(assignedUsername);
alert("Data NOT Added");
$.mobile.changePage("#mainMenu");
}
});
});
function orderFood()
{
alert(storeLocation + ", " + assignedUsername);
return JSON.stringify({
"food1": food1,
"food2": food2,
"food3": food3,
"food4": food4,
"food5": food5,
"food6": food6,
"food7": food7,
"food8": food8,
"food9": food9,
"location": storeLocation,
"username": assignedUsername
});
}
PHP:
$app->post('/orderFood/', 'orderFood');
function orderFood()
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$sql = "INSERT INTO subsordered(food1, food2, food3, food4, food5, food6, food7, food8, food9, location, username) VALUES (:food1, :food2, :food3, :food4, :food5, :food6, :food7, :food8, :food9, :location, :username)";
try
{
$db = getConnection();
$stmt=$db->prepare($sql);
$stmt->bindParam("food1",$q->food1);
$stmt->bindParam("food2",$q->food2);
$stmt->bindParam("food3",$q->food3);
$stmt->bindParam("food4",$q->food4);
$stmt->bindParam("food5",$q->food5);
$stmt->bindParam("food6",$q->food6);
$stmt->bindParam("food7",$q->food7);
$stmt->bindParam("food8",$q->food8);
$stmt->bindParam("food9",$q->food9);
$stmt->bindParam("location",$q->location);
$stmt->bindParam("username",$q->username);
$stmt->execute();
$db = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
I know the PHP is correct though testing with cURL but I thought I'd include it just to get the whole picture
I am extremely stuck with this, from what I can see it SHOULD work but it just doesn't
I want to store an image as a blob into my database(MySQL) while using PHP Rest service, but I dont know how to do it. Here is my PHP code (I'm using Slim framework for PHP)
function addProblem() {
global $app;
$postdata = file_get_contents("php://input");
$req = json_decode($postdata); // Getting parameter with names
$paramName = $req->station; // Getting parameter with names
$paramAdres = $req->address; // Getting parameter with names
$paramCity = $req->city;// Getting parameter with names
$parampostal = $req->postalcode;
$parampic = $req->pictureOfDamage;
$paramdescrip= $req->description;
$sql = "INSERT INTO problems (Station,Address,Postalcode,City,PictureOfDamage,Description) VALUES (:station,:address,:postalcode,:city,:pictureOfDamage,:description)";
try {
$dbCon = getConnection();
$stmt = $dbCon->prepare($sql);
$stmt->bindParam(':station', $paramName);
$stmt->bindParam(':address', $paramAdres);
$stmt->bindParam(':city', $paramCity);
$stmt->bindParam(':postalcode', $parampostal);
$stmt->bindParam(':pictureOfDamage', $parampic);
$stmt->bindParam(':description', $paramdescrip);
$stmt->execute();
$dbCon = null;
echo json_encode("toegevoegd ");
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
and this is my angular code (i'm using fileuploader right now.)
.controller('MeldingController', function ($scope, $upload, $rootScope, $state, $http) {
$scope.station = $rootScope.station;
$scope.PictureOfDamage;
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var pictureOfDamage = files[i];
return pictureOfDamage;
}
}
}
$scope.submit = function () {
console.log($scope.PictureOfDamage);
var data = {
station: $scope.station.name,
address: $scope.station.streetName,
postalcode: $scope.station.postalCode,
city: $scope.station.city,
pictureOfDamage: $scope.upload($scope.files) /* picture*/,
description: document.getElementById("Description").value
}
console.log('NOJSN ', data);
data = JSON.stringify(data);
console.log('JSON', data)
$http({
method: "POST",
url: 'http://localhost/Dats24/problem/add/',
data: data})
.success(function (data, status, headers, config) {
$state.go('GoogleMaps');
}).error(function (data, status, headers, config) {
console.log(data);
});
};
})
For your angular application, you can use the upload method of the $upload service like this:
file_upload: function(file) {
return $upload.upload({
url: 'http://your-upload-url/',
file: file
});
}
as described in here : https://github.com/danialfarid/ng-file-upload
Then on your service in PHP, you can get the file using
move_uploaded_file($_FILES['file']['tmp_name'], $file_path);
It will store the file on the path of your choice, then you can use PHP to do whatever you want with the file data.