AJAX POST Request not working in Laravel 5.6 - php

While trying to use ajax request in my application using Laravel 5.6 I've found that the ajax request is not triggering.
My Controller code
class AjaxController extends Controller
{
function index(Request $request)
{
$msg = "Sample Messgae";
return response()->json(['msg' => $msg)]);
}
}
The Route,
web.php
Route::post('/message','AjaxController#index');
Route::get('/sample','UserRedirectController#ajaxRedirect');
The view
<input type="text" name="ajax" id="ajax">
<input type="text" name="_token" value="{{csrf_token()}}" id="token" hidden>
<button id="save" onclick="ajaxRequestFun();">Show</button>
<span id="cont"></span>
Finally the script
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
});
functon ajaxRequestFun()
{
$.ajax({
type : 'POST',
url : '/message',
data : {'_token': {{csrf_token()}} },
success:function(res){
alert("success");
}
});
}
</script>

Finally found some solution,
I've just added a meta tag to the view head tag just like.
<meta name="token" content="{{csrf_token()}}">
then at the JavaScript side formed the data to send using,
var pass= {'_token':$('meta[name="token"]').attr('content'),
'MessageContent': document.getElementById("message").value,
};
and initiated the ajax call normally with data: parameter as variable pass which I've created,
My ajax code is something like,
$.ajax({
type:'POST',
url:'{{url("/message")}}',
datatype:'json',
data: pass,
success:function(data){
$("#bubble").html(data);
}
}).fail(function(jqXHR, textStatus, error){
alert(jqXHR.responseText);
});
what I've found important is,
Use of the meta tag with the csrf_token() key
what else is as same as that of the other frameworks,

Related

Laravel 7 Route Resource and Jquery POST 301 issue

I'm facing a very weird issue. I'm trying to store photo using Jquery AJAX.
My Route
Route::resource('photo', 'PhotoController');
My Blade Code
<form id="photo_form" enctype="multipart/form-data" onsubmit="return false;">
<input type="file" name="file" id="photo_file" accept="image/gif, image/jpeg, image/png"/>
<input type="submit" class="btn btn-outline-dark" value="Upload and Get Link"/><br/>
</form>
My View AJAX Code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#photo_form").submit(function () {
var formData = new FormData(this);
$.ajax({
url: "{{route('photo.index')}}",
method: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (data) {
console.log(data);
if (data.status) {
}
},
error: function (error) {
alert(error.responseText);
}
});
});
My Controller Code
public function store(Request $request) {
return [true];
}
when ajax call is called, it gives me 2 issue in network tab of firefox
POST https://fb.srdlict.com/photo
301 Moved Permanently
And
403 Forbidden
GET https://fb.srdlict.com/photo/
Seems like the ajax request is forwarded to /photo/ route somehow and then 403 happened. Other routes are working fine. Just only this route. Can anyone help me?

Ajax returns GET request instead of POST

