Getting data from Android device in laravel - json

I am trying to get data from android in server in laravel. What I did till now is :
here in my route:
Route::any('jsondata','JsonController#jsonFunction');
And in my controller:
public function jsonFunction()
{
$jsonPostedData = Input::all();
return response(['jsonobjtest'=>$jsonPostedData]);
}
}
What it gives in browser is:
{"jsonobjtest":[]}
Actually i want to do is i want to send a success message to android device when it sends data. And get data here in server.

You can write like this
In your Controller
public function jsonFunction()
{
$jsonPostedData = Input::all();
// do something with your data insert or update or anything
if(count($jsonPostedData) > 0) // here you might write any of your condition.
{
return response()->json(['success'=>true]);
}
return response()->json(['success'=>false,'error'=>'your error message']);
}

You can try following code
public function jsonFunction(){
$requestObj=Input::all();
return response()->json(['success'=>true,'request_param'=>$requestObj]);
}

You can check whether
$jsonPostedData = Input::all();
input contain data or not by by simply
die and dumping $jsonPostedData variable
example
dd($jsonPostedData);

Related

Consuming IMDB api results bad json

I have a simple program that consumes IMDB api, I'm getting the result, but it was shown as error because the result is not a structured json.
MovieService.ts
export class MovieService {
constructor(private http:HttpClient) { }
getMovie(movie:string){
return this.http.get(this.generateURL(movie));
}
private generateURL(movie:string){
return "https://v2.sg.media-imdb.com/suggests/titles/"+movie.charAt(0)+"/"+movie+".json?callback=imdb$"+movie;
}
}
addmovie.component.ts
private _filterMovies(value: string) {
this.movieService.getMovie(value).subscribe(
movies => {
console.log(movies);
return movies;
}
);
}
ngOnInit() {
this.addMovieForm.get('movie').valueChanges.subscribe(val => {
this._filterMovies(val)
});
}
I'm getting error like
the response is of bad json. How can I format the json upon receiving? How to solve this? Any leads would be helpful.
The result is not JSON, but rather JSONP. It is essentially returning you a script that is trying to execute the callback method specified.
Instead of http.get() you should call http.jsonp(url, "imbdIgnoresThisParam").
However, according to this answer, the callback query string parameter is ignored by IMDB. The answer suggests dynamically creating the expected callback function, whose name contains the title for which you are searching. In that callback you could do a few different things.
Use the closure to call / set something in your MovieService. This will result in your call to the API throwing an error, as the Angular framework's callback will not be called as expect. You could ignore the error.
Try to call the expected Angular callback, ng_jsonp_callback_<idx>. This will prevent the API call from throwing, but it may not be reliable. The callback name is dynamic and increments with each jsonp() call. You could try to track the number of jsonp() calls in your app. And of course, the framework may change and break this solution. Concurrent calls to getMovie() may break, as the next one may step on the previous callback on the window. Use with caution!
In typescript, your getMovie() function and related helpers might look like so:
private imdbData: any = null;
private jsonpIdx = 0;
private setImdb(json: any) {
this.imdbData = json;
// or do whatever you need with this
}
getMovie(movie:string) {
// dynamically create the callback on the window.
let funcName = `imdb$${movie}`;
window[funcName] = (json: any) => {
// use the closure
this.setImdbData(json);
// or try to call the callback that Angular is expecting.
window[`ng_jsonp_callback_${this.jsonpIdx++}`](json);
}
// go get your data!
let url = this.generateURL(movie)
return this.http.jsonp(url, "ignored").subscribe((json) => {
// this happens if you successfully trigger the angular callback
console.log(json);
}, (err) => {
// this happens if the angular callback isn't called
console.log(this.imdbData); // set in closure!
});
}
Edit for Angular 4
For Angular 4, it looks like you will need to import the JsonpModule along with the HttpModule. Then, you'd inject jsonp just like you'd inject http into your service. The call to IMDB becomes this.jsop.request(url).subscribe(...) and your dynamic callback name needs to change, too.
window[funcName] = (json: any) => {
// or try to call the callback that Angular is expecting.
window["__ng_jsonp__"][`__req${this.jsonpIdx++}`]["finished"](json);
}
I don't have an Angular 5 or 6 project immediately set up, so hard to say if there are any differences with the callback in those versions.
Sort of a hack, but hope it helps!

GET,POST,PUT Which should be used for receiving a json object to my rest api and send a json object in response?

