clear blade laravel for render new response ajax - php

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();
},

Related

CodeIgniter4: Resubmitting form using Ajax giving 403 Forbidden

I'm working on a project in CodeIgniter4. I'm trying to make an Ajax call to an endpoint (/adjustments/store). I'm validating the form using CodeIgniter and showing the validation errors in my view. The issue is when the first time, i submit the form, it works and shows some validation errors. But when i fill the form correclty (to get not validation errors) and resubmit it again it gives me 403 forbidden error in the console.
Ajax call
$.ajax({
type: 'post',
url: '/adjustments/store',
dataType: 'html',
data: {
number,
date,
type,
account,
description,
adjData,
csrf_test_name
},
success: function (res) {
if (IsJsonString(res)) {
const response = JSON.parse(res);
if (response.hasOwnProperty('validation_errors')) {
const errors = response.validation_errors;
for (err in errors) {
$(`input[name=${ err }]`)
.parent()
.append(`<small class="text-danger">${ errors[err] }</small>`)
}
}
}
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
console.log(res);
}
CodeIgniter Controller
public function store () {
$data = $this->request->getPost(NULL);
// Validate
if (! $this->validate([
'number' => 'required',
'date' => 'required',
'type' => 'required',
'adjData' => 'required',
]))
{
echo json_encode(['validation_errors' => $this->validator->getErrors()]);
return;
}
echo json_encode($data);
}
Any solution to this?
If you are resubmitting a form then you have update csrf token on every request with ajax.
Whenever validation fails pass csrf token and update it every time.
In your controller -
public function store () {
$data = $this->request->getPost(NULL);
// Validate
if (! $this->validate([
'number' => 'required',
'date' => 'required',
'type' => 'required',
'adjData' => 'required',
]))
{
echo json_encode(['validation_errors' => $this->validator->getErrors(), 'csrf' => csrf_hash()]);
return;
}
echo json_encode($data);
}
In you ajax -
$.ajax({
type: 'post',
url: '/adjustments/store',
dataType: 'html',
data: {
number,
date,
type,
account,
description,
adjData,
csrf_test_name
},
success: function (res) {
if (IsJsonString(res)) {
const response = JSON.parse(res);
$("input[name='csrf_test_name']").val(response ["csrf"]);
if (response.hasOwnProperty('validation_errors')) {
const errors = response.validation_errors;
for (err in errors) {
$(`input[name=${ err }]`)
.parent()
.append(`<small class="text-danger">${ errors[err] }</small>`)
}
}
}
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
So once you update csrf then it will work fine.
Thanks.

AJAX get call always returning empty string

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?

Parse php array('s) to json isn't work

I've created a function in CakePHP 3 to get a list of content and a list of labels for a dynamic filled html table. But after I parsed the php array's to json the labels array isn't parsed. This will give me the "Cannot use 'in' operator...." error from the DataTables library.
When I log the parsed array you can see below that 'labels' is a normal array and content is a json array. I need two json array's.
{labels: Array(6), content: {…}}
Parse php array to json inside my controller:
public function ajaxGetContentList() {
$allContent = this.getAllData();
$contentArray = array();
$labelArray = array();
foreach ($allContent as $content) {
if (isset($content->element->display)) {
$contentArray[$content->form_id][$content->element->name] = $content->content;
if(!in_array( $content->element->name, $labelArray)){
$labelArray[] = $content->element->name;
}
}
}
$data = [
'labels' => $labelArray,
'content' => $contentArray
];
$content = json_encode($data);
$this->response->getBody()->write($content);
$this->response = $this->response->withType('json');
return $this->response;
}
}
Ajax call inside my view:
function setContentListToTable() {
$.ajax({
url: websiteUrl + 'storages/list/' + '<?= $slug; ?>' + '/ajaxGetContentList',
type: 'post',
dataType: 'html',
data: {slug: '<?= $slug; ?>'},
success: function (data) {
var jsonArray = jQuery.parseJSON(data)
$('table').DataTable({ "columns": jsonArray.labels,"data": jsonArray.content});
}
});
}

how to retrive form.serialize() data in laravel controller

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.

Call function before return Response::json in Laravel 4 gives "json.parse:unexpected non-whitespace character after json data"

My Controller
public function electricityBillAddToCart(){
$accountNumber = Input::get( 'accountNumber' );
$amount = Input::get( 'amount' );
$userId = Auth::user()->id;
$type = TransactionTypes::ELECTRICITY;
if(is_numeric($accountNumber)) {
CartHelper::addToCart($userId, $accountNumber, $amount, $type);
return Response::json("Okay");
}
return Response::json("Error");
}
The above function is called using the following ajax request
$.ajax({
url: "/addToCart/electricityBill",
type: "POST",
dataType:"json",
data: {'accountNumber': reloadto, 'amount': amount},
success: function (re) {
console.log("Success");
},
error: function(re) {
console.log("Error");
}
The response to the front end would be []"okay", and "Error" would be printed in the console. If the static function that I call before sending the response is commented out it would work fine (it would return "okay", and print "Success"). The code that I comment is
CartHelper::addToCart($userId, $accountNumber, $amount, $type);
Anyone knows why this is?
I found the problem. There was an echo in the CartHelper class. Once that was deleted, it worked fine

Categories