I use $("form").serialize() to submit form data. while I return value from a method it works fine. My method code is as below.
public function store(Request $request)
{
$list = #$request['lists'];
$total_amount = #$request->total_amount;
$r_g_amount = #$request->r_g_amount;
$type = #$request->type;
$cash = #$request->cash;
$credit = #$request->credit;
$bank = #$request->bank;
$from = #$request->from;
$to = #$request->to;
return $cash;
}
it sends me null value, if I return $request->formdata then it sends me all details of form. formdata is variable which I pass from ajax as formdata:$("form").serialize().
so how can I get values of form data into variable.
ajax request
$.ajax({
url: "{{ route('HK.store') }}",
data: {
lists: list, total_amount: total_amount, formdata : $("form").serialize(), "_token": "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
console.log(data);
}
});
enter code here
Use below code in your controller function of Laravel,
$box = $request->all();
$myValue= array();
parse_str($box['formdata'], $myValue);
print_r($myValue);
Hope it will help you!
You need to update your code like:
public function store(Request $request)
{
$list = $request->lists;
$total_amount = $request->total_amount;
$r_g_amount = $request->r_g_amount;
$type = $request->type;
$cash = $request->cash;
$credit = $request->credit;
$bank = $request->bank;
$from = $request->from;
$to = $request->to;
return response(['cash' => $cash]);
}
When you are using dynamic post data you have to be sure that variables exists. So here is an example how to get variables you need:
public function store(Request $request)
{
$data = $request->all();
$list = array_get($data, 'list', 'default value');
$total_amount = array_get($data, 'total_amount', 0);
...
return $whatever;
}
You can convert your serialized formData into Object first and then send it to your server:
const clientInfo= $('#checkoutForm').serialize();
const searchParams = new URLSearchParams(clientInfo);
clientInfo = Object.fromEntries(searchParams);// { 'type' => 'listing', 'page' => '2', 'rowCount' => '10' }
And then in ajax request, pass the clientInfo to data property:
$.ajax({
url: ...,
method: "post",
data: clientInfo ,
success: function(){
}
})
In the Controller, when you dd the payload, it's gonna look like this:
array:6 [
"customer_name" => "Arely Torphy II"
"customer_email" => "lexi.kulas#jacobson.net"
"customer_phone" => "1-448-897-3923 x1937"
"address" => "1422 Ellie Stream Suite 859"
"post" => "37167"
"company_name" => "company"
]
Now, you can easily retrieve any data you'd like to.
Related
I'm trying to use the same blade to return a response from ajax.
In my first controller function I return a view with data:
public function index()
{
$data = (object) array(
'title' => trans('web.blog_title'),
'description' => trans('web.blog_header_info'),
);
$posts = \DB::table('blogs')->paginate(3);
return view('web.blog')->with('data', $data)->with('posts', $posts);
}
But now I'm doing a search with ajax and I want to use the same blade template for the response.
My second function that should render my response is:
public function getLocalNews($restaurant_id) {
$data = (object) array(
'title' => trans('web.blog_title'),
'description' => trans('web.blog_header_info'),
);
$news = Blog::query()->where('restaurant_id', '=', $restaurant_id)->paginate(3);
return view('web.blog')->with('data', $data)->with('posts', $news);
}
but it doesn't do anything...
ajax:
$("#submit_btn_blog_res").on("click", function(e){
e.preventDefault();
var form = $('#searchRestaurant');
$(this).find('input').removeClass('is-invalid');
$(this).find('.error').html('');
$.ajax({
url: "blog/getLocalNews/" + $(".suggest-element").attr('id'),
data: form.serializeArray(),
type: 'GET',
dataType: form.data('type'),
success: function(data){
console.log(data);
$(".post-article").remove();
},
error: function(jqXHR){
var response = JSON.parse(jqXHR.responseText);
if (response.errors.name) {
$(form).find('input[name="name"]').addClass('is-invalid');
$(form).find('.name-error').html(response.errors.name);
} else if (response.errors.email) {
$(form).find('input[name="email"]').addClass('is-invalid');
$(form).find('.email-error').html(response.errors.email);
} else if (response.errors.phone) {
$(form).find('input[name="phone"]').addClass('is-invalid');
$(form).find('.phone-error').html(response.errors.phone);
} else if (response.errors.comments) {
$(form).find('input[name="comments"]').addClass('is-invalid');
$(form).find('.comments-error').html(response.errors.comments);
} else if (response.errors.gRecaptchaResponse) {
$(form).find('input[name="g-recaptcha-response"]').addClass('is-invalid');
$(form).find('.g-recaptcha-response-error').html(response.errors.gRecaptchaResponse);
}
}
});
}); //submit search form restaurant
You should pass your response with a content-type of application/json. Hopefully, laravel has a function as response() which do this for you.
public function getLocalNews($restaurant_id){
$data = (object) array(
'title' => trans('web.blog_title'),
'description' => trans('web.blog_header_info'),
);
$news = Blog::query()->where('restaurant_id', '=', $restaurant_id)->get();
$response_data = ['data'=>$data, 'posts'=>$news];
return response()->json($response_data, 200);
}
As said in laravel helpers functions doc First parameter of response() receives the data that you want to be included in the body. If you pass an array, it will be converted to json, and the second parameter is the http status code of the response.
Notice: If you want to send your results with pagination. You can use laravel api resource.
Update: Use your ajax to add new received data to your html.
success: function(response){
console.log(response);
$('#desired-element-for-data').html('');
$.each(response.data, function(item){
html1 += '<p>item</p>';
});
$('#desired-element-for-posts').html('');
$.each(response.posts, function(item){
html2 += '<p>item</p>';
});
$('#desired-element-for-data').html(html1);
$('#desired-element-for-posts').html(html2);
$(".post-article").remove();
},
I am trying to make a simple AJAX GET call to my php backend, it hit and runs the method defined however no matter what the response data in the success function is always an empty string with a 200 response.
My ajax request is:
$("#coverage-table").on("click", "td", function() {
$(this).attr('id');
//Create Ajax call
//Get bill data/notes
//Present modal
$.ajax({
url: 'http://tms-v2.test/tms/getBillNotes',
type: 'GET',
data: {
bills: $(this).attr('id')
},
success: function(response) {
console.log(response);
debugger;
modal.style.display = "block";
}
});
});
My php method is:
public function getBillNotes() {
$bills = array_filter(explode("," ,$_GET['bills']));
$billingGateway = new BillingGateway;
$data = $billingGateway->getBillNotes($bills);
//Convert mysql object to array
while($row = mysqli_fetch_array($data)){
$items[] = $row;
}
foreach ($items as $key => $bill) {
$return[$bill['bill_id']] = [
'invoice_number' => $bill['invoice_number'],
'supplier' => $bill['supplier_name'],
'creation_date' => $bill['creation_date'],
'uploaded_by' => $bill['first_name'].' '.$bill['last_name'],
'is_credit_note' => !!$bill['type'],
'validation_status' => !!$bill['is_validating'],
'paid_date' => $bill['paid_date'],
'critical_notes' => $bill['note']
];
}
return 'TEST';
}
However this is always returning "", is this something to do with my request headers?
I'm trying to send a username from the view to the controller through Ajax like this :
$('#exampleFormControlSelect1').change(function(){
var username =$('#exampleFormControlSelect1').val();
$.ajax({
type: 'POST',
dataType: "json",
url: "Panier/loadPanier",
data: {username: username},
success: function(result){
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
},
});
});
and I try to use the sent value to do some work:
public function loadPanier()
{
$res = [];
$username = $this->input->post('username');
$panier_data = $this->model_panier->getPanierData($username);
foreach ($panier_data as $k => $v) {
$idPiece = $v['idPiece'];
$qte = $v['quantity'];
$piece_data = (array)$this->model_catalogue->getDetail($idPiece);
$price = (int)$piece_data['Unit Price'];
$montant = $qte * $price;
array_push($res, array(
'idPiece' => $idPiece,
'Description' => $piece_data['Description'],
'qte' => $qte,
'prix HT' => round($piece_data['Unit Price'], 3),
'montant' => $montant
));
}
return $res;
}
In my URL I'm getting this error :
Invalid argument supplied for foreach()
but here's what I'm noticing by doing var_dump($username):
C:\wamp64\www\PortalDealer\application\controllers\Panier.php:66:null
So my data is not passing!
Can you help me with this?
EDIT
showcase the result of this part of the code :
var_dump($_REQUEST);
$res = [];
$username = $this->input->post('username');
var_dump($username);
$panier_data = $this->model_panier->getPanierData($username);
var_dump($panier_data);
The below code should send your data to Panier/loadPanier/.
$('#exampleFormControlSelect1').change(function(){
var val1 =$('#exampleFormControlSelect1').val();
$.ajax({
method: "POST",
url: "Panier/loadPanier/",
data: { username: val1}
}).done(function( result ) {
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
});
});
You were seeing null every time you did var_dump() because you were trying to load the page independently. The page will only give you the POST value if you are going to the page thru the form, in this case, the form is javascript. When you load a page with POST method in javascript, the response is sent to the same page with ajax so you can work with your code without having to refresh the page.
Also: You cannot return data to javascript. You have to print it out to client side so that your javascript's JSON parser can read it. Therefore, instead of return $res; :
echo json_encode($res);
Straight to the case.
This is some functions from my model (Student Model):
public function get_exam_data($exam_id){
$this->db->select('exam_id, exam_name, duration');
$this->db->from('exams');
$this->db->where('exam_id', $exam_id);
$result = $this->db->get();
$exam = array();
$examrow = $result->row();
$exam['id'] = $examrow->exam_id;
$exam['name'] = $examrow->exam_name;
$exam['duration'] = $examrow->duration;
return $result;
}
public function start_exam($exam_id, $student_id)
{
$this->db->select('*');
$this->db->from('exam_record');
$exam_newstatus = array(
'student_id' => $student_id,
'exam_id' => $exam_id);
$this->db->set('start_time', 'NOW()', FALSE);
$this->db->insert('exam_record', $exam_newstatus);
//$examrecord_id is autoincrement in mysql exam_record table
$examrecord_id = $this->db->insert_id();
return $examrecord_id;
}
This is a function from the Student Controller:
public function get_student_exam_data()
{
$exam_id = $this->input->post('examId');
$examdata = $this->student_model->get_exam_data($exam_id);
$session = get_session_details();
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode($examdata);
}
This is how I access the $examdata value via Ajax:
jQuery(function()
{
$.ajax({
type : "POST",
url : "../get_exam_data/",
async : false,
data : {"examId": EXAM_ID },
success: function(response)
{
var data = $.parseJSON(response);
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
});
}
I want to be able to pass $examrecord_id from the Student Controller to use it on my jQuery file, just like the $examdata.
I tried to use json_encode() twice on the Controller. Didn't work.
How do I pass $examrecord_id from the Controller to the jQuery file?
Can someone enlighten me, please? Thank you.
Add another index for your $examrecord_id
if (isset($session->studentdetails) && !empty($session->studentdetails))
{
$loggeduser = (object)$session->studentdetails;
$examrecord_id = $this->student_model->start_exam($exam_id, $loggeduser->student_id);
}
echo json_encode(array(
'examdata' => $examdata,
'examrecord_id' => (!empty($examrecord_id)?$examrecord_id:0)
));
Note the shorthand if condition to check if $examrecord_id is empty
Add a dataType option with 'json' as it's value. Then you can access the data
dataType : 'json',
success: function(response)
{
var data = response.examdata;
alert(response.examrecord_id); // your examrecord_id
examId = data.id;
examName = data.name;
examDuration = data.duration;
}
I am sending values from view to controller
Here is my Script :
<script>
$(document).ready(function() {
var vehicle_data = [];
$("#vehicle_submit").click(function(event) {
event.preventDefault();
vehicle_data.push($("#_token").val());
vehicle_data.push($("#VehicleNo").val());
vehicle_data.push($("#VehicleName").val());
$.ajax({
type: "POST",
url: "{{ URL::to('vehicle-process') }}",
data: "vehicle_arr=" + vehicle_data,
async: true,
success: function(data) {
console.log(data);
}
}, "json");
});
});
</script>
I am sending the values VehicleNo and VehicleName to the vehicle-process controller as a single array named as vehicle_arr using POST Method.
Now in the controller :
public function vehicle_process()
{
$a = Input::except(array('_token')) ;
$rule = array(
'VehicleNo' => 'required',
'VehicleSeats' => 'required'
);
$validator = Validator::make($a, $rule);
if ($validator - > fails()) {
$messages = $validator - > messages();
return $messages;
}
else
{
$table = new VehicleModel;
$table->VehicleNo=$VehicleNo; // How can i get the value of VehicleNo and Vehcle Name
$table->save();
}
The Validator can't able to analyze the name of the element i.e., VehicleNo or VehicleSeats,
So whenever i pass the data from view it was showing VeihcleNo required validator messages all the time.
Can i make the validator like
$rule = array(
$a['VehicleNo'] => 'required',
$a['VehicleSeats'] => 'required'
);
as i am storing the all the values in $a.
I even tested return $a; to view all elements in the controller it shows like
Object {vehicle_arr: "wBNTzuTY20GL6BR147TIM9l8mxpCbgMAM7ok7fD4,EZ-55,35"}
Is it possible to get values like
$value = Input::post('VehicleNo');
So, How can i get the values extract so that i can done with the validation and store in db
My Model just has the Table Name
So i just need the way to get the value of $VehicleNo to store in db. So that i can construct this
$table->VehicleNo=$VehicleNo;
$table->save();
Update : It is ok even if i change the method to POST to GET in order to achieve my Result