Not getting post data in controller from ajax - laravel

I am posting my form data to A controller but when I post data I am not getting in the controller when I call print_r($_POST); its returning null array I don't know what I have missed
Please let me know what inputs you want from my side
var data2 = [];
data2['user_firstname'] = user_firstname;
data2['user_lastname'] = user_lastname;
data2['user_phone'] = user_phone;
data2['user_email'] = user_email;
data2['user_username'] = user_username;
data2['user_password'] = user_password;
console.log(data2);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "http://localhost/shago/register/submit",
data: { 'data2': data2 },
// dataType: "text",
success: function(resultData) { console.log(resultData); }
});
controller code
public function submit()
{
print_r($_POST);
}

You can use the following
public function submit(Request $request)
{
dump($request);
}

Try adding Request as parameter on your submit function
public function submit(Request $request)
{
print_r($request);
}
Also, do you really need to pass your information as an array?
You could just create a new object and pass that as well.
var data2={
'user_firstname': user_firstname,
'user_lastname': user_lastname,
'user_phone': user_phone,
'user_email': user_email,
'user_username': user_username,
'user_password': user_password
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "http://localhost/shago/register/submit",
data: data2,
success: function(resultData) { console.log(resultData); }
});

You need to inject Request Class injection into submit method. This can help you:
public function submit(\Illuminate\Http\Request $request)
{
dd($request->all()); // will print all data
}
of if you don't want to inject Request then this code may helps you
public function submit()
{
dd(request()->all()); // will print all data
}
Good Luck !!!

Maybe the request was intercepted by Laravel CSRF Protection policy.In order to prove it, you should add request URL in VerifyCsrfToken middleware file, like following:
protected $except = [
'yoururl'
];
If you can get the data you expect in your controller, then I am right.

Thanks all i found error in when i am sending array data now i have modified code and its working fine
see code
$.ajax({
url: "register/submit",
type: "post",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {'user_firstname':user_firstname,'user_lastname':user_lastname,'user_phone':user_phone,'user_email':user_email,'user_username':user_username,'user_password':user_password},
success: function(result){
console.log(result);
}
});
}

Related

Passing ID to Controller using Ajax - Error 404 in Laravel

I am new to Laravel.
Trying to Pass ID from View to Controller but getting Error
POST http://127.0.0.1:8000/getbuffaloidformonitor 404 (Not Found)
This is my View BuffaloMonitor :
$(document).on('click', '.viewmonitormodal', function() {
var modal_data = $(this).data('info').split(',');
$('#viewbuffaloID').val(modal_data[1]);
var buffaloid = document.getElementById('viewbuffaloID').value// get buffalo id from textbox to get data for that ID
alert(buffaloid);
//alert(data);
$(function() {
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor",
data: {
'_token': $('input[name=_token]').val(),
'id': buffaloid,
},
success : function(response) {
alert(response);
}
});
});
}
This is BuffalomonitorCOntroller :
public function getbuffaloidformonitor(Request $req) {
$data = buffalodata::find($req->id);
alert(data);
$id = $req('data');
return $id;
}
This Is Route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
Your post route has {id} but it's not necessary. This is what you need Route::post('/getbuffaloidformonitor','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
pass id to the link http://127.0.0.1:8000/getbuffaloidformonitor
as you write the route
Route::post('/getbuffaloidformonitor/{id}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
You are just pass id by routes Params, so the URL must like this
http://127.0.0.1:8000/getbuffaloidformonitor/yourbuffaloid
You need to change URL.
$.ajax({
method : "POST",
url: "/getbuffaloidformonitor/" + buffaloid,
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If you use this script in you blade template just use
const url = '{{ route("getbuffaloidformonitor",":id") }}'
$.ajax({
method : "POST",
url: url.replace(':id',buffaloid),
data: {
'_token': $('input[name=_token]').val(),
//'id': buffaloid, remove this line
},
success : function(response) {
alert(response);
}
});
If your routes {id} is optional just
Route::post('/getbuffaloidformonitor/{id?}','App\Http\Controllers\BuffalomonitorController#getbuffaloidformonitor')->name('getbuffaloidformonitor');
with question on your id route you can use both by pass id by route params or you can pass id by data post.
In controller
public function getbuffaloidformonitor(Request $req, $id = null)
{
// id is get from route params
$getId = $req->get('id') // this one get from data post.
}

Make ajax call dependent on another ajax call

I would to avoid nesting a bunch of ajax calls inside the 'success' event of one another. I was wondering if someone could guide me in the right direction on how to do something like this? Where one ajax call is dependent on another's return value?
The getLoginAccess() function will be used in many other methods in a similar manner.
If the first one fails i would like to just have it return a 'null' value which i can then take into account before running the second ajax call. Below i demonstrate a psuedo example of what im trying to do.
The method getLoginAccess returns a dictionary of data that is required for the second method createItem to execute. So only if getLoginAccess returns valid data will createItem continue on to call the actual ajax call.
Thank you
function getLoginAccess() {
$.ajax({
url: '.../api/v1/auth/access_token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Connection': 'keep-alive'
},
data: {
grant_type: 'client_credentials',
username: 'johnDoe',
password: '******'
},
success: function (data) {
console.log(JSON.stringify(data));
return data;
},
error: function (data) {
console.log(data);
return null;
}
})
}
function createItem() {
var login = getLoginAccess();
if (login == null) {
return false;
}
$.ajax({
url: '.../api/v1',
method: 'POST',
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'access': `${login.access_token}`
};
data: {},
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (data) {
console.log(data);
}
})
}
window.onload = function(){
createItem();
};
If you want to refactor the part where the login is verified we could create an intermediate function .. something like this:
Your login function here
function getLoginAccess(){
// Return login data or null
}
Here we can create an intermediate function to deal with the dependencies of the next execution. If the login returns something other than null, the function passed as a parameter will be executed.
function intermediateFunction(functionName,login){
if(login){
window[functionName]();
}
}
Here are the other functions you have created.
function createItem() {
// Do something
}
function listItem() {
// Do something
}
Here instead of calling the createItem() function you call the intermediary
window.onload = function(){
intermediateFunction(getLoginAccess(), "createItem");
};
So basically you would always call the intermediate function that would check the login before calling a particular function. I believe that this is how I would refactor :)

