Input::all() returns empty array in laravel 5 - laravel

here's my ajax request. i send request to controller to remove pictures
$(document).on("click", "button[data-delete]", function(e) {
var tour_id = $("form").attr("data-tour-id");
var gallery = {};
$("input:checkbox[class = checkbox]:checked").each(function(k){
gallery[k] = $(this).attr("data-gallery-id");
});
gallery = JSON.stringify(gallery);
bootbox.confirm({
message: "გსურთ აღნიშნული სურათის წაშლა?",
callback: function(result){ }
});
$("button[data-bb-handler='confirm']").on("click",function(){
$.ajax({
headers: {'X-CSRF-Token': $('meta[name="csrf_token"]').attr('content')},
url: "/{lang}/admin/tours/"+ tour_id +"/edit/removeGalleryPic/"+ gallery,
data : { id: tour_id, pics: gallery },
}).done(function() {
window.location.reload();
});
});
});
it works. so if request response 200(ok) page will be reloaded. but i have another form fields, and after being reloaded i want to save(flash) the values of these fields. so in controller i return input, but it returns empty array. here's my controller
public function removeGalleryPic($id, $pics)
{
$pics = json_decode($pics, true);
$tour_whole_gallery = Tour_gallery::where("tour_id", $id)->get();
if(count($tour_whole_gallery) > 0)
{
foreach($tour_whole_gallery as $gallery)
{
foreach($pics as $pic_id)
{
if($gallery->id == $pic_id)
{
unlink(public_path() . $gallery->path);
Tour_gallery::where("id", $pic_id)->delete();
}
}
}
}
return Input::all();
}
how should i return all input fields with their data? i also tried these
$request->all();
$request->flash();
redirect()->back()->withInput();
but result is the same.

you could try this:
$input = Input::all();
return response()->json($input);

Related

Laravel: update function creating new record instead of updating existing one

