Laravel 5: Retrieve JSON array from $request - laravel-5

I'm a Laravel newbie and I'm converting a php/jquery app to Laravel. The original code used a JSON array with an ajax POST, which was retrieved like this:
$json = file_get_contents('php://input');
$data = json_decode($json,true);
I'm doing much the same thing on the POST side, but I don't see any data coming through in my Laravel $request collection. Is there something special that I need to do to retrieve JSON data structured like this:
[
{ "name": "John", "location": "Boston" },
{ "name": "Dave", "location": "Lancaster" }
]
Here is my jQuery ajax POST code (with hard coded data)
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
success:function(data) {
$('#save_message').html(data.message);
}
});
Here is the code in my Controller that receives the POST
public function store(Request $request)
{
dd($request->all());
}
But all I get is:
[]
Any ideas on how I can retreive my data?

You need to change your Ajax call to
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
contentType: "json",
processData: false,
success:function(data) {
$('#save_message').html(data.message);
}
});
change the dataType to contentType and add the processData option.
To retrieve the JSON payload from your controller, use:
dd(json_decode($request->getContent(), true));
instead of
dd($request->all());

$postbody='';
// Check for presence of a body in the request
if (count($request->json()->all())) {
$postbody = $request->json()->all();
}
This is how it's done in laravel 5.2 now.

Just a mention with jQuery v3.2.1 and Laravel 5.6.
Case 1: The JS object posted directly, like:
$.post("url", {name:'John'}, function( data ) {
});
Corresponding Laravel PHP code should be:
parse_str($request->getContent(),$data); //JSON will be parsed to object $data
Case 2: The JSON string posted, like:
$.post("url", JSON.stringify({name:'John'}), function( data ) {
});
Corresponding Laravel PHP code should be:
$data = json_decode($request->getContent(), true);

You can use getContent() method on Request object.
$request->getContent() //json as a string.

As of Laravel 5.2+, you can fetch it directly with $request->input('item') as well.
Retrieving JSON Input Values
When sending JSON requests to your application, you may access the
JSON data via the input method as long as the Content-Type header of
the request is properly set to application/json. You may even use
"dot" syntax to dig deeper into JSON arrays:
$name = $request->input('user.name');
https://laravel.com/docs/5.2/requests
As noted above, the content-type header must be set to application/json so the jQuery ajax call would need to include contentType: "application/json",
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
contentType: "application/json",
success:function(data) {
$('#save_message').html(data.message);
}
});
By fixing the AJAX call, $request->all() should work.

My jQuery ajax settings:
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: url,
dataType: "json",
type: "post",
data: params,
success: function (resp){
....
},
error: responseFunc
});
And now i am able to get the request via $request->all() in Laravel
dataType: "json"
is the important part in the ajax request to handle the response as an json object and not string.

Related

Shopify Ajax API

I am trying to access the Shopify backend to update a customer's email, phone, and name via Ajax request.
I'm receiving a 404 error. while in postman and in google chrome the values are returned correctly and in postman, I am able to modify the values with PUT type.
my code:
let custFN = document.getElementById("customerFirstName").getAttribute("value") ;
let custLN = document.getElementById("customerLarstName").getAttribute("value") ;
let custEM = document.getElementById("customerEmail").getAttribute("value") ;
let custPH = document.getElementById("customerPhone").getAttribute("value") ;
let custID = document.getElementById("customerId").getAttribute("value") ;
let customerdata = {
"customer": {
"id": custID,
"first_name": custFN ,
"last_name": custLN,
"email": custEM,
"phone": custPH,
}
};
var customer_data_json = JSON.stringify(customerdata);
jQuery.cookie("session", null);
jQuery.ajax({
url:'https://{api key}:{api password}#{mysotre}.myshopify.com/admin/api/2022-04/customers/{customer_id}}.json',
type: 'PUT',
cache: false,
data: customer_data_json,
crossDomain: true,
dataType: "JSONP",
contentType: "application/json; charset=utf-8",
success: function(response) {
console.log(response);
},
error: function(response) {
console.log("-------------------------------- <ERROR> --------------------------------");
console.log(response);
console.log("-------------------------------- </ERROR> --------------------------------");
}
});
I placed the values noted with {} above.
I have changed to JSONP from JSON to avoid and fix the CORS policy error.
keep in mind that the response readyState is 4.
P.S: As mentioned by Shopify documentation, I created a private app, and did all the steps required to CRUD using API in Shopify are done.

Django Ajax 'GET'