why is codeigniters raw_input_stream null?

I was wondering why is the raw_input_stream returning null. Here is my ajax call that I do from UI5.
$.ajax({
url: "/CI/controllername/functionname",
type: "POST",
data: JSON.stringify(oParameters),
contentType: "application/json",
success: function (data) {
MessageToast.show(data);
},
error: function (e) {
MessageToast.show(e.status);
}
});
Here is my controller
class controllername extends CI_Controller
{
public function functionname()
{
echo $this->input->raw_input_stream;
if ($this->input->raw_input_stream == null) echo "null";
}
}
When I run this code raw_input_stream is null. Not sure why. I check the request payload on chrome developer tools and the data is send. Here is request payload.
Try using Following:
parse_str(urldecode($this->input->raw_input_stream), $output);
$data = $output;
This may help.

laravel ajax pass multiple variables to controller?

I need to pass 4 variables to controller so that I can do what I want to do with it, however I get an error:
Missing argument 1 for
App\Http\Controllers\ProfileController::getGoogle()
Here's my Controller:
function getGoogle($lat, $lng, $destinationLat, $destinationLng) {
print_r($lat);
print_r($lng);
print_r($destinationLat);
print_r($destinationLng);
}
and ajax:
function getDirections(lat, lng, destinationLat, destinationLng) {
$.ajax({
url: '/google/',
type: 'post',
data: {
lat: lat,
lng: lng,
destinationLat: destinationLat,
destinationLng: destinationLng
},
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
Route:
Route::post('google/', 'ProfileController#getGoogle');
You are actually sending POST variables to the controller, but you are accepting them in controller as GET variables,if you want to read the variables, your controller should be like this:
function getGoogle(Request $request) {
print_r($request->input('lat'));
print_r($request->input('lng'));
print_r($request->input('destinationLat'));
print_r($request->input('destinationLng'));
}
Remember to import Request as use Illuminate\Http\Request;
You aren't passing any parameter via the url and is passing via ajax POST params so you need to change your controller method definition to
function getGoogle() {
print_r(Input::get('lat'));
print_r(Input::get('lng'));
print_r(Input::get('destinationLat'));
print_r(Input::get('destinationLng'));
}

Render partial view with AJAX-call to MVC-action

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

Resources