Posting a Laravel AJAX request passes 0 arguments - php

I'm having trouble passing arguments through a Laravel AJAX request. There are a lot of similar questions asked, but none of them seem to address the problem I have.
Here is are my Laravel routes:
Route::get('workerAjax', function(){
return View::make('workerAjax');
});
Route::post('/workerAjax/post', 'WorkerController#storeWorker');
WorkerController.php
<?php
class WorkerController extends \BaseController {
public function storeWorker(Request $request){
return 'I am in';
}
}
workerAjax.blade.php
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="_token" content="{{ csrf_token() }}" />
<title>Register worker</title>
</head>
<body>
<div class="container">
<div class="alert alert-success" style="display:none"></div>
<form id="myForm">
<!-- don't think I need this, but it doesn't work with or without -->
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="text" id="firstName">
</div>
<div class="form-group">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" id="email">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password">
</div>
<button class="btn btn-primary" id='ajaxSubmit'>Submit</button>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
jQuery(document).ready(function(){
jQuery('#ajaxSubmit').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/workerAjax/post') }}",
method: 'post',
data: {
firstName: jQuery('#firstName').val(),
lastName: jQuery('#lastName').val(),
email: jQuery('#email').val(),
password: jQuery('#password').val(),
},
success: function(result){
jQuery('.alert').show();
jQuery('.alert').html(result.success);
}});
});
});
</script>
</body>
</html>
</html>
After filling in the form in a browser and clicking submit, I get a POST error 500 in the console.
The preview of the network error shows this message
error: {type: "Symfony\Component\Debug\Exception\FatalThrowableError",…}
file: "/path/to/folder/app/controllers/WorkerController.php"
line: 64 ( public function storeWorker(Request $request){ )
message: "Type error: Too few arguments to function WorkerController::storeWorker(), 0 passed and exactly 1 expected"
type: "Symfony\Component\Debug\Exception\FatalThrowableError"
I feel like I've done everything right, yet it's still not working. Could someone more experienced with the framework please give me a hand?
Edit:
Here is data which is sent through the request:
XHR Request
Edit 2:
My folder structure may be a piece of the puzzle, here it is:
App folder structure

Change method key to type in ajax object.
<script>
jQuery(document).ready(function(){
jQuery('#ajaxSubmit').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/workerAjax/post') }}",
type: 'POST',
data: {
firstName: jQuery('#firstName').val(),
lastName: jQuery('#lastName').val(),
email: jQuery('#email').val(),
password: jQuery('#password').val(),
},
success: function(result){
jQuery('.alert').show();
jQuery('.alert').html(result.success);
}});
});
});
</script>

You are missing to import the request class after the namespace declaration:
use Illuminate\Http\Request;
Without it, Laravel don't know how to inject that parameters, and don't inject anything.

So using the command ssh php artisan -V, I found out I've been using Laravel 4.2 rather than Laravel 6.15 as my plesk installation lead me to believe.
I solved this problem by calling the controller function from the route directly:
Route::post('/workerAjax/{post}', function(){
return WorkerController::storeWorker(Input::all());
});
and WorkerController.php
<?php
class WorkerController extends \BaseController {
public function storeWorker($request){
$val = json_encode($request);
// use for accessing json variables
$firstName = $request['firstName'];
// alert.(result.success) returns:
// {"firstName":"John","lastName":"Doe","email":"johndoe#email.com","password":"password1"}
return Response::json(['success'=>$val],200);
}
?>
Thanks for everyone's input and I hope this helps someone in the future!

Related

How to submit a blade.php form with AJAX

How should I handle the csrf_field() function when doing this with AJAX?
here is a link to the project repo.
Here is a link to the article which helped me write the code.
I'm pretty sure I don't have to make too many changes to the code to handle the forms with AJAX instead of regular blade.php form submissions, but I'm unsure of the implementation
<form id="add_item" method="POST" action="/item">
<div class="form-group">
<textarea name="item_name" placeholder='Enter your item'></textarea>
#if ($errors->has('item_name'))
<span class="text-danger">{{ $errors->first('item_name') }}</span>
#endif
</div>
<div class="form-group">
<button type="submit" >Add Item</button>
</div>
{{ csrf_field() }}
</form>
you can also put csrf-token in header file like this...
<meta name="csrf-token" content="{{ csrf_token() }}">
then give one unique id to submit button... then after in JavaScript detect that click event. then after call ajax on click event of submit button
$.ajax({
type: "POST",
// url: "{{ route('admin.users')}}" + id,
// url : '/admin/users/',
url: "{{url('admin/users/')}}", // you can pass url using url() OR as simple url OR Route name also
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') //get the Csrf token from header
},
data: { id: id, }, //pass here all data which you want to pass to controller
success: function (data) {
console.log(data);
}
});
get the csrf value using
var token = $('input[name="csrfToken"]').attr('value');
and append it to the header
$.ajax({
url: route.url,
data : JSON.stringify(data),
method : 'POST',
headers: {
'X-CSRF-Token': token
},
success: function (data) { ... },
error: function (data) { ... }
});
you can read more about it here https://stackoverflow.com/a/51964045/9890762
SOLVED.
I had to remove the 'type' attribute from the form as ajax is being used instead,
and ensure the ajax functions are at /public/js/file.js
Then, to make the changes available to the folder resources
npm run dev
<form id="add_item_form" action="/item">
<div class="form-group">
<textarea id="add_item_name" placeholder='Enter your item'></textarea>
#if ($errors->has('item_name'))
<span class="text-danger">{{ $errors->first('item_name') }}</span>
#endif
</div>
<div class="form-group">
<button id="ajaxSubmit_add">Add Item</button>
</div>
</form>

