fetching ajax array values to Laravel controller - ajax

Please refer the below code.
public function store(Request $request)
{
$productId = $request->id;
$request->validate([
'fmcode',
'fmcodes',
'area',
'naoffm','glno'
]);
$input = $request->all();
$products=array($request->GLNO);
foreach ((array)$products as $product1) {
$product = Product::updateOrCreate(
[
'id'=> $productId ,
'fmcode' => $request->FMCODE,
'fmcodes' => $request->FMCODES,
'area' => $request->AREA,
'naoffm' => $request->NAOFFM,
'glno'=>$product1
]
);
}
return Response()->json($product);
}
I am requesting glno as array of selected values
$.ajax({
dataType: 'json',
url: "/getCountry/"+id,
type: "GET",
success: function (data) {
console.log(data);
$('select[name="NAOFFM"]').empty();
$.each(data, function(key,data){
$('select[name="NAOFFM"]').append('<option value="'+ data.NAOFFM +'">'+ data.NAOFFM +'</option>');
});
$('select[name="AREA"]').empty();
$.each(data, function(key,data){
$('select[name="AREA"]').append('<option value="'+ data.AREA +'">'+ data.AREA +'</option>');
});
$('select[name="FMCODES"]').empty();
$.each(data, function(key,data){
$('select[name="FMCODES"]').append('<option value="'+ data.FMCODES +'">'+ data.FMCODES +'</option>');
});
},
error: function(error) {
console.log(error);
}
});
$.ajax({
dataType: 'json',
url: "/getCity/"+id,
type: "GET",
success: function (data) {
console.log(data);
$('select[name="GLNO"]').empty();
$.each(data, function(key,data){
$('select[name="GLNO"]').append('<option value="'+ data.GLNO +'">'+ data.GLNO +'</option>');
});
},
error: function(error) {
console.log(error);
}
});
I am getting the ajax form select values but its not passing to controller. My doubt is how to get glno all dropdown list values to store in laravel. In select option I got values from ajax get by id but it is not passing to controller to store values.

Related

Laravel Explode Ajax Request Containing Name and Numbers

I'm using laravel 8.4 .
My route :
Route::post('test',[\App\Http\Controllers\DataController::class, 'store'])->name('pos-test');
My Controller :
public function store(Request $request)
{
// DB::table('data')->insert('product_code',$request->id);
$badge = explode(' ', $request);
$employee_id = $badge[0];
\DB::table('data')->insert(['product_code'=> $employee_id]);
return response()->json(['success'=>'Product saved successfully.']);
}
Ajax code :
function handleBarcode(scanned_barcode) {
//handle your code here....
console.log(scanned_barcode);
let _token = $('meta[name="csrf-token"]').attr('content');
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('pos-test') }}",
type: "POST", // Can change this to get if required
data: {
code : scanned_barcode,
_token: _token
},
success: function(data) {
$("#status").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#status").text(textStatus);
console.log(jqXHR);
}
});
};
The request is like this "555444 Razif Raziq" , i would like to explode it so I may insert only "555444" into table but in table column product_code is 'POST' .
The question is how to fix it? thank you
you must explode your correct data in request object not request object itself.
$badge = explode(' ', $request->code);
If the 'code' value is sent correctly, just use this
$request->code
public function store(Request $request)
{
\DB::table('data')->insert(['product_code'=> $request->code]);
return response()->json(['success'=>'Product saved successfully.']);
}

Ajax update field database field in laravel blade template

I have a list of hotels in a select I want update the database base on the hotel selected if it update the field I want to alert it on the home page.
this is the ajax function
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'{{ route('home', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert(data);
},
error: function (result) {
alert("Error occur in the update()");
}
});
}
}
my controller
public function update(Request $request, $hotel_plan_id)
{
$hotel=plan_hotel::where('hotel_plan_id', $hotel_plan_id)->first();
$hotel->hotel_name = $request->input('hotel_name');
//$hotel ->room_name = $request->input('room_name');
$hotel->save();
// return redirect('/home')->with('success', 'price updated');
}
my route
Route::post('home/{hotel_plan_id}', 'HomeController#update')->name('home');
my select form
{!! Form::select('hotel_name', array($item[4], $item[10]),'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onclick'=>"showRoom(this.value, $item[8])"));!!}
You have error with ajax url and you dont also pass the value of hotel name.
Check this changes.
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'/home/' + id,
data:{_token:'{{ csrf_token() }}', hotel_name: 'Your value here'},
});
}
Please return json response
return response()->json();
You have to return json object like this
return response->json([
'status' => 200,
'result' => true,
'error' => false,
'data' => $hotel
]);

laravel- request empty in controller using ajax

