Laravel AJAX image upload - php

Trying to get AJAX image upload working on Laravel 4 but having issues.
This is what I have:
The form:
{{ Form::open(array('class' => 'update-insertimage-form', "files" => true,)) }}
{{ Form::file('image', array('class' => 'update-insertimage-btn', 'name' => 'update-insertimage-btn')) }}
{{ Form::close() }}
And the PHP:
$createImage = Image::make(Input::file('update-insertimage-btn'))->orientate();
$createImage->resize(600, null, function ($constraint) {
$constraint->aspectRatio();
});
$createImage->save("user_uploads/cover_images/TEST.jpeg");
jQuery:
$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
$.ajax({
url: rootAsset+'saveUploadedImage',
type: 'post',
cache: false,
dataType: 'json',
data: $('.update-insertimage-form').serialize(),
beforeSend: function() {
},
success: function(data) {
if(data.errors) {
$('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
} else if (data.success) {
$(".form-control-addupdate").append(data.name);
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
I use this same exact code else where which works fine but not with AJAX.
The error is this:
{"error":{"type":"Intervention\\Image\\Exception\\NotReadableException","message":"Image source not readable","file":"\/Applications\/MAMP\/htdocs\/buildsanctuary\/vendor\/intervention\/image\/src\/Intervention\/Image\/AbstractDecoder.php","line":257}}
Any help?
Note, tried using formData and changed the jQuery to:
$('.update-insertimage-form').submit(function() {
$(".submit-newupdate-btn").addClass('disabled');
var rootAsset = $('.rootAsset').html();
var formData = new FormData();
formData.append('update-insertimage-btn[]', $('.update-insertimage-btn')[0].files[0], $('.update-insertimage-btn')[0].files[0].name);
$.ajax({
url: rootAsset+'saveUploadedImage',
type: 'post',
cache: false,
dataType: 'json',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data) {
if(data.errors) {
$('.modal-body').append('<div class="alert alert-danger centre-text modal-error-message" role="alert"><strong>Error!</strong> '+ data.errors +'</div>');
} else if (data.success) {
$(".form-control-addupdate").append(data.name);
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
return false;
});
But that is throwing the error:
{"error":{"type":"ErrorException","message":"preg_match() expects parameter 2 to be string, array given","file":"\/Applications\/MAMP\/htdocs\/buildsanctuary\/vendor\/intervention\/image\/src\/Intervention\/Image\/AbstractDecoder.php","line":208}}
Thanks for any help.

Try passing the form to the FromData contructor instead of trying to manually add the file to it.
var formData = new FormData($('.update-insertimage-form')[0]);

Related

Ajax getting 400 Bad Request when submitting Form only on Firefox

I have written a php code in wordpress to submit a form using ajax. It working fine on chrome but getting 400 Bad request on Firefox. This is my code:
jQuery(document).ready(function($){
jQuery( 'form[name="contact-me"]' ).on( 'submit', function(e) {
e.preventDefault();
var form_data = {};
$(this).serializeArray().forEach( function(element){
form_data[element.name] = element.value;
});
$.post(zt_send_form_obj.ajax_url, {
action: "zt_save_campain_form_data",
_ajax_nonce: zt_send_form_obj.nonce,
type: "POST",
contentType: 'application/json; charset=utf-8',
values: JSON.stringify(form_data),
}, function(data) {
if (data.success) {
if(data.data.info.message=='no'){
$('#myModal').show();
console.log('cod is in')
}
if(data.data.info.message=='yes'){
$('#CodeModal').show();
$('.the_cod_div').append('<span>'+data.data.info.code+'</span>');
console.log('data saved');
}
}
else{
console.log("not working");
}
});
});
});
Try this
$('form[name="contact-me"]').submit(function (e) {
e.preventDefault();
var form = $('#form_id')[0]; //set form id
var varform = new FormData(form);
varform.append("action", "zt_save_campain_form_data");
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: varform,
processData: false,
contentType: false,
cache: false,
crossDomain: true,
success: function (response) {
//if success do this...
console.log(response);
},
error: function (xhr, textStatus, error) {
console.log(xhr, textStatus, error);
}
})
});
Inside your form you can put this code for nonce validation
<?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' ); ?>

Laravel: MethodNotAllowedHttpException error with no message after AJAX call to resource controller

I'm updating the value of some models in a database but when I hit submit I get the following error:
"message: "", exception:
"Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException",
file:
"C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php",
line: 255"
This is my JQuery code:
var formData = new FormData();
formData.append('id', $(this).attr("data-id"));
formData.append('first', $('#schedules_morning').val());
formData.append('second', $('#schedules_night').val());
$.ajax({
async: true,
cache: false,
url: '/schedules',
type: 'PUT',
data:
{
formData
},
dataType: 'JSON',
processData: false,
contentType: false,
success: function (data) {
$('.form_valid_container').fadeIn().html('<span class="form_valid_text">✓ '+ data.success +'</span>');
form.trigger("reset");
console.log(data.success);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$.each(errors , function(){
$('.form_error_container').fadeIn().html('<span class="form_error_text">✘ '+ errors.message +'</span>')
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm sending the request to a resource controller route:
Route::resource('/schedules','ScheduleController');
public function update(Request $request)
{
$schedule = Schedule::findOrFail($id);
$schedule->morning = $request->morning;
$schedule->night = $request->night;
$schedule->save();
return response()->json([
'schedule' => $schedule,
'success' => 'Horario actualizado correctamente',
]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
PHP (Laravel) Just trick up PUT and DELETE request so with all put request in laravel they put a hidden variable called _method with value put and laravel validated that method agains the post request. So replace your code like below and it should work.
var formData = new FormData();
formData.append('id', $(this).attr("data-id"));
formData.append('first', $('#schedules_morning').val());
formData.append('second', $('#schedules_night').val());
formData.append('_method', 'put');
$.ajax({
async: true,
cache: false,
url: '/schedules',
type: 'POST',
data:
{
formData
},
dataType: 'JSON',
processData: false,
contentType: false,
success: function (data) {
$('.form_valid_container').fadeIn().html('<span class="form_valid_text">✓ '+ data.success +'</span>');
form.trigger("reset");
console.log(data.success);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$.each(errors , function(){
$('.form_error_container').fadeIn().html('<span class="form_error_text">✘ '+ errors.message +'</span>')
});
}
});

Pass data from ajax to laravel 5.1 Controller in order to save to mysql?

I need to pass data from jquery (version 1.9.1) to my Controller (Laravel 5.1) and then save it to mysql.
How to do that and pass the variable slot? It didn't work so far. For any further details, please asked me.
jquery:
$(".tic").click(function(){
var slot = $(this).attr('id');
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { _token: {{ csrf_token() }}, moves: slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
Controller:
public function addhistory(Request $request)
{
$history = new History();
$history->game_id = Game::orderBy('id', 'desc')->first()->id;
$history->moves = $request->moves;
$history->save();
return redirect()->back();
}
Routes:
Route::post('/addhistory', 'GameController#addhistory');
Errors in console:
(index):198 Uncaught ReferenceError: HAmcYRScL9puItnUGbd2kHx.... is not defined
at HTMLAnchorElement.<anonymous> ((index):198)
at HTMLAnchorElement.dispatch (191.js:3)
at HTMLAnchorElement.v.handle (191.js:3)
191.js file is the jquery version of 1.9.1
You can use this code, it may works
$(".tick").click(function (event) {
event.preventDefault();
$('.loading').show();
var form = $(this);
var data = new FormData($(this)[0]);
var url = form.attr("action");
$.ajax({
type: "POST",
url: url,
data: data,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert("Data has been saved successfully.");
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
Try this code-
$(".tic").click(function(){
var slot = $(this).attr('id');
var token= $("input[name='_token']").val();
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { '_token': token, 'moves': slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
And in your controller you don't need return redirect because the request is asynchronous. So I am returning true. Make sure you include History model at the top of your controller
public function addhistory(Request $request)
{
$game_id=Game::orderBy('id', 'desc')->first()->id;
History::create([
'game_id'=>$game_id,
'moves'=>$request->moves
]);
return true;
}

How handle errors in php script fired by Jquery.ajax?

I have php-script, firing with jquery ajax function. Somthing like this:
$("a.test").click (function () {
var new_id = $(this).attr("new_id");
$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(){
alert('error');
}
});
return false;
});
Now, a have some errors in test.php, but I can't see them. Sript just runs and I have no feedback, only error alert (alert ('error')).
How can I get back errors, that I have in test.php to handle them?
If you echo the errors in test.php, you can simply do:
$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(data){
alert('error:'+data);
}
});
return false;
});
Edit:
I usually do something like this. In test.php if you get an error, create an array with your error info and echo it json encoded:
$message=array('error' => 1,'message' => '<div class="alert alert-danger" role="alert">' . $login['message'] . '</div>' );
echo json_encode($message);
Now in your jquery you can retrive the error by:
success: function (data) {
alert (data);
},
error: function(data){
var obj = JSON.parse(data);
alert(obj.message);
}
When you have it in array like this you dont even need error: function(data) anymore, since you can simply:
success: function (data) {
var obj = JSON.parse(data);
if (obj.error) {
// do something
alert (obj.message);
}else{
// do something else
}
},
On test.php you could show errors using the code explained here: https://stackoverflow.com/a/21429652/6525724
And then on this page instead of alert('error') you could use alert(data).
Try this
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}

ajax does not get data from the controller in laravel

I want to perform multiple operation when i select value from dropdownbox for that i am using ajax in larvel.My problem is when i select dropdown list value it get passsed through the ajax,from ajax it calls controller based on that i want fetch required filed from datatabase but ajax does not return any success result.Here is my code.
view
{{ Form::select('asset_type_id', $assettype_list,
Input::old('asset_type_id', $assetdetail->asset_type_id), array('class'=>'select2','id'=>'asset_type_id', 'style'=>'width:350px')) }}
ajax
$(document).ready(function() {
$("#asset_type_id").change(function() {debugger;
// alert($('#asset_type_id option:selected').val());
var data=$('#asset_type_id option:selected').val()
$.ajax({
type: 'POST',
url: '/Controllers/Admin/AssetdetailsController',
data: data,
cache: false,
success: function(data)
{
check(data);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
});
});
controller
public function postPositions($data)
{
if (Request::ajax())
{
$positions = DB::table('asset_types')->select('is_nesd')->where('id', '=', $data)->get();
return $positions;
}
}
route
Route::post('Controllers/Admin', [usesu'Controllers\Admin\AssetdetailsController#postPositions');
In your ajax, try to change the URL:
$(document).ready(function() {
$("#asset_type_id").change(function() {debugger;
// alert($('#asset_type_id option:selected').val());
var data=$('#asset_type_id option:selected').val()
$.ajax({
type: 'POST',
url: '{{ URL::route('post_form') }}',
data: data,
cache: false,
success: function(data)
{
check(data);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
});
});
And in your route (see Laravel 4 Docs)
Route::post('Controllers/Admin', array('uses' => 'Controllers\Admin\AssetdetailsController#postPositions', 'as'=>'post_form'));
Update
To solve the error with the controller, try this:
public function postPositions()
{
if (Request::ajax())
{
$data = Input::get('form_data');
$positions = DB::table('asset_types')->select('is_nesd')->where('id', '=', $data)->get();
return $positions;
}
}
And the JS code:
$(document).ready(function() {
$("#asset_type_id").change(function() {debugger;
// alert($('#asset_type_id option:selected').val());
var f_data=$('#asset_type_id option:selected').val(); // changed
$.ajax({
type: 'POST',
url: '{{ URL::route('post_form') }}',
data: { form_data: f_data }, // changed
cache: false,
success: function(data)
{
check(data);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
});
});
you may need to change URL to url: '/Controllers/Admin'.
Because you made Route as Controllers/Admin.
View:
{{ Form::open(array('url' => 'crud', 'method' => 'get', 'id' => 'myform', 'name' => 'myform')) }}
{{ Form::select('application',$download_options, Input::get('application'),$options = array('id' => 'application', 'class' => 'application')) }}
{{ Form::label('date', 'date', array('id' => 'date_label')); }}
{{ Form::select('date', $options = array('id' => 'date', 'class' => 'date')) }}
{{ Form::submit('Display', array('class' => 'btn btn-small btn-info', 'id' => 'submit')) }}
{{ Form::close() }}
<script>
$(document).ready(function($) {
$('#application').change(function(e){ // e=event
var application = $('#application option:selected').val();
$.getJSON('/getdata/'+application, function(data){
$('select#date').html('$'+data);
});
});
});
</script>
Route:
Route::get('getdata/{application}', function($application){
$selectboxtwo = DB::table('downloads')
->where('application', '=',$application)
->groupBy('date')
->lists('date');
return $selectboxtwo;

Categories