Laravel 4.2 AJAX post giving me 404 error - laravel

I'm still using Laravel 4.2 and I'm trying to post a form with AJAX, but it gives me error 404 for a post page. Here is my code:
routes.php:
Route::post('/', array(
'as' => 'postFora',
'uses' => 'HomeController#postFora'
));
HomeController.php:
public function postFora() {
$form = Input::all();
$f = New Fora;
$f->content = Input::get('contant');
$f->user_id = Input::get('user_id');
$f->save();
return Response::json(array('success' => true));
}
main.js:
$('.dodaj-foro').submit(function(e) {
var form = $(this);
$.ajax({
url : "http://localhost/belezka/",
type: "POST",
dataType: "JSON",
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
e.preventDefault();
});
index:
<form class="dodaj-foro" action="/" method="post" accept-charset="utf-8">
<input type="hidden" name="user_id" value="{{$user[0]->id}}">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<input type="text" name="contant" placeholder="Fora tuki">
</form>

I think you have to enter the route in present in Route file instead of http://localhost/belezka/
Try to replace :
$.ajax({
url : "http://localhost/belezka/",
type: "POST",
dataType: "JSON",
.....
By :
$.ajax({
url : "postFora",
type: "POST",
dataType: "JSON",
.....
Hope this will help.

In case you did not change the defaults Laravel comes with, add public to the AJAX request URL. By default, the route '/' corresponds to http://localhost/belezka/public/ due to URL rewriting.

Related

Passing muliple options to controller in laravel

I'm trying to send multiple selected options to my controller but i can't
Code
route
Route::post('/spacssendto/{id}', 'ProductController#spacssendto')->name('spacssendto');
ajax
$("body").on("click", ".sendspacsdatato", function(e){
e.preventDefault();
var id = $("#product_id").val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'subspecification_id': $('.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
controller
public function spacssendto(Request $request, $id) {
dd($request->all());
}
my form (output)
<form method="POST" action="http://sieffgsa.pp/admin/products/15" accept-charset="UTF-8">
<input name="_token" value="DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16" type="hidden">
<input name="product_id" id="product_id" value="15" type="hidden">
<div class="col-md-4">ram</div>
<div class="col-md-6">
<select class="subspecifications form-control tagsselector" id="subspecifications" name="subspecifications[]" multiple="multiple">
<option value="3">2gig</option>
<option value="4">4gig</option>
</select>
</div>
<div class="col-md-2">
<label for="">Actions</label><br>
<button type="button" id="sendspacsdatato" class=" sendspacsdatato btn btn-xs btn-success">Save</button>
</div>
</form>
PS: This form printed by Ajax in my view so it means there is several
more forms involved (the same way) that's why i mostly used classes
and not id's. Yet when I hit save button I will get 3 times repeat in
network (if i have 3 form)
Errors
Error 500 in network
dd result:
array:3 [
"_token" => "DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16"
"product_id" => "15"
"subspecification_id" => null
]
Question
How can I pass my multiple options (selected) to controller?
UPDATE
Thanks to Seva Kalashnikov I fixed the problem just for helping others I'll publish final results here so you can have full code, hope it helps.
javascript
$(document).ready(function() {
$("body").on("click", ".sendspacsdatato", function(e){
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
// e.preventDefault();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}',
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'subspecifications': $(this).closest('form').find('select.subspecifications').val()
},
success: function (data) {
alert('Specifications added successfully.').fadeIn().delay(6000).fadeOut();
},
error: function (data) {
console.log('Error!');
}
});
});
});
controller
public function spacssendto(Request $request) {
$this->validate($request, array(
'product_id' => 'required',
'subspecifications' => 'required',
));
$product = Product::find($request->product_id);
$product->subspecifications()->sync($request->subspecifications, false);
}
You need to get select with css class subspecifications inside the same form element
'subspecification_id': $(this).closest('form').find('select.subspecifications').val()
Try this code:
$('.sendspacsdatato').click(function() {
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': form.find('input[name=_token]').val(),
'product_id': id,
'subspecification_id': form.find('select.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});

Joomla sending Data (special Image) with Ajax (Formdata)

Using Joomla:
My problem is when I submit the button, ajax send an empty data array back to my client. Debbuging in the console shows me that datas in the header but the preview and response values are empty.
Here is my code (I am using a modal form from bootstrap).
HTML in my default script:
<form action="<?php echo JRoute::_('index.php?option=com_addproduct&view=addproducts'); ?>" method="post" name="modalMessageForm" id="modalMessageForm" enctype="multipart/form-data">
<input type="file" id="message-image-upload" accept="image/*" style="display:none;" name="message-image-upload">
<textarea class="form-control message-textarea" id="message-textarea" placeholder="Nachricht..." name="new-message" rows="4"></textarea>
<button type="button" id="button-close-message" class="btn btn-default btn-block btn-message-close" style="display:none; margin-top:5px;"><?=JText::_( 'COM_ADDPRODUCT_MODAL_MESSAGES_CLOSE')?></button>
</form>
JQuery / Ajax:
$(document).on("submit", "#modalMessageForm", function(e)
{
var form = $('#modalMessageForm').get(0);
e.preventDefault();
var formData = new FormData(form);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
$.ajax({
crossDomain: true,
type: "POST",
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
data: formData,
dataType: "json",
processData: false
})
.done(function(data, textStatus, jqXHR){
console.log('Message: '+data.new-message+' PicName: '+data.img);
})
});
Here my controller.php:
public function sendMessages()
{
JResponse::setHeader('Content-Type', 'application/json', true);
$app = JFactory::getApplication();
$input = $app->input;
$new-message = $input->getString('new-message', '', 'RAW');
$img = $_FILES['message-image-upload']["name"];
$img = JFile::makeSafe($img);
$results=array(
'new-message' => 'new-message',
'img' => $img
);
echo json_encode($results);
$app->close();
}
I got the datas / variables in the console log.
it is:
new-message: null,
img: null
trying to set contentType: false will give me an 500 error.
Thank you very much
That´s the info from my network
enter image description here
I figure something out.
It´s the URL in my ajax command.
When I am using a normal url like
url: 'upload.php'
that will work and then I can set the
contentType: false,
But this is not safety enought.
I just want to use this url
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
But then I got the error message that the view is not found. That´s very strange.

File Data is blank array in server side: Laravel 5.3

I am trying to post File using JQuery. Below is my code.
<script language="javascript">
$(document).ready(function() {
$('#frmUpdateProfile').on("submit", function(event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data = {
"FileName" : event.target.FileName.files,
"_token" : "{!! csrf_token() !!}"
};
$.ajax({
url: '{{URL::route("UpdateProfile")}}',
method: "POST",
async: true,
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8",
success: function (msg) {
SuccessCallback(msg);
},
error: function (jqXHR) {
ErrorCallback(jqXHR);
}
});
});
});
</script>
I tried processData: false,. While debugging in Js, you can check that image is coming in the data. Below is the screenshot.
But when I print the request data in Laravel, it show blank array.
Html form is here
<form method="POST"
action="http://localhost:1234/AS6-Code/public/UpdateProfile"
accept-charset="UTF-8"
enctype="multipart/form-data"
id="frmUpdateProfile">
<input name="_token" type="hidden" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input type="hidden" name="_token" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input multiple="1" name="FileName" type="file">
<input class="btn btn-info" type="submit" value="Update">
</form>
Am I doing something wrong?
Try sending your request with FormData instead:
var data = new FormData($('#frmUpdateProfile')[0]);
Also set contentType to false:
contentType: false
Also Update
event.target.FileName.files
to
event.target.FileName.files[0]
event.target.FileName.files is a FileList object. I believe you need event.target.FileName.files[0] instead.

token mismatching ajax in Laravel

$('#id').change(function(){
var a = $('#id_one').val();
var token = '<?php echo csrf_token(); ?>';
$.ajax({
url: "url",
type: 'POST',
data: {'id':a,'_token':token},
success: function(data)
{
// some code
}
});
})
This is my code.
Getting token mismatch error..!!
I have tried both of the following..
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<script type="text/javascript">
var _globalObj = {{ json_encode(array('_token'=> csrf_token())) }}
Can any one help ??
You can utilize your token from the blade template, just declare your session token in the blade file of your view under the script tag like this:
<script> var token = '{{ Session::token() }}'; </script>
and call the token in ajax, in your code it will be something like this:
$('#id').change(function(){
var a = $('#id_one').val();
$.ajax({
url: "url",
type: 'POST',
data: {'id':a,'_token':token},
success: function(data)
{
// some code
}
});
})
Possibly because the token field name should be _token and not token
Also If this javascript code in a separate javascript file then php function will not work.
Also if the data you are trying to send is of a form then you can do this
$('#id').change(function(){
var data = $("#form").serialize() ;
$.ajax({
url: "url",
type: 'POST',
data: data,
success: function(data)
{
// some code
}
});
})
where your form looks like
<form id="form">
<input type='hidden' value='{{ csrf_token() }}' name='_token'>
<input type="text" name='id'>
</form>
$.ajax({
url: someurl,
type: 'POST',
data : formData,
headers: {
"x-csrf-token": $("#token").data('id')
}
});
}
and in your html
<div id="token" data-id="{!! csrf_token() !!}"></div>

Sending AJAX request before submitting the form

Problem: I'm trying to send ajax reguest, and then submit the form.
Aproaches:
1. I solved the problem by putting
success: function() {
document.myform.submit();
}
But i think it's not the most elegant solution. Can you explain me why it works only if i put document.myform.submit(); in success? Is there any other way to solve this problem?
<div class="buttons">
<div class="right">
<form name="myform" onsubmit="javascript: startAjax(); return false;" action="https://example.com/payment.php" method="get">
<input type="hidden" name="merchantId" value="<?php echo $merchantIdKZM; ?>">
<input type="submit" value="<?php echo $button_confirm; ?>" id="button-confirm2" class="button" name="PayKZM" />
</form>
</div>
</div>
<script type="text/javascript">
function startAjax() {
console.log("dafaaaa");
$.ajax({
type: 'get',
url: 'index.php?route=payment/bank_transfer/confirm',
async: 'false',
success: function() {
// location = '<?php echo $continue; ?>';
}
});
} // Calls ajaxComplete() when finished
function ajaxComplete()
{
console.log("dafa");
document.myform.submit();
}
</script>
success's function is called upon the get request receiving a valid response as #harsh pointed out. Thus it will occur after the get request. I believe something similar to the following would do as you request though I haven't tested it:
<script type="text/javascript">
$(function () {
$("#form").on('submit', function () {
var $form = $(this);
$.ajax({
type: 'GET',
url: 'index.php?route=payment/bank_transfer/confirm',
data: $form.serialize(),
async: 'false',
success: function () {
$.ajax({
type: 'GET',
url: 'https://example.com/payment.php',
data: $form.serialize(),
});
}
});
});
});
</script>

Resources