Laravel 4.1.* AJAX response method - php

I'm trying to setup a simple POST method with AJAX, posting to a Laravel controller and processed.
The issue I am having is returning a response that the AJAX call understand and can use.
routes.php
Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController#processSupplierApplication');
AJAX stuff to get form data:
$('#supplierChainCheckForm').submit(function( event ) {
event.preventDefault();
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// As we're using the "csfrUnsafeMethod" of POST - we'll need to setup the csfr token to be passed between client and server:
$.ajaxSetup({
// This is standard before send method for the ajaxSetup() function:
beforeSend: function(xhr, settings) {
// If settings.type in $.ajax method is unsafe i.e., if it is 'POST' then we'll need to set X-CSRFToken in the xhr Request Header: omitted && sameOrigin(settings.url) currently;
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", $('meta[name="csrf-token"]').attr('content'));
}
}
});
// Get all the form inputs into an array:
var $inputs = $('#supplierChainCheckForm :input');
// We can now loop over all of the input names & values of the form:
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
$.ajax({
type: 'POST', //This will always be a post method for the supplier chain check form.
url: 'supply-us/application', //URL endpoint for the post form method: we'll set this to the controller function we're targeting.
data: { 'companyName': values['companyName'] ,'_token': '{{ csrf_token() }}'}
}).done(function(response) {
console.log(response.companyName);
});
});
ApplicationController.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication() {
if (!Input::get('companyName') == null) {
$company = Input::get('companyName');
return Response::json([ 'companyName' => $company ], 200);
} else {
$company = "No compnay specified";
return Response::json([ 'companyName' => $company ], 200);
}
}
}
However, combining all of the above gives me
console.log(response.companyName) as "undefined"
Please advise. Please note, I am using Laravel 4.1.*

Update function parameter as below;
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $request) {
if (!$request->input('companyName') == null) {
$company = $request->input('companyName');
return Response::json([ 'companyName' => $company ], 200);
} else {
$company = "No compnay specified";
return Response::json([ 'companyName' => $company ], 200);
}
}
}

Related

How to pass variables from jquery fetch function to symfony routes.yaml?

So I want to call a controller in symfony by passing in my route declared in routes.yaml with a jquery fetch function and I want to pass to variables from jquery to the controller. How can I do that ?
Here's my jquery. I call this route and I want to pass the two variable on top with it.
var longitudde = lonLat[0];
var latudde = lonLat[1];
fetch('/weather_request)
.then(function(response) {
return response.json();
}).then(function(json) {
// ...
});
To pass those variables to routes.yaml in Symfony:
weather_request:
path: /weather_request
controller: App\Controller\WeatherController::weather
methods: [get]
defaults:
longitude: longitude
latitude: latitude
To finaly pass them in the weather function in WeatherController:
public function weather($longitude, $latitude)
{
return $this->render('weather/index.html.twig', ['weatherInfos' => $this->weatherService->getWeather($longitude, $latitude)]);
}
So how can I pass the longitude and latitude from jquery fetch to the controller here ? I'm new to Symfony so I could be completely wrong.
I guess this can help you :
$.ajax({
url: '{{path('weather_request')}}',
type: 'GET',
data: {
longitude: lonLat[0],
latutide: lonLat[1],
},
success: function(response) {
//called when successful
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
In your controller :
use Symfony\Component\HttpFoundation\Request;
public function weather(Request $request)
{
if ($request->isXMLHttpRequest()) {
$longitude = $request->query->get('longitude');
$latutide = $request->query->get('latutide');
}
}
for me I use it like that:
In Js:
const obj = {
"longitudde":lonLat[0],
"latudde":lonLat[1]
}
fetch('/weather_request',
{
method:'POST',
headers: {
'Content-Type':'application/json'
},
body:JSON.stringify(obj)
}).then(resp => {
return resp.json();
}).then(res => {
console.log(res)
//...
})
}
In Controller route annotations,but you can use with Route.yaml:
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
/**
* #Route("/weather_request", methods={"POST"})
*
*/
public function weather(Request $request)
{
$data = json_decode($request->getContent());
$longitude = $data->longitudde;
$latitude = $data->latudde;
return $this->render('weather/index.html.twig',
[
'weatherInfos' => $this->weatherService
->getWeather($longitude, $latitude)
]);
}

Form AJAX post response cycle in Laravel 4.1.*

I have a rather old site that I have inherited as part of a new position - it's been built to Laravel 4.1.* version specs.
My issue is Response::json returning undefined variables in the response, using standard AJAX post method with all CSRF stuff and ajaxSetup() defined correctly.
application.blade.php
$.ajax({
type: 'POST', //This will always be a post method for the supplier chain check form.
url: 'supply-us/application', //URL endpoint for the post form method: we'll set this to the controller function we're targeting.
data: { 'companyName': values['companyName'] }, //This will carry the form data that is needed to be passed to the server.
success: function (response) {
console.log(response['companyName']); << THIS LINE RETURNS "undefined"
console.log(typeof response) << THIS LINE RETURNS string
},
error: function (response) {
console.log(response);
},
});
values['companyName'] returns what I input into the form. The above "response" simple chucks back html - so I think my routes might be incorrectly defined or incorrectly defined in the AJAX url param, perhaps? Here are the two applicable routes:
routes.php
Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController#processSupplierApplication');
ApplicationController.php:
<?php
use Illuminate\Http\Request;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $request) {
if (Input::has('companyName')) {
$this->companyName = Input::get('companyName');
$data = [
'success': true,
'companyName': $this->companyName
];
return response()->json($data);
}
}
}
Any pro-tips would be greatly appreciated!
to check what your are missing in controller when posting or getting your result
usually which i follow
in blade.php
<.form method="post" action="{{url('supply-us/application')}}".>
{{csrf_field()}}
<.input type="text" name="companyName".>
<./form.>
remove dot try this it will help you to find missing thing in controller
in your blade
<.input type="text" name="companyName" id="companyName".>
in your ajax
var company = $('#companyName').val();
$.ajax({
type: 'POST',
url: 'supply-us/application',
data: { 'Company':company,'_token': '{{ csrf_token() }}' },
success: function (response) {
alert(data) // if this not work then try this alert(data.company)
},
error: function (response) {
console.log(response);
},
});
in your controller
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $req) {
if (!$req->get('Company')==null) {
$company = $req->get('Company');
return response()->json($company);
}else{
$company="no input give";
return response()->json($company);
}
}
}