newbie here. I am trying to get some data from my database using ajax.
In my views.py,
def getEvents(request):
eventList = Events.objects.all()
events=[]
for event in eventList:
events.append({"name": event.name, "start": event.start, "end": event.end})
return HttpResponse(events, content_type="application/json")
Note that Events is the model that I am trying to parse. After I collect the data from this model, I want to return it to my template using the following ajax code:
$.ajax({
url: 'getEvents/',
datatype: 'json',
type: 'GET',
sucess: function(data) {
alert(data.name);
}
});
In my urls.py:
url(r'^getEvents/', views.getEvents, name='getEvents'),
However, I think I am doing something wrong because it doesn't work. I have been stuck on this for hours...Any ideas?
EDIT:
Okay. When I append the getEvents to the url, I do see all the database objects together in a dict but it seems my ajax is not working. How do I parse this data? The data is in the form:
[{"start": "2017-02-06", "end": "2017-02-07", "name": "Capstone Meeting"},
{"start": "2017-02-07T0:00", "end": "2017-02-08", "name": "Capstone"},
{"start": "2017-01-31T0:00", "end": "2017-02-01", "name": "dasdsd"},
{"start": "2017-01-31", "end": "2017-02-01", "name": "hjb"}]
Here is what I have so far...
$.ajax({
url: 'getEvents/',
datatype: 'json',
type: 'GET',
sucess: function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});
One of your errors is being caused by not using a JsonResponse in your view instead of an HttpResponse. Here’s how to fix that issue:
from django.http import JsonResponse
def getEvents(request):
eventList = Events.objects.all()
events=[]
for event in eventList:
events.append({"name": event.name, "start": event.start, "end": event.end})
return JsonResponse(events)
From the docs, the JsonResponse is
An HttpResponse subclass that helps to create a JSON-encoded response.
The reason that your regular HttpResponse didn’t work, is because you have to manually serialize the data to JSON when using an HttpResponse, e.g., something like:
import json
response_data = json.dumps(events)
return HttpResponse(response_data, content_type="application/json")
Otherwise, I think what will happen is that you will get a call to __repr__ on the events list which will get you python ast serialized data and not JSON serialized data.
First of all, there's a typo of your sucess function, it should be success.
Secondly, JSON response should be a dict object rather than a list, if you really want to get a JSON array response anyway, then you have to specify safe=False when you serializing the data by using JsonResponse(events, safe=False), otherwise you'll get a TypeError like TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
So the code sample should be:
def getEvents(request):
eventList = Events.objects.all().values("name", "start", "end")
return JsonResponse({"events": eventList})
And for frontend:
$.ajax({
url: 'getEvents/',
datatype: 'json',
type: 'GET',
success: function(data) {
$.each(data.events, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});

Update database with JSOn string asp.net MVC4

Hey I am trying to post a form to my controller as Json and then update the database where columns match. I can't seem to get it to work. I am using a function as shown below to convert the form data into a json string and it's posting through but I'm having trouble with the controller method I need to find out how to match the valuse in the json with the values in the database any help would be great
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "Admin/update/",
dataType: "json",
data: formToJSON(),
success: function (themessage) {
}
});
Converting form with JSON.stringify
function formToJSON() {
return JSON.stringify({
"username": $('#username').val(),
"fname": $('#fname').val(),
"lname": $('#lname').val(),
"address1": $('#address1').val(),
"address2": $('#address2').val(),
"postcode": $('#postcode').val(),
"town": $('#town').val(),
"memcat": $('#memcat').val(),
"phone": $('#phone').val(),
"email": $('#email').val(),
"message": $('#message').val(),
"password": $('#password').val(),
"Admin": $('#Admin').val(),
});
}
Post contains
{"username":"Broon","fname":"Paw","lname":"Broon","address1":"12 Glebe Street","address2":"Sinderins","postcode":"DD12 4RT","town":"Dundee","memcat":"Ordinary","phone":"123456","email":"paw#localhost","password":"paw","Admin":"no"}
Controller Method
//
// POST: /Admin/
public JsonResult update(string username)
{
var themessage = from b in db.member
select b;
themessage = themessage.Where(b => username.Contains(b.username));
foreach (var item in themessage)
{
item.username = username;
}
db.SaveChanges();
return Json(themessage, JsonRequestBehavior.AllowGet);
}
The problem is accessing the json data to match the database data. I'm guessing I may need to parse the json some way? Above I have only tried to match the username.

Posting JSON with AJAX request in play2

i'm using play framework 2.0.4
i have a route :
POST /addMail controllers.Application.addMail()
In my controller Application i define the addMail method :
public static Result addMail()
{
JsonNode json = request().body().asJson();
Long id = json.findPath("id").asLong(0);
String email = json.findPath("email").getTextValue();
GameScore gs = GameScore.findById(id);
gs.setEmail(email);
gs.save();
return ok();
}
If i call this method through CURL i have no problem :
curl --header "Content-type: application/json" --request POST --data '{"id": 13, "email": "test#DB.com"}' http://localhost:9000/addMail
But if i call this method through an AJX request i have a 500 response.
$addMailBtn.click(function(event) {
$this = $(this);
var id = $this.attr("id").substring(14);
var email = $("#saisieMailField_" + id).val();
$.ajax({
type: 'POST',
url: "#routes.Application.addMail()",
dataType:"json",
data: {"id":id, "email": '"' + email + '"'},
success: location.reload()
})
} );
If i print in my console my json data, json data is null when i perform my ajax request but is alright through curl.
I have tried to add
#BodyParser.Of(play.mvc.BodyParser.Json.class)
on my method but it doesn't change anything.
Thanks for your time.
This works for me. Note that i stringify the JSON object, and I think this is your problem.
$.ajax({
type: "POST",
url: "http://myservice:9000/api/v1/positions",
data: JSON.stringify({"nwLng":72.22,"nwLat":22.22, "seLng":22.22,"seLat":55.33}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { alert(data); },
failure: function (errMsg) { alert(errMsg); }
});

ExtJs 4.1 : How to send json data in the request body using Ext.Ajax.request()?

I would like to send json data using Ext.Ajax.request() then access it in ASP.NET using Request.InputStream which is the content of the request body. I need a way to tell ExtJs to write the data in the request body as it is done while using an Ext.data.proxy.Ajax.
Specify POST method and just use the request's jsonData config:
Ext.Ajax.request({
url: 'myUrl',
method: 'POST',
params: {
requestParam: 'notInRequestBody'
},
jsonData: 'thisIsInRequestBody',
success: function() {
console.log('success');
},
failure: function() {
console.log('woops');
}
});
If you want a record written as JSON you can use a JSON writer like this also.
var writer = Ext.create('Ext.data.writer.Json'),
record = Ext.getStore('SomeStoreID').first();
Ext.Ajax.request({
url: 'myUrl',
method: 'POST',
params: {
requestParam: 'notInRequestBody'
},
jsonData: writer.getRecordData(record),
success: function() {
console.log('success');
},
failure: function() {
console.log('woops');
}
});

Resources