Hi guys i am trying to update my existing record in my edit page..so when i clicked on update button it is creating new record instead of updating existing one
Here is my controller:
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = new Qtype_editor();
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = $request->input('qtype_json');
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
And i have ajax call where i am updating records from ajax
Here is my ajax code
function saveEditQtypeFile(edit_qtype_id)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
chk_EnumValuesValidation = chkEnumValuesValidation(isSoltion, stepCount);
if(!chk_EnumValuesValidation)
{
return false;
}
else
{
// Function to push "MainArray" in current Solution
pushVarMainArrayInThisSolution(isSoltion, var_main_arr.var_arr_values);
arr = ar;
var edit_qtype_id = $('#edit_qtype_id').val();
var qtype_name = $('#qtype_name').val();
var subject_list = $('#qtype_subject_id').val();
var ddl_topic_type = $('#qtype_topic_id').val();
var qtype_option = $('#qtype_option').val();
var jasondata = $('#qtype_json').val();
var sort_order = $('#sort_order').val();
var jasondata = $('#jasonData').val();
var sendInfo = {
'edit_qtype_id':edit_qtype_id,
'arr':arr,
'saveEditQtypeFile':1,
'qtype_name':qtype_name,
'qtype_subject_id':subject_list,
'qtype_topic_id':ddl_topic_type,
'qtype_option':qtype_option,
'qtype_json':jasondata,
'sort_order':sort_order
};
console.log(sendInfo);
//var loadQtypeInfo = JSON.stringify(sendInfo);
$.ajax({
url: "/eqtype-editor/update",
type: "POST",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});
}
}
Here is my route file:
Route::post('eqtype-editor/update', 'QtypeEditorController#update');
Can anyone help me where i did mistake..thanks in advance.
There are two ways to achieve update of records
One - minor change in your code to just get it working
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = $request->input('qtype_json');
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
Second:
Following Laravel conventions - The Laravel Way
Route definition should be: PUT/PATCH methods for resource update
Route::match(
['PUT', "PATCH'],
'eqtype-editor/{qtype_editor}', //qtype_editor param for route model binding
'QtypeEditorController#update'
);
public function update(Request $request, Qtype_editor $qtype_editor)
{
//$qtype_editor will be resolved via route model binding
//object representing db record with id of $qtype_editor passed from frontend
//$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = $request->input('qtype_json');
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
Javascript
$.ajax({
url: `/eqtype-editor/${edit_qtype_id}`, //add the id to the route
type: "PUT",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});

Column can not be null in ajax laravel update function

Hi guys i am sending my updated values from ajax to my update function.i am getting error as "Column cannot be null"
Here is my input which i am sending json data:
<input type="text" id="jsonData" name="jsonData">
And here is my ajax form:
function saveEditQtypeFile(edit_qtype_id)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
chk_EnumValuesValidation = chkEnumValuesValidation(isSoltion, stepCount);
if(!chk_EnumValuesValidation)
{
return false;
}
else
{
// Function to push "MainArray" in current Solution
pushVarMainArrayInThisSolution(isSoltion, var_main_arr.var_arr_values);
arr = ar;
var edit_qtype_id = $('#edit_qtype_id').val();
var qtype_name = $('#qtype_name').val();
var subject_list = $('#qtype_subject_id').val();
var ddl_topic_type = $('#qtype_topic_id').val();
var qtype_option = $('#qtype_option').val();
var jasondata = $('#jsonData').val();
var sort_order = $('#sort_order').val();
var sendInfo = {
'edit_qtype_id':edit_qtype_id,
'arr':arr,
'saveEditQtypeFile':1,
'qtype_name':qtype_name,
'qtype_subject_id':subject_list,
'qtype_topic_id':ddl_topic_type,
'qtype_option':qtype_option,
'qtype_json':jasondata,
'sort_order':sort_order
};
console.log('json',jasondata);
//return false;
//var loadQtypeInfo = JSON.stringify(sendInfo);
$.ajax({
url: "/eqtype-editor/update",
type: "POST",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
window.location.href ="/eqtype-editor";
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});
}
}
and here is my controller:
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = json_decode($request->input('jsonData'));
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
From ajax when i console i am getting my json data..i am getting error as qtype_json cannot be null.
Can anyone help me where i am missing it.
Thanks in advance.
You use a wrong key for your data.
Change the line in your controller:
$qtype_editor->qtype_json = json_decode($request->input('jsonData'));
to
$qtype_editor->qtype_json = json_decode($request->input('qtype_json'));
and it will work.

Worpress bad request 400 pure Javascript

I get this following error when I use ajax in pure javascript:
"POST http://localhost:8888/website/wp-admin/admin-ajax.php" 400 (Bad Request) line in code: this.xhr.send(JSON.stringify(data));
my Contact.js file:
var Contact = function(data){
//setups and others methods
this.onFormSent = function(data){
data = {
action: 'my_action',
data: data
};
if(this.ajaxSendURL !== null){
this.xhr.open("post", this.ajaxSendURL);
this.xhr.setRequestHeader("Content-Type", "application/json");
this.xhr.onload = function() {
if(self.xhr.status === 200){
console.log(self.xhr.responseText);
var response = JSON.parse(self.xhr.responseText);
self.onSuccessForm(data);
}
};
this.xhr.send(JSON.stringify(data));
}
};
};
I use a form tag in html after filled my "form" and pressed the submit button it should call 'my_action' in php.
this my function.php:
function add_theme_scripts() {
wp_enqueue_script('Contact', get_template_directory_uri() . '/js/Contact.js', array(), 1.0, true);
wp_localize_script('Contact', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
/* AJAX */
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action(){
echo 'msg from server:' + $_POST['data']['name'];
die();
}
What am I doing wrong?
Updated: replaced by the following code and it works
this.onFormSent = function(data){
data = "action=my_function&name=" + dada.name;
this.xhr.setRequestHeader("Content-Type", "application/json");
...
}
Change this lines in ajax request;
data = {
action: 'my_action',
data: youdatadata
};
var data = $.param(data);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(data);

checking if the success data is empty in ajax method of jquery

I have two select boxes in my form.when a user select an option of first select box the options of second select box will be shown by jquery ajax.My problem is that some options of first select box has no record in database and when they selected the second select box should not be shown.I need to check if the data is empty .I treid this code but nothing happens
view:
<script type='text/javascript'>
$(document).ready(function(){
$('#subsec').hide();
$('section').change(){
var sec_id=$(this).val();
var url='article_controler/get_options/'+sec_id;
$.ajax({
url:url,
type:'post',
success:function(resp){
if(!resp)
$('#subsec').hide();
else
$('#subsec').show();
$('$subsec').html(resp)
})
}
});
</script>
you can try this
$.ajax({
url:url,
type:'post',
success:function(resp){
if(resp == "" || resp == null){
$('#subsec').hide();
}
else {
$('#subsec').show();
$('#subsec').html(resp);
}
})
}
});
I have added inline comments to help you out
class Article_Controller extends CI_Controller
{
public function get_options()
{
$option = $this->input->post('option'); // validate this
//Get a list of Sub options from your model
$model = ''; //your own implementation here
//If no model data returned, send a 404 status header
//and bail
if(!$model){
return $this->output->set_status_header(404);
}
$responce = array(
'suboptions' => $model // array of suboptions the model returned
);
// Ideally Abstract all the Ajax stuff to
// its own controller to keep things Dry
return $this->output
->set_status_header(200)
->set_content_type('application/json')
->set_output(json_encode($responce));
}
}
-
//Global URL variable or put it in <base href>
var URL = "<?php echo site_url();?>";
(function($){
var myForm = {
init : function(){
//initialize myForm object properties here
this.Form = $("form#myFormID");
this.selectChange = this.Form.find("select#mySelectBoxI");
this.newSelect = this.Form.find("select#secondaryselectboxId");
//hide second select with CSS by default
//Bind the Change event to our object(myForm) method
this.selectChange.on('change', $.proxy(this.ChangedEvent, this));
},
ChangedEvent : function(event){ // gets the change event
//Grab the currentTarget(option[i]) value from the event received
//You may also need to pass the CSRF Token
this.buildAjaxRequest({'option' : event.currentTarget.value});
},
buildAjaxRequest : function( data ){
var config = {
cache : false,
url : URL + 'article_controller/get_options',
method : 'POST',
data : data, //'option' : event.currentTarget.value
dataType : 'json'
};
this.makeAjaxRequest(config).then(
$.proxy(this.ResponceHandler, this),
$.proxy(this.ErrorHandler, this)
);
},
makeAjaxRequest : function( config ){
return $.ajax( config ).promise();
},
ResponceHandler : function( data ){
$.each(data.suboptions, function(i, v){
this.newSelect.append('<option value="'.data[i].'">'.data[v].'</option>');');
});
this.newSelect.show();
},
ErrorHandler : function(xhr, statusText, exception){
switch(xhr.status)
{
case 404: //remember the 404 from the controller
alert(xhr.statusText); //handle your own way here
break;
}
},
}
myForm.init();
}(jQuery));
Hi pls try this,
<script type='text/javascript'>
$(document).ready(function(){
$('#subsec').hide();
$('#firstSelectBoxId').change("selectboxMethod");
});
function selectboxMethod(){
var sec_id=$("#firstSelectBoxId").val();
alert("Selected from first select"+sec_id);
if(sec_id != null){
var url='article_controler/get_options/'+sec_id;
$.ajax({
url:url,
type:'post',
success:function(resp){
$('#subsec').show();
$('#subsec').html(resp);
}
});
}else{
$("#subsec").hide();
}
}
</script>

how to retrieve data sent by Ajax in Cakephp?

I have been stuck at this problem for a whole day. What im trying to do is to send 2 values from view to controller using Ajax.
This is my code in hot_products view:
<script>
$(function(){
$('#btnSubmit').click(function() {
var from = $('#from').val();
var to = $('#to').val();
alert(from+" "+to);
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to,
success: function(data){
alert("success");
}
}
});
});
});
and my hot_products controller:
public function hot_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
//code to get data and process it here
}
}
I dont know how to get 2 values which are start_time and end_time.
Please help me. Thanks in advance.
PS: im using cakephp 2.3
$this->request->data gives you the post data in your controller.
public function hottest_products()
{
if( $this->request->is('ajax') ) {
$this->autoRender = false;
}
if ($this->request->isPost()) {
// get values here
echo $this->request->data['start_time'];
echo $this->request->data['end_time'];
}
}
Update
you've an error in your ajax,
$.ajax({
url: "/orders/hot_products",
type: 'POST',
data: {"start_time": from, "end_time": to },
success: function(data){
alert("success");
}
});
If you method is POST:
if($this->request->is('ajax'){
$this->request->data['start_time'];
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->data['start_time'];
$this->autoRender = false;
ANd if method is GET:
if($this->request->is('ajax'){
$this->request->query('start_time');
$this->layout = 'ajax';
}
OR
public function somefunction(){
$this->request->query('start_time');
$this->autoRender = false;

Resources