I'm writing my first web API using MVC.
I'm aware that POST and PUT are usually implemented to define the HTTP methods for inserting or updating a database behind an API. But all I want to do is receive a JSON object from the caller, do some processing then return another JSON object in response. No database is involved.
I've tested using both POST and GET in my API controller method and they both work ok but which http method should I actually be using for best practice?
eg
public IHttpActionResult Get(ApiEquipment equipment)
{
// Convert equipment to a compatible buffer
return Ok(new ConvertToBuffer(equipment));
}
GET is useful for SAFE(*) operations where you do not need to pass many parameters to the server - all of the parameters must be in the URL as GET operations do not pass data in the HTTP body.
POST is useful for UNSAFE(*) operations or operations where you need to pass large amounts of data to the server as the data can be passed in the HTTP body.
Use GET for simple queries and calculations with few parameters. Use POST for large payloads or operations that change server state (such as updating something or performing complex bussiness operations).
See the HTTP method definitions in RFC 7231 for more in-depth information.
(*) SAFE operations are operations that do not change (visible) server state. UNSAFE operations do change (visible) server state.
GET
It seems that your just want to retrieve data in a meaningful representation (response after processing) from the raw data (request from the caller).
There is no modification / insertion of data, so GET should be use.
The POST verb seems to be what you want.
If I understand correctly, you want to send a JSON from the client to server. Then the server will modify the JSON and return it to the client.
In REST APIs, POST is commonly used to create a new resource. But it's also a catch-all verb for operations that should not be executed using the other methods.
For more details on using POST to invoke arbitrary processing, have a look at this answer.
I would suggest you to use 'HTTPPOST' if you require to process your JSON object else useGETmethod.
Consider this example for using HttpPost method since I process the JSON object to get some info from database.
[HttpPost]
public IHttpActionResult Masters([FromBody]Download_Config_UserInfo Info)
{
List<TestMaster> testMaster = null;
ResponseValidation objValidation = new ResponseValidation();
try
{
#region Validation
objValidation = base.ValidateRequest(Info);
if (!objValidation.isValid)
return base.JsonErrorResult(this.MasterName, objValidation.ErrorCode, objValidation.ErrorDesc);
#endregion
#region Initialization
this.Initialization();
#endregion
#region Functionality
//testMaster = this.GetTestMaster();
testMaster = this.GetTestDateMaster();
if (testMaster == null)
return base.JsonErrorResult(this.MasterName, "E19", "Data Not Available");
var result = (from a in testMaster
select new object[]
{
a.TestId,
a.TestName
});
#endregion
return base.JsonResult(this.MasterName, this.Fields, result);
}
catch (Exception ex)
{
loggerService.Error(Info.ToJSON(), this.MasterName, ex);
return base.JsonErrorResult(this.MasterName, "E20", "Internal Server Error", ex.Message + "_" + ex.StackTrace);
}
finally
{
testMaster = null; objValidation = null; base.UserMaster = null; base.UserPositionMapping = null;
}
}
#endregion
#region Functionality
[NonAction]
public List<TestMaster> GetTestMaster()
{
List<ADM_Retailer> testMaster = null;
try
{
testMaster = this.GetTest();
if (testMaster == null || (testMaster.Count == 0)) { return null; }
string weekNo = base.GetWeekNumber();
return (from a in testMaster
select new TestMaster
{
TestId = a.ARTR_Id,
TestName = a.ARTR_Name,
}).ToList();
}
finally { }
}

Allow to get POST data from outter server YII2

i want to make a yii2 route which can receive POST data from other server (of course i know about all risk).
I tried to just send it like usual but i got this error message.
Error 400
Unable to verify your data submission.
more or less is just like this...
public function actionWriteSession()
{
if (isset($_POST))
{
print_r($_POST);
...
write to session
...
}
...
}
Any Advice?
Thanks..
You should disbale csrf verification E.g:
$this->enableCsrfValidation=false;//In your controller context
// Or if you only use this action for sending post from outer server
// you can disbalecsrf token verification only this action. So, in your controller
public function beforeAction($action)
{
if ($action->id == 'writeSession') {
Yii::$app->controller->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}

Return eloquent collection as json format

I'm trying to implement a RESTful api in Laravel, and I for my index I want to return all the tasks as json.
However, when I use
return Response::json(Task::all());
I get an error: "The Response content must be a string or object implementing __toString(), "boolean" given".
I get the same error when I use:
return Task::all();
I thought this was supposed to work? What am I doing wrong?
I double-checked to see if Task::all() actually returns anything, and it does. This code does work in another project, although on another server and maybe another php version?
Someone suggested to use toArray(), but I get the same result. Code:
<?php
class UserController extends BaseController {
public function index() {
$users = User::all();
$userArray = $users->toArray();
return Response::json($userArray);
}
}
Response::json function is expecting argument 1 to be an array. From the API:
json( string|array $data = array(), integer $status = 200, array $headers = array() )
Return a new JSON response from the application.
So you can't just pass through the results of your find, but instead use the toArray() function and pass that through instead:
$tasks = Task::all();
Response::json($tasks->toArray());
Edit ---
If you're working with a BLOB, then base64_encode it first. See this post.
Example:
base64_encode($user['image']);

Fatal error: Can't use function return value in write context SOMETIMES

I get so annoyed when I transfer websites from one machine to another and I get a bunch of errors, such as this case. But this one made it to my curiosity and this is why I'm asking a question. I have the following code:
namsepace MF;
class Box {
private static $dumpYard = array();
public static function get($name) {
return self::$dumpYard[$name];
}
public static function set($name, $value, $overwrite=false) {
if($overwrite || !isset(self::$dumpYard[$name])){
self::$dumpYard[$name] = $value;
}else{
if(DEBUG_MODE){
echo('Value for "'.$name.'" already set in box, can\'t overwrite');
}
}
}
}
So when my application gets to the following line on my LOCAL testing server:
if(!empty(\MF\Box::get('requestsSpam'))){
throw new \Exception('Please don\'t spam');
}
I get a Fatal error: Can't use function return value in write context. However this code does not throw an error on the actual hosting server of my website. How come is that?
empty() works only with a variable. It should be:
$result = \MF\Box::get('requestsSpam');
if(!empty($result)){
throw new \Exception('Please don\'t spam');
}
Why? empty() is a language construct and not a function. It will work only with declared variables, that's just how it is designed, no magic.