Laravel 5 access to ajax Post Data - php

I'm trying to receive data from a form through AJAX on Laravel 5.
JavaScript code:
event.preventDefault(); // Disable normal behaviour of the element (Form)
var formData = {
form: $("#newCustomerForm").serialize() // Transmit all input data of the form serialized
}
console.log(formData); // Log to the console the Input data
$.ajax({
type: 'post', // POST Request
url: 'save', // Url of the Route (in this case user/save not only save)
data: formData, // Serialized Data
dataType: 'json', // Data Type of the Transmit
beforeSend: function (xhr) {
// Function needed from Laravel because of the CSRF Middleware
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success: function (data) {
// Successfuly called the Controler
// Check if the logic was successful or not
if (data.status == 'success') {
console.log('alles ok');
} else {
console.log(data.msg);
}
},
error: function (data) {
// Error while calling the controller (HTTP Response Code different as 200 OK
console.log('Error:', data);
}
});
Route:
Route::post ('user/save', 'CustomerController#createNewCustomer');
Controller:
public function createNewCustomer (Request $request)
{
$inputArray = $request->all();
print_r ($inputArray['form']);
// Set JSON Response array (status = success | error)
$response = array ('status' => 'success',
'msg' => 'Setting created successfully',);
// Return JSON Response
return response ()->json ($response);
}
In the network tab I can see how the parameters look like:
radio-inline-left=on&firstname=sdsd&private_lastname=&private_title=&private_birthdate=&private_email=&business_email=&private_phone=&business_phone=&private_mobile=&business_mobile=&brand=&business_job_title=&business_address_street=sdsd&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&business_address_street=&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&source=social_media&source=&availability=on&additional-info={"status":"success","msg":"Setting created successfully"}
I also tried to access the data with $request->input('name of the field') but then it's always empty.
Does anybody have an idea what i'm doing wrong?

The problem is that you are calling $("#newCustomerForm").serialize(), and this method serializes the form in url-encoded parameters and not a json encoded body.
In this question an answer is provided for this to work.

You can access like this
$request['name of field'];

i think you need to receive the data in the controller as json:
$request->json('field_of_interest')

The problem is your formData variable. Instead of:
var formData = {
form: $("#newCustomerForm").serialize()
}
it should be
var formData=$("#newCustomerForm").serialize();

Related

Passing data via ajax issues

I'm trying to pass data to my laravel controller function via Ajax. At this point I just want to return the data being sent to verify ajax is working. I can "GET" with ajax, but when I try to "POST" ajax brakes.
Could someone please tell me what I'm doing wrong? Thank you.
Here is my ajax code...
var startMapLocation = { startCity: "Cleveland", startStat: "Oh" };
$.ajax({
type: "POST",
url: url,
data: startMapLocation,
success: function(data, status) {
//alert(data);
console.log("success:", data);
},
error: function() {
alert("Ajax Broke!" + status);
}
});
My laravel function is...
public function postphp( Request $request)
{
$a = $request->all();
$city = $a["startCity"];
return json_encode( $city );
}
Thanks every one for your help. To resolve this issue, I first had to verify that my route was a post route not a get route.
Route::post('/postphp', 'GSResultController#postphp');
I also need to get my csrf-token and add it to the ajax call.
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
This fixed my problem.

json_decode in Symfony controller returns array of length 0

I'm relatively new to Symfony, and I think my problem is in my controller, but cannot see it. I'm sending valid JSON via ajax request to my controller. When attempting to decode it, the resulting array is of length 0, like my JSON isn't being decoded properly or maybe returned by getContents() properly?
js/ajax:
$('#aggregate').on('click',function(){
var sorted = [];
$('.sortable-items').each(function(){
sorted.push(JSON.stringify($(this).sortable('toArray')));
});
console.log(sorted);
$.ajax({
url: '/documentwarehouse/items/aggregate',
type: "POST",
contentType : 'application/json',
data: {"sorted": sorted},
success: function (data){
alert(data);
}, error: function(data){
alert("Sorry");
}
});
});
example JSON stored in var sorted, and validated via JSONlint:
["[\"list1_23\",\"list1_24\",\"list1_16\",\"list1_17\",\"list1_19\"]", "[\"list2_22\"]", "[\"list4_21\"]"]
So, what gets sent as the json data via ajax, also validated, is:
{"sorted":[" . [\"list1_23\",\"list1_24\",\"list1_16\",\"list1_17\",\"list1_19\"]", "[\"list2_22\"]", "[\"list4_21\"]"]}
controller:
public function aggregateAction(Request $request){
$arrayOfListArrays = json_decode($request->getContent(),true);
$response = new JsonResponse([sizeof($arrayOfListArrays)]);
$response->send();
return $response;
}
The response alerted in the success block of my ajax call is 0.

AJAX call is not working as expected

I am trying to send form data using ajax. But there's an error in ajax operation and only "error" callback function is executed.
Here's what I tried:
$("#issue_submit").click(function (e) {
console.log("clicked on the issue submit");
e.preventDefault();
// Validate the form
var procurementForm = $("#it_procuremet_form");
if($(procurementForm).valid()===false){
return false;
}
// Show ajax loader
appendData();
var formData = $(procurementForm).serialize();
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
dataType: "json"
});
formRequest.done(function (res) {
console.log(res);
});
formRequest.error(function (res, err) {
console.log(res);
});
formRequest.always(function () {
$("#overlay-procurement").remove();
// do somethings that always needs to occur regardless of error or success
});
});
Routes are defined as:
$f3->route('POST /itprocurement/save', 'GBD\Internals\Controllers\ITProcurementController->save');
Also I added :
$f3->route('POST /itprocurement/save [ajax]', 'GBD\Internals\Controllers\ITProcurementController->save');
I tried returning a simple string to the ajax call at the controller class.
ITProcurementController.php :
public function save($f3)
{
echo 'Problem!';
return;
$post = $f3->get('POST');
}
But only 'error' callback is executed. I cannot locate what is wrong. Please Help.
You are specifying that you expect json back:
// Send request to save the records through ajax
var formRequest = $.ajax({
url: app.baseurl("itprocurement/save"),
data: formData,
type: "POST",
// Here you specify that you expect json back:
dataType: "json"
});
What you send back is not json:
echo 'Problem!';
return;
This is an unquoted string, which is not valid json.
To send valid json back, you would need:
echo json_encode('Problem!');
return;
You could also remove the dataType attribute, depending on your needs.