I am using laravel 6.0 and i am building crud application. I have following jquery code in view file
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/'+id,
method: 'post',
success: function (res) {
console.log(res);
}
})
});
}
And this is the code in controller
public function update(Request $request, $id='') {
$country = $request->input('countryname');
$sortname = $request->input('sortname');
$phonecode = $request->input('phonecode');
//return $country.$sortname.$phonecode;
return $request;
// DB::table('countries')->where('id',$id)->update(
// [
// 'name' => $country,
// 'sortname' => $sortname,
// 'phonecode' => $phonecode,
// ]);
}
The problem is $request returns empty.
If I don't use ajax then I am getting all input values. But I dont know why its not working for ajax request. Also I have added this line in view file
headers: {
'X-CSRF-TOKEN': '{!! csrf_token() !!}'
}
});
Please help me to solve this problem
You are not passing your form data. Try this:
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: $(this).serialize();
success: function (res) {
console.log(res);
}
})
});
}
laravel by default does not send raw data , you have to convert your data to json, the best practice is :
return response()->json([
'data' => $request
]);
Just try this code for example and see if you get any hint.
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: {'countryname' : 'India','sortname' : 'Sort Name', 'phonecode' : '022'};
success: function (res) {
console.log(res);
}
})
});
}
See if you are getting any response.

added a new record using ajax and codeigniter.i want to redirect to the view page after adding record. so i want to get the last insert id

Ajax function and controller action is given below.anyone can help to get the last insertid to redirect.the redirection is done in ajax success function. can it do in controller action.its not getting
Ajax function
<script type="text/javascript">
$('#rfqsubmit').click(function () {
//var title = $('#title').val();
var form_data = {
title: $('#txtname').val(),
merid: $('#mermerchant').val(),
userid: $('#customer').val(),
description: $('#txtrequirement').val(),
reqid: $('#requirementid').val(),
shipmethod: $('#shipmethod').val(),
shiplocation: $('#shiplocation').val(),
attachment: $('#txtattachments').val(),
bidclose: $('#txtbidclose').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo base_url() ?>moderator/RFQ/addoffline",
type: 'POST',
data: form_data,
success: function () {
window.location.href ="<?php echo base_url() ?>moderator/Employee/manageemployee/";
// window.location.href ="<?php //echo base_url() ?>moderator/RFQ/viewrfq/"+ form_data.reqid;
// alert('added Successfully');
}
});
return false;
});
</script>
Controller action
$this->load->helper(array('form', 'url'));
$this->load->helper('file');
$data7 = array(
'rfq_title' => $this->input->post('title'),
'rfq_detail' => $this->input->post('description'),
'rfq_merchantid' => $this->input->post('merid'),
'rfq_userid' => $this->input->post('userid'),
);
$add= $this->requirement_model->forminsert($data7);
}
Your question is not clear anyhow if i got what you need try this.
in your controller action return json response:
$this->load->helper(array('form', 'url'));
$this->load->helper('file');
$data7 = array(
'rfq_title' => $this->input->post('title'),
'rfq_detail' => $this->input->post('description'),
'rfq_merchantid' => $this->input->post('merid'),
'rfq_userid' => $this->input->post('userid'),
);
$inserted_id= $this->requirement_model->forminsert($data7);
//your forminsert method in model should return
//$this->db->insert_id();
$response=array('id'=>$inserted_id,'message'=>"inserted successfully");
echo json_encode($response);
die();
}
Your model function return last_inserted_id:
public function forminsert($data7)
{
$this->db->insert('jil_mrorfq',$data7);
//it will return last id
return $this->db->insert_id();
}
Now in ajax success :
$.ajax({
url: "<?php echo base_url() ?>moderator/RFQ/addoffline",
type: 'POST',
data: form_data,
dataType:"Json",
success: function (data) {
//to access that id
var last_inserted_id = data.id;
window.location.href ="<?php echo base_url() ?>moderator/Employee/manageemployee/"+last_inserted_id;
}
});

How to use ajax in Wordpress?

I want to use ajax in wordpress. How can I do it? I have attached my code here. But this is not working for me.
Here it is my wordpress action and hook.
function ajax_enqueuescripts() {
wp_enqueue_script('ajaxloadpost', get_template_directory_uri().'/js/my-ajax.js', array('jquery'));
wp_localize_script( 'ajaxloadpost', 'ajax_postajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', ajax_enqueuescripts);
add_action('wp_ajax_nopriv_ajax_ajaxhandler', 'my_action_callback' );
add_action('wp_ajax_ajax_ajaxhandler', 'my_action_callback' );
function my_action_callback(){
//echo "Df";print_r($_POST);die;
}
and here it is my js code
jQuery(document).ready(function(){
jQuery('#event-form').submit( function () {
var email = jQuery('#event_name').val();
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function() {
alert(email);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
return false;
});
});
The value that you alert in your success ajax function must come from your php function so you would have something like this:
PHP
function my_action_callback(){
echo $_POST['email']; die();
}
Javascript
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function(data) {
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
in your case data in javascript will be equal to anything that you echo out in your php function.
You can send json objects to javascript by encoding arrays in which case you would have
PHP
function my_action_callback(){
echo json_encode('email' => $_POST['email']));
die();
}
Javascript
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function(data) {
alert(data.email);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
I only gave you example of the places in your code that needed to be replaced, the rest seems alright.

Resources