I'm trying to create a personal messaging system in laravel, and apart of this system is being able to send messages in a form without refreshing the entire page.
I've been following some youtube tutorials, and this is the Ajax script I have so far.
<form id="form{{$dm->id}}">
{{ csrf_field() }}
<input id="message" placeholder="Send a message" style="border-radius: 0px;" type="username" class="form-control" name="message">
<script>
$('form{{$dm->id}}').ready(function (){
$('form{{$dm->id}}').on('submit', function( event ) {
event.preventDefault();
$.ajax({
type: 'post',
url: '{{ route("sendMessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
});
});
</script>
</form>
Instead of sending a POST request to the controller, it sends a GET request and just redirects.
This is my first time messing with Ajax/Javascript in general, so I don't know exactly why this isn't working.
Controller script:
public function sendM(Request $request, $id)
{
$validatedData = $request->validate([
'message' => 'required|string|max:255|min:4',
]);
$dm = Dm::find($id);
$mess = new Message;
$mess->Authid = Auth::user()->id;
$mess->Userid = $dm->Userid;
$mess->Dmid = $dm->id;
$mess->message = $request->input('message');
$dm->messages()->save($mess);
$dm->touch();
}
Route entry:
Route::post('/sendmessage/id{id}', 'SettingsController#sendM')->name('sendMessage')->middleware('verified');
Any help is very much appreciated! (Note: Sorry if it is something really obvious)
In the $.ajax call, you need to set the method to post instead of the type.
$.ajax({
method: 'post',
url: '{{ route("sendMessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
As an aside, jquery is often considered to be on the way out. You may want to look into what some alternatives to jquery would look like, such as vue.js or react. Specific to the ajax aspect, Laravel has built in axios support.
Not sure if it solves your problem, but you must also add the csrf token to the headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
(if the token is in a meta tag of course)
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
<form id="form{{$dm->id}}">
{{ csrf_field() }}
<input id="message" placeholder="Send a message" style="border-radius: 0px;" type="username" class="form-control" name="message">
<script>
$('form{{$dm->id}}').ready(function (){
$('form{{$dm->id}}').on('submit', function( event ) {
event.preventDefault();
$.ajax({
type: 'POST', //Check your JQ version.
method: 'POST', //Check your JQ version.
contentType:"multipart/form-data; charset=utf-8",
//url: '{{ route("sendMessage", $dm->id) }}',
url: '{{ route("sendmessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
});
});
</script>
</form>

How to get back ajax request sent to the controller on the view

I have a form
<form id="myForm">
<div class="button dropdown">
<select name="languageSelected" required="required" id="languageselector">
<option value="">Select the language</option>
#foreach($reviewForm_language as $lang)
<option value="{{$lang->id}}">{{$lang->name}}</option>
#endforeach
</select>
</div>
</form>
On selection; it makes a ajax request
<script>
$(function() {
// when select changes
$('#languageselector').on('change', function() {
// create data from form input(s)
let formData = $('#myForm').serialize();
// send data to your endpoint
$.ajax({
url: '/selected/languageId',
method: 'post',
data: formData,
dataType: 'json',
success: function(response) {
console.log(response);
}
});
});
});
</script>
The route
Route::post('/selected/languageId','ProfileController#selectedLangId');
On the controller
public function selectedLangId(Request $request)
{
\Log::info("Was here");
return response()->json(['success'=> $request->languageSelected]);
}
This works well up to this point.
How do I get the $request->languageSelected passed to the controller back on the view? I would like to be assigned as a PHP variable to be used elsewhere.
Anyone?
You're already sending it through
['success'=> $request->languageSelected]
Just need to print it on your success call of blade by
console.log(response.success);
if you'r route registered in web.php you need to whitelist url in VerifyCsrfToken middleware like below
protected $except = [
'url',
];

How to take value from textarea to textarea with Laravel + Jquery Ajax?

How do I take value from one textarea to another with laravel and jquery ajax.
I have this files so far.
Route:
Route::post('/post', 'PostController#post');
Controller:
class PostController extends Controller
{
public function post(Request $request)
{
$request->json()->all();
}
}
JQuery file:
$(function(){
$('#insert').on('click', function(e){
e.preventDefault();
var intrare = $('textarea#firsttextarea').val();
$.ajax({
type:'POST',
url: '/post',
data: {intrare: intrare},
success: function(data){
$('textarea#secondtextarea').val(data);
}
});
});
});
and the html :
<textarea class="form-control" name="firsttextarea" rows="10" id="firsttextarea" ></textarea>
<button id="insert" class="btn btn-md btn-primary"><span class="glyphicon glyphicon-circle-arrow-right"></span>Insert</button>
<textarea class="form-control" name="secondtextarea" rows="10" id="secondtextarea" ></textarea>
When i push the button nothing happens.
First problem probably can be in CSRF Verify. You can disable it if it so or add {{ csrf_token() }}.
Then your post action should be looks like this:
public function post(Request $request)
{
return response()->json($request->all());
}
I checked it and it's work fine. but in textarea insert [Object object] because it JSON. You can add JSON.stringify in your Jquery script like this:
$(function(){
$('#insert').on('click', function(e){
e.preventDefault();
var intrare = $('textarea#firsttextarea').val();
$.ajax({
type:'POST',
url: '/post',
data: {intrare: intrare},
success: function(data){
$('textarea#secondtextarea').val(JSON.stringify(data));
}
});
});
});
Try this, you're not returning a response in your Controller method.
class PostController extends Controller
{
public function post(Request $request)
{
return response()->json([
'data' => $request->get('intrare'),
]);
}
}
then, add this to your head in your blade file
<meta name="csrf-token" content="{{ csrf_token() }}">
and replace your JS with the below:
$(function() {
// We need CSRF Token in our ajax request so we can
// validate the POST request
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
}
});
// Insert text from first textarea to the other textarea
$("#insert").on("click", function(e) {
e.preventDefault();
var intrare = $("textarea#firsttextarea").val();
$.ajax({
type: "POST",
url: "/post",
data: { intrare: intrare },
success: function(response) {
$("textarea#secondtextarea").val(response.data);
}
});
});
});

CodeIgniter and AJAX form submit

I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.
Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.
My problem is the form won't submit with e.preventDefault(); in place, but without it the form does the normal method of posting to the db then refreshing the page.
Here is my AJAX call:
$(document).ready(function() {
$('form#feedInput').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $('.feed-input').val(),
dataType: "html",
success: function(data){
debugger;
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
});
I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault(); function.
How can I get this form to submit via AJAX if the e.preventDefault() function is stopping it before it can reach the $.ajax() function?
The data attribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() } or in query format 'key='+$('.feed-input').val().
Also there is an unnecessary debugger variable in the success method.
A working code could be:
$('form#feedInput').submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function(data){
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
Html part in view
<form id="comment" method="post">
<h2>Enter Your Details</h2>
<center><div id="result"></div></center>
<div class="form_fld">
<label>Name</label>
<input type="text" placeholder="Enter Your Full Name" name="name" required="">
</div>
<div class="form_fld">
<label>Email ID</label>
<input type="text" placeholder="Enter Email ID" name="email" required="">
</div>
<div class="form_fld">
<label>Contact Number</label>
<input type="text" placeholder="Enter Contact Number" name="contact" required="">
</div>
<div class="form_fld">
<label>Developer</label>
<select name="developer">
<option>Lotus</option>
<option>Ekta</option>
<option>Proviso</option>
<option>Dosti</option>
<option>All</option>
</select>
</div>
<div class="form_fld">
<button type="submit" id="send">Submit</button>
</div>
</form>
After Html Part Just put ajax request
<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "home/contact",
data: dataString,
success: function(data){
// alert('Successful!');
$("#result").html('Successfully updated record!');
$("#result").addClass("alert alert-success");
}
});
return false; //stop the actual form post !important!
});
});
</script>
Within Controller
public function contact()
{
$ip = $_SERVER['REMOTE_ADDR'];
$data = array('name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'number' => $this->input->post('contact'),
'developer' => $this->input->post('developer'),
'ip' => $ip,
'date' => date("d/m/Y"));
$result = $this->User_model->contact($data);
print_r($result);
}
You don't have to use preventDefault(); you can use return false; in the end of function submit() but I doubt this is the problem.
You should also use url encoding on $('.feed-input').val() use encodeURIComponent for this.
You should also check if you have errors in your console.
To determine if default action is prevented you can use e.isDefaultPrevented(). By default action in this case I mean submit action of the form with id feedInput.
You didn't name your param in data. Check jquery ajax examples.
You are probably getting an error e.preventDefault(); is not stopping the ajax.
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $("#form").serializeArray(),
success: function(resp){
$('#container').html(resp);
},
error: function(resp) { alert(JSON.stringify(resp)); }
});

Categories