Ajax post request is received as empty object

I send an ajax post request , and get a response, but it comes up empty. Is there is some details that need to be adjusted?
The idea is to send text that is submitted with a submit button. But just for testing, I have specified the data to be sent as "url": "helllo".
$(document).ready(function() {
$('form.ajax').on('submit', function(e) {
e.preventDefault();
var submitted = $(this),
destination = submitted.attr('action'),
method = submitted.attr('method'),
url_send = {
"url": "helllo"
};
$.ajax({
type: method,
contentType : 'application/json',
url: destination,
data: url_send,
success: function(response){
console.log(response);
},
error: function(){
console.log("there was an error");
}
});
The "method" (post) and "destination" is specified in the form. So "url_send" is the object which is sent. Should this be retrieved as {"url": "helllo"} on the other end, or is it nested inside an object?
In PHP with laravel,I have a controller function where the request is recieved:
$data = json_decode(file_get_contents("php://input"));
If $data is empty, it's returned:
return Response::json($data);
And that gives me
Object { }
You are passing data an object, so it will be urlencoded by jQuery.
urlencoded data is not JSON, so trying to parse it as JSON will fail.
You need to actually send JSON.
data: JSON.stringify(url_send)

HTTP 422 Error with JSON & jQuery + Human API

I am using the Human API found here: https://docs.humanapi.co/docs/connect-backend
At one point in connecting to the API, I need to send data back to them as JSON. I get a JSON object called sessionTokenObject which contains this:
{
humanId: "1234567890",
clientId: "abcdefg",
sessionToken: "9876zyx",
}
To which I'm supposed to add a clientSecret. Essentially, I'm taking what's in the JSON object, converting it individual variables, passing them through to another page via URL parameters and then reconstructing everything so that I can add the clientSecret like so:
$pop_clientid = $_GET['clientid'];
$pop_humanid = $_GET['humanid'];
$pop_userid = $_GET['userid'];
$pop_sessiontoken = $_GET['clientid'];
$my_sessiontokenobject = '{
humanId: "'.$pop_humanid.'",
clientId: "'.$pop_clientid.'",
sessionToken: "'.$pop_sessiontoken.'",
clientSecret: "thesecretgoeshere"
}'; ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
type: "POST",
url: 'https://user.humanapi.co/v1/connect/tokens',
data: '<?php echo $my_sessiontokenobject; ?>',
success: null,
dataType: 'application/json'
});
});
</script>
If I don't wrap the data value in the .ajax() call in apostrophes, I get a 422 error back from https://user.humanapi.com/v1/connect/tokens
If I do, I get an "Uncaught SyntaxError: Unexpected token ILLEGAL" error.
Can anyone see what's wrong with my code, or perhaps even tell me if trying to recreate a JSON object and then pass it back via .ajax() in the manner I am is just completely incorrect?
Try with this: (Returns a 404 Not found error, but it seems that it is in their side)
connectBtn.addEventListener('click', function(e) {
var opts = {
// grab this from the app settings page
clientId: clientId,
// can be email or any other internal id of the user in your system
clientUserId: clientUserId,
clientSecret: clientSecret,
finish: function(err, sessionTokenObject) {
console.log(sessionTokenObject);
// When user finishes health data connection to your app
// `finish` function will be called.
// `sessionTokenObject` object will have several fields in it.
// You need to pass this `sessionTokenObject` object to your server
// add `CLIENT_SECRET` to it and send `POST` request to the `https://user.humanapi.co/v1/connect/tokens` endpoint.
// In return you will get `accessToken` for that user that can be used to query Human API.
sessionTokenObject.clientSecret = clientSecret;
jQuery(document).ready(function($) {
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
contentType: "application/json",
data: sessionTokenObject,
});
});
// clientId=ceb8b5d029de3977e85faf264156a4e1aacb5377&humanId=f54fa4c56ca2538b480f90ed7b2c6d22
// $.post(url, sessionTokenObject, function(res){
// console.log(res);
// });
},
close: function() {
// do something here when user just closed popup
// `close` callback function is optional
}
}
HumanConnect.open(opts);
});
Human API Code for Testing, this code generates accessToken from Human API Developer Side but its not coming as in response while i execute this code
<script src='https://connect.humanapi.co/connect.js'></script>
<script>
var options = {
clientUserId: encodeURIComponent('email'), //Unique ID of user on your system (we send this back at the end)
clientId: '',
publicToken: '',
finish: function (err, sessionTokenObject) {
/* Called after user finishes connecting their health data */
//POST sessionTokenObject as-is to your server for step 2.
console.log(sessionTokenObject);
sessionTokenObject.clientSecret = 'Client Secret Key';
$.ajax({
type: 'POST',
url: 'https://user.humanapi.co/v1/connect/tokens',
method: 'POST',
data: sessionTokenObject
})
.done(function (data) {
console.log(data);
// show the response
if (data.success) {
alert(data.success);
} else {
alert(data.error);
}
})
.fail(function (data) {
console.log(data);
// just in case posting your form failed
alert("Posting failed.");
});
// Include code here to refresh the page.
},
close: function () {
/* (optional) Called when a user closes the popup
without connecting any data sources */
alert('user clicked on close Button');
},
error: function (err) {
/* (optional) Called if an error occurs when loading
the popup. */
}
}
function openHumanApiModel() {
HumanConnect.open(options);
}
</script>

Categories