Validate if value in input field is an Instagram URL in blade.php

I am using blade.php in my development, and I have a concern in validating if the input is a valid instagram url. I have tried doing this:
<form class="search_form" id="apply" action=" method="post">
#csrf
<label>
<input type="url" pattern="https?://.+" required id="instagram" value="" placeholder="Instagram Post URL (Paste Here)">
</label>
<div class="flex_box">
<button class="btn pink applyfnsh_btn" type="button" id="save">Confirm</button>
</div>
</form>
UPDATE this modal is displayed after validation
<div class="applyfnsh_modal">
<div class="applyfnsh_box">
<div class="modal_close">
<img src="../../assets/images/close.png" alt="close">
</div>
<p>Success</p>
</div>
</div>
modal.js
$(".applyfnsh_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$(".applyfnsh_modal").toggleClass("open");
});
$(".applyfnsh_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.applyfnsh_box').length) {
$(".applyfnsh_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
location is here
<script src="{{ url('/assets/js/modal.js') }}"></script>
And by the way, I'm using ajax in saving data to db so that page is not refreshed.
<script>
$(document).on("click", "#save", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "post",
url: '/contest/apply/{{ $contest->id }}',
data: {url : $("#instagram").val(), user_id: 1, contest_id: {{ $contest->id }} },
success: function(store) {
},
error: function() {
}
});
});
</script>
This isn't working and even processes the data when the button is clicked even if the input is not a url or empty.
Is there a way to do it without making a function?
here it is :
$(document).on("click", "#save", function() {
var instagramLink = $('#instagramLink').val();
var pattern = new RegExp('https://www.instagram.com/p/(.+?)', 'g');
if((instagramLink != undefined || instagramLink != '') && instagramLink.match(pattern)){
alert(instagramLink + 'is valid');
/*
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
url: '/contest/apply/{{ $contest->id }}',
data: {url :instagramLink, user_id: 1, contest_id: {{ $contest->id }} },
success: function(store) {
},
error: function() {
}
});
*/
}else{
alert('Please Enter Valid Instagram Link');
$('#instagramLink').val('');
// show modal
$('.applyfnsh_modal').modal('open');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<form class="search_form" id="apply" action="" method="post">
<label>
<input type="url" required id="instagramLink" value="" placeholder="Instagram Post URL (Paste Here)" class="form-control"/>
</label>
<div class="flex_box">
<button class="btn btn-primary" type="button" id="save">Confirm</button>
</div>
</form>
</body>
</html>
update-2 : remove your existing scripts :
$(".applyfnsh_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$(".applyfnsh_modal").toggleClass("open");
});
$(".applyfnsh_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.applyfnsh_box').length) {
$(".applyfnsh_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
display modal using this way when it is required to display :
to OPEN MODAL : $('.applyfnsh_modal').addClass('open');
to CLOSE MODAL : $('.applyfnsh_modal').removeClass('open');
so
if (validation successfull){
// submit form using AJAX
}else{
$('.applyfnsh_modal').addClass('open');
}
also create one function to close modal :
$(document).on('click','.modal_close',function(){
$('.applyfnsh_modal').removeClass('open');
});

laravel api ajax form wont submit

This is my first api project. Can you help me with my code please?
I can't see the problem.
Here is my controller.
public function store(Request $request)
{
//
$valid=Validator::make($request->all(),[
'text'=>'required',
'body'=>'required'
]);
if($valid->fails()){
return response()->json(['message'=>$valid->messages()]);
}else{
$item= Item::create([
'text'=>$request->input('text'),
'body'=>$request->input('body')
]);
return response()->json($item);
}
}
and here is my form.Is there anything wrong in the form?
<form id="form">
<div class="form-group">
<label>Text :</label>
<input type="text" id="text" class="form-control col-sm-4">
</div>
<div class="form-group">
<label>Body :</label>
<textarea id="body" class="form-control col-sm-4"></textarea>
</div>
<div class="form-action">
<input type="submit" class="btn btn-primary" value="submit">
</div>
</form>
and the ajax code between the show function is working but I don't know where the problem is ?.
$('#form').on('submit', function (e) {
e.preventDefault();//prevent the form to submit to file
let text = $('#text').val();
let body = $('#body').val();
addItems(text, body);
});
function addItems(text, body) {
var item = {
text: text,
body: body
};
$.ajax({
method: 'POST',
url: 'http://localhost:8000/api/items',
data: item,
success: function (item) {
alert('done the item number' + item.id + ' has been added!!');
location.reload();
},
error: function () {
alert('error')
}
})
}
Thanks for helping!
if your front-end source separated from back-end source, then add cross-Origin Resource Sharing
package to your laravel project.
if its on your laravel view then add csrf token to meta tag -
<meta name="csrf-token" content="{{ csrf_token() }}">
and send it with your ajax request { _token : document.querySelector('meta[name="csrf-token"]').content}
The problem is that you're sending the form without sending the cross site request forgery token.
Add the directive #csrf to your view
Then send it has Hasan wrote ;)

Internal Server error during file uploading in laravel5.3

I am trying to upload a file in laravel.But every time i hit the submit button it gives me the internal server error in the console. I have checked the rote with a get request to check if the controller function is working properly and it works fine. Can any say what is the problem?
here is my code samples
route code
Route::post('/storefile','PublicationController#storeFile');
controller
public function storeFile(Request $request){
if($request->ajax()){
echo "got";
}
else echo "not ajax";
}
view
#extends('layouts.app')
#section('stylesheet')
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link type="text/css" href="/css/bootstrap-tagging.css" rel="stylesheet">
#endsection
#section('content')
<div class="validation-system">
<div class="validation-form">
<form id="test-form" action="/storepublication" method="post" enctype="multipart/form-data" >
{!! csrf_field() !!}
<div class="col-md-3 form-group1">
<label class="control-label">Upload Paper</label>
<input type="file" name="file" id="paper">
</div>
<div class="col-md-3 form-group1">
<input type="submit" id="submit" name="submit" class="btn btn-primary" value="Add">
</div>
</form>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function() {
$("#test-form").submit(function (event) {
event.preventDefault();
var file_data = $('#paper').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "/storefile",
type: "post",
data: form_data,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
});
});
</script>
#endsection
Try to replace this
var file_data = $('#paper').prop('files')[0];
by this
var file_data = $('#paper').files[0];

Ajax Request on jQuery Mobile using with Codeginiter

Currently Im trying to do ajax request using jQuery Mobile. I`m trying to use example on http://www.giantflyingsaucer.com/blog/?p=2574. Yes, it works perfectly. But problems was coming when i tried to use the code inside codeigniter.
Here is my controller :
<?php
class Ajax extends CI_Controller {
function __construct() {
}
function index() {
?>
<!DOCTYPE html>
<html>
<head>
<title>Submit a form via AJAX</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.css" />
<script src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.js"></script>
</head>
<body>
<script>
function onSuccess(data, status)
{
data = $.trim(data);
$("#notification").text(data);
}
function onError(data, status)
{
// handle an error
}
$(document).ready(function() {
$("#submit").click(function(){
var formData = $("#callAjaxForm").serialize();
$.ajax({
type: "POST",
url: "callajax",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
});
</script>
<!-- call ajax page -->
<div data-role="page" id="callAjaxPage">
<div data-role="header">
<h1>Call Ajax</h1>
</div>
<div data-role="content">
<form id="callAjaxForm">
<div data-role="fieldcontain">
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName" value="" />
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" value="" />
<h3 id="notification"></h3>
<button data-theme="b" id="submit" type="submit">Submit</button>
</div>
</form>
</div>
<div data-role="footer">
<h1>GiantFlyingSaucer</h1>
</div>
</div>
</body>
</html>
<?php
}
function callajax() {
echo "ok";
}
}
I want to display 'ok' in notification. Im trying to call function callajax instead of call from callajax.php is this possible or do I need to create callajax.php?
Ive tried to create callajax.php but it was failed.
Thank you,
You probably want the url to be:
url: "ajax/callajax",
As you are calling the callajax function within the controller ajax.

Categories