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

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

Related

clear blade laravel for render new response ajax

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

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?

Data sent from Ajax to codeigniter controller

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);

AJAX POST two dimensional array to a Zend controller and recieving it

Hi in my view I am creating a two dimentional array in javascript and passting it to the update controller as follows :
Array in Javascript
item[0][0] = null;
item[0][1] = 1;
item[1][0] = 2;
item[1][0] = 3;
alert (item); will show ,1,2,3
Passing it to Zend controller as :
$.ajax({
type: "POST",
url: "admin/navigation/update",
data: item,
success: function(data) {
alert(data);
},
error: function() {
alert("failure");
}
});
return false;
}
How can I receive this from update controller and assign to it a php array as
public function updateAction() {
$data = $this->_request->getPost();
//Code should come here
array(
item1(
array(
value1 = item[0][0] //From javascript array
value2 = item[0][1]
)
)
item2(
array(
value1 = item[1][0]
value2 = item[1][0]
)
)
)
}
I'm a n00b in Zend and any help would be much appriciated :)
Instead of the below code:
$data = $this->_request->getPost();
Use the following code:
$data = $this->_request->getParams();
print_r($data);
This will give you the array as you are sending from javascript.
In your javascript file declare your array:
var item = [[1,2],[3,4]];
Then in your ajax call you should modify the data sent to be JSON. Replace the line
data: item
with
data: {data: JSON.stringify(item)}
Then, in your controller you can decode the data send to get your array:
$data = json_decode($this->getRequest()->getPost("data"));
and you have your array.

How to send array of JSON objects with jQuery

I'm programming an web page and I really stucked trying to send an Array of JSON objects to my PHP backend script.
this is my javascript code (using jQuery):
var toSend = new Array();
$("input[type=checkbox]").each(
function (indice, item)
{
var dom = $(item);
var domJSON = {
id: dom.attr("value"),
checked: (dom.attr("checked") == "checked" ? true : false)
};
//put object as JSON in array:
toSend.push($.toJSON(domJSON));
}
);
$.ajax({
type:"POST",
url: "salvar_escala.php",
data: {checkbox: toSend},
success: function(response) {
$("#div_salvar").html(response);
},
error: function() {
alert("Erro");
}
}
);
And in PHP I have this:
//Grab the array
$arrayFromAjax = $_POST['checkbox'];
foreach($arrayFromAjax as $aux) {
$temp = json_decode($aux, true);
$id = $temp['id'];
$value = $temp['checked'];
//This line doesn't print anything for $id and $value
echo "Id: $id | Value: $value<br />";
//This line prints an crazy string, but with right values
echo "CHEKBOX[] => $b<br />";
}
In this code, I'm decoding my objects to json, putting then in an array and sending. I also tried but objects in array (without json), and then, convert the array to json, and send them like that:
$.ajax({
type:"POST",
url: "salvar_escala.php",
dataType: "json",
data: {checkbox: $.toJSON(toSend)},
success: function(response) {
$("#div_salvar").html(response);
},
error: function() {
alert("Erro");
}
}
);
But in this case, it's worse, the error function is called.
You should be able to do the following in PHP
<?php
$checkboxes = json_decode($_POST['checkbox']);
foreach($checkboxes as $checkbox) {
$id = $checkbox['id'];
$val = $checkbox['value'];
print $id . ': ' . $val;
}
The problem is that you're trying to loop through a JSON string without first decoding it into a PHP array.

Categories