ajax demo for laravel, step by step - php

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');

Related

I'm making an dependent drop-down of countries states and cities in Laravel 9 using jQuery and Ajax but getting an 500 internal server

I'm making an dependent drop-downn of countries states and cities in laravel using jQuery and Ajax. I'm doing it on localhost Xampp. First i use jQuery for country. when country change jQuery get value and send to Controller. But when i send value from RegistrationFormComponent to CountryStateCity Controller and try to show what value i get. I got an error ( POST http://127.0.0.1:8000/getstate 500 (Internal Server Error) ). i don't know why im getting this error.
Route:
Route::get('/register', [CountryStateCityController::class, 'getcountry']);
Route::POST('/getstate ', [CountryStateCityController::class, 'getstate']);
JQuery and Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$('#country').change(function () {
var cid = this.value; //$(this).val(); we cal also write this.
$.ajax({
url: "getstate",
type: "POST",
datatype: "json",
data: {
country_id: cid,
},
success: function(result) {
// if(cid == "success")
// alert(response);
console.log(result);
},
errror: function(xhr) {
console.log(xhr.responseText);
}
});
});
});
Controller
class CountryStateCityController extends Controller
{
public function getcountry() {
$country = DB::table('countries')->get();
$data = compact('country');
return view('RegistrationForm')->with($data);
}
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
public function getcity() {
}
}
I think i tryed every possible thing. But didn't work. Please tell me how can i get rid of this problem. And please also tell me how can i send data from component to controller using jquery and ajax and get value form controller and take data from database and send back to component.
This is written incorrectly.
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
It should look like this.
public function getstate(Request $request) {
$state = State::where('countryid', '=', $request->country_id)->get();
return response()->json($state);
}
please check controller function
public function getstate(Request $request) {
$state = State::where('countryid' `=` ,request->$countryid)->get();
return response()->json($state);
}

Ajax GET request is empty despite correct query string parameter

Using a simple Ajax GET request to retrieve some data, it successfully checks if($request->ajax()) {} but then fails any validation because there is no data in the Request $request variable. This happens only on the production server, on localhost everything works fine.
The console shows the intended URL https://example.com/employeeInfo?id=1, then error 422 (Unprocessable Entity). Output from error: function(jqxhr, status, exception) { alert('Exception:', exception); } gives an empty alert message.
View
<script>
(function ($) {
$(document).ready(function() {
$(".team-pic").off("click").on("click", function() {
$id = $(this).data('id');
// Get data
$.ajax({
type: 'GET',
url: 'employeeInfo',
data: {'id':$id},
success: function(data){
var obj=$.parseJSON(data);
// Show output...
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
});
});
}(jQuery));
</script>
Route
Route::get('/employeeInfo', 'EmployeeController#get');
Controller
public function get(Request $request) {
if($request->ajax()) {
$this->validate($request, [
'id' => 'required|integer',
]);
// Id
$employee = Employee::find(request('id'));
// Create output
$data = ...
echo json_encode($data);
}
}
If I were you, I would use a RESTful API with route model binding, specifically the explicit binding.
RouteServiceProvider.php
public function boot()
{
parent::boot();
Route::model('employee', App\Employee::class);
}
Route
Route::get('api/employees/{employee}', 'EmployeeController#get');
Controller
public function get(Employee $employee)
{
// The id being valid is already done by forcing it to be an Employee
// It is also an ajax call because it is going to the api route
// This will json_encode the employee object.
return $employee;
}

Laravel 4.1.* AJAX response method

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);
}
}
}

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);
}
}
}

CakePHP 2.0 Ajax login

I have the following method which allows a user to login into my application:
public function login()
{
if($this->Auth->user())
{
$this->Session->setFlash(__('Already logged in...'), 'default', array(), 'auth');
$this->redirect(array('controller'=>'pages','action'=>'display','home'));
}
if ($this->request->is('ajax'))
{
$this->layout = 'ajax';
if ($this->Auth->login())
{
}
else
{
}
}
else if ($this->request->is('post'))
{
if ($this->Auth->login())
{
return $this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
It allows a user to login either using a post request or via an ajax request. However with regards to the ajax requests how do I pass the results back using JSON? So for example if the user enters the wrong details pass back an error message?
I have the jQuery AJAX already setup so I just need to do some extra logic in the success method to deal with the return which will either show the error message from the server or do a redirect again based on the return from the server.
e.g.
$('form').live('submit', function (event) {
// Declare the form
var form = $(this);
// Stop the form from doing a native postback
event.preventDefault();
// Get the data from the form
var data = form.serialize();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: data,
success: function (responseHtml) {
// If correct login details
if(success){
window.location.href('INSERT LOCATION TO REDIRECT TO FROM SERVER');
} else {
alert('INSERT MESSAGE FROM THE SERVER');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error!');
}
});
});
Can anyone help? I'm using CakePHP 2.0 and all of the tutorials I have seen on the net and on here have either been outdated or much too long-winded for what I'm trying to achieve.
Edit: you need to use the following php code
if ($this->Auth->login())
{
$arr = array("login" => "true" , "redirect" => "/redirect_url");
echo json_encode($arr);
}
else
{
$arr = array("login" => "false" , "error" => "Invalid Login Credentials");
echo json_encode($arr);
}
on the javascript side you need to modify your javascript to handle json values using jQuery.getJSON. example of jQuery.getJSON is availabe here http://api.jquery.com/jQuery.getJSON/
use this jQuery code
<script type="text/javascript">
$.getJSON("login.php", function(data) {
if(data.login)
{
//redirect user with data.redirect
}
else
{
//display error with data.error
}
})
</script>

Categories