Post method fail with Vue.js "500 (Internal Server Error)"

So I'm trying to store data in my election_users table but making a POST request gives a "500 (Internal Server Error)" error. My object does return the right "election_id". I don't know what I'm doing wrong.
here's my method in my vue script:
methods: {
createVote: function () {
var itemId = this.$route.params.id
var input = this.newUserVoted
this.newUserVoted.election_id = itemId
this.$http.post('http://www.nmdad2-05-elector.local/api/v1/electionuser', input)
.then((response) => {
this.newUserVoted = {'election_id': itemId}
}).catch(e => {
console.log(e)
console.log(input)
})
}
},
my UsersController.php
public function store(Request $request)
{
$userVoted = new ElectionUser();
$userVoted->election_id = $request['election_id'];
$userVoted->user_id = Auth::id();
if ($userVoted->save()) {
return response()
->json($userVoted);
}
}
my routesApi.php
Route::post( 'electionuser', 'UsersController#store' );
My ElectionUser.php
class ElectionUser extends Model
{
// Relationships
// =============
protected $fillable = [
'election_id',
'user_id'
];
public function election()
{
return $this->belongsToMany(Election::class);
}
}
You need to add CSRF token:
https://laravel.com/docs/5.4/helpers#method-csrf-token
For example in the view
<script>
var csrf = '{{csrf_token()}}';
</script>
And in your script
var formData = new FormData();
formData.append('_token', csrf);
formData.append('input', this.newUserVoted);
this.$http.post('http://www.nmdad2-05-elector.local/api/v1/electionuser', formData)

ajax demo for laravel, step by step

I think this code has a lot of errors. What i need is to create a form, do a XHR submit to the controller, get the data, send to model, check the validations, return to controller with the output of validation and then sent to the view the message "errors or success"
routes.php
Route::get('checkValidationEmail', 'HomeController#checkValidationEmail');
<?php
echo Form::open(array('url' => 'checkValidationEmail', 'class' => 'form_notify'));
echo Form::text('Email', Input::old('Email'), array('placeholder'=>'Email', 'class' => 'hg'));
echo Form::close()
?>
Notify Me!
ok, this works fine, next, the problems begin.
AJAX
<script>
$(function () {
$(".send_email").click(function () {
email = $('.hg').val();
$.ajax({
type: "POST",
url: 'checkValidationEmail', //what is the correct url?
data: {
email: email
}
}).done(function (msg) {
alert(msg);
});
});
});
</script>
500 error:
{"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException","message":"","file":"C:\\VertrigoServ\\www\\laravel\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php","line":1439}}
Controller
class HomeController extends BaseController {
public function checkValidationEmail() {
//how to get the data from form and pass to the model, more exactly validate($input)
if ($validation) {
return true;
}
else {
return 'incorrect email'; //how send this message to the view?
}
}
}
Model
class Home extends Eloquent {
protected $table = 'emails';
public function validate($input) {
//validations
}
}
In your route you are defined the checkValidationEmail as GET request and from your ajax, you are trying to access this as a POST request. So this will throw MethodNotAllowedHttpException. So you have to change your route from,
Route::get('checkValidationEmail', 'HomeController#checkValidationEmail');
To,
Route::post('checkValidationEmail', 'HomeController#checkValidationEmail');
Or,
Route::any('checkValidationEmail', 'HomeController#checkValidationEmail');

How do I use the PUT feature in REST

Using this git-hub library:
http://github.com/philsturgeon/codeigniter-restserver
How do I use the PUT feature to save its data?
example: example.com/put/some-data/some-data/...
you can use it like this: but take in count that PUT is less commonly used and not supported by most browsers
function somename_put()
{
$data = array('somedata: '. $this->put('some-data'));
$this->response($data);
}
You can do it with an ajax request e.g.
(assumes use of jQuery)
$.ajax({
url: '/index.php/my_controller/somedata',
type: 'PUT',
success: function(result) {
console.log(result);
}
});
According this (link: https://github.com/philsturgeon/codeigniter-restserver/blob/master/application/libraries/REST_Controller.php#L915), $this->put only return if passed a param to it (so that works: $username = $this->put('username')). But in REST_Controller, $this->_put_args is protected so, you will extend this class and can access it like: $params = $this->_put_args.
In short (this is just an example, you may improve it as you need);
<?php
// route: /api/users/123
class Users extends REST_Controller
{
...
// update a user's data
public function user_put() {
$params = $this->_put_args;
// you need sanitize input here, "db" is a pseudo
$username = $db->escape($params['username']);
$userpass = $db->escape($params['userpass']);
$db->update(array(
'username' => $username,
'userpass' => $userpass
), (int) $params['id']);
if (!$db->error) {
// suppose right code should be 201 for PUT
$this->response('Created', 201);
} else {
$this->response('Internal Server Error', 500);
}
}
}
?>
<script>
// Some ajax library
Ajax("/api/users/123", {
method: "PUT",
data: {username:"John", userpass:"new pass"},
onSuccess: function(){ console.log("Success!"); }
...
});
</script>

Categories