send json responses but with lots of data - javascript

I have a problem where the data that I send to my view doesn't match the amount of data that the query generates. only single data appears.
this is my function :
function lokasi_ajax() {
var kode_lokasi = $('#kode_lokasi').val();
$.ajax({
url : '<?= base_url() ?>index.php/asset/asset_dijual_proses/lokasi_ajax',
data: 'kode_lokasi='+kode_lokasi,
success : function (data) {
var json = data;
value = JSON.parse(json);
console.log(value.kode_aset);
}
});
}
this is the method on my controller :
function lokasi_ajax()
{
$kode_lokasi = $_GET['kode_lokasi'];
$data =array();
$query = $this->db->query("SELECT id_reg, item_lokasi, item_barang FROM asset_item
WHERE item_lokasi= '$kode_lokasi'");
foreach ($query->result() as $row) {
$data = array(
'kode_aset' => $row->id_reg,
'item_lokasi' => $row->item_lokasi,
'item_barang' => $row->item_barang
);
}
echo json_encode($data);
}
the amount of data that should be generated is like this picture :
result data from dbms
but from the response json only displays one data like this :
json response result

Your foreach loop reassigns the data. you need to add it to the array.
foreach ($query->result() as $row) {
$data[] = array(
'kode_aset' => $row->id_reg,
'item_lokasi' => $row->item_lokasi,
'item_barang' => $row->item_barang
);
}

Related

how to convert this string to an array?

I'm trying to convert this array I create in JS to then used in my controller to used in a foreach and used the data of the array. I'm using the framework codeigniter.
Here where I create the array in my JS file.
function get_array(){
var datos = []; // Array
$("#tbl_esctructura tbody > tr").each(function() {
var item = $(this).find('td:eq(1)').text();
var cantidad = $(this).find('td:eq(4)').text();
datos.push({
"item": item,
"cantidad": cantidad
});
});
datos = JSON.stringify(datos);
$.ajax({
data: {
'datos': datos
},
url: "<?php echo base_url() ?>Controller/data_from_array",
type: 'POST',
dataType : "json",
success: function(response) {
}
});
}
the data I send to the controller look like this.
[{"item":"1","cantidad":"2"},{"item":"2","cantidad":"4"}]
Now my controller PHP
public function data_from_array(){
$data = $this->input->post('datos', TRUE);
$items = explode(',', $data);
var_dump($items);
foreach ($items as $row) {
echo $row->item.'<br>';
}
}
and the var_dump($items) this is the result
array(2) { [0]=> string(12) "[{"item":"1"" [1]=> string(16) ""cantidad":"1"}]" }
}
And in this echo I get this error Message: Trying to get property 'item' of non-object
And I don't know what I'm doing wrong
Looks like a standard JSON.
Be sure to add true to json_decode function (second parameter) to return array instead of object.
$result = json_decode($data, true);
Have a look at JSON as this is a, nowadays, standard of data interchange for web and mobile apps and learn more about the function:
https://www.php.net/manual/en/function.json-decode.php
also look at its counterpart that will encode your arrays into JSON format:
https://www.php.net/manual/en/function.json-encode.php
You can use this code as the explode return array, not an object.
public function data_from_array(){
$data = $this->input->post('datos', TRUE);
$items = explode(',', $data);
var_dump($items);
foreach ($items as $row) {
echo $row["item"].'<br>';
}
there are two scenarios:
if you want to parse JSON object, then
$items = json_decode($data); // instead of $items = explode(',', $data);
if you want to treat data as a strings then
echo $row[0].'<br>'; // instead of echo $row->item.'<br>';

Undefined variable: data in laravel

Undefined variable: data error occure when i want to display data from database.
Here is my code
Controller
public function filter(Request $request)
{
$data = Trial::where('zipcode',$request->zipcode)->select('lat','lng')->first();
$lat = $data->lat;
$lng = $data->lng;
$distance = 5 ;// Diatanse in kms
$query = Trial::getByDistance($lat, $lng, $distance);
$ids = [];
//Extract the id's
if(!empty($query)) {
foreach($query as $q)
{
array_push($ids, $q->id);
}
}
// Now write final query
if(!empty($ids)){
$results = DB::table('trial')->whereIn( 'id', $ids)->where('zipcode');
}
return view('search.searchhome',compact('data',$data));
dd($data);
}
Blade
<p>
#foreach($data as $dat)
{{$dat->zipcode}}
#endforeach
</p>
Change in controller
public function filter(Request $request)
{
$data = Trial::where('zipcode',$request->zipcode)->select('lat','lng')->first();
$lat = $data->lat;
$lng = $data->lng;
$distance = 5 ;// Diatanse in kms
$query = Trial::getByDistance($lat, $lng, $distance);
$ids = [];
//Extract the id's
if(!empty($query)) {
foreach($query as $q)
{
array_push($ids, $q->id);
}
}
// Now write final query
if(!empty($ids)){
$results = DB::table('trial')->whereIn( 'id', $ids)->get();
}
return view('search.searchhome',['data' => $results]);
}
Change in blade
<p>
#foreach($data as $dat)
{{$dat->zipcode}}
#endforeach
</p>
You have a few errors in your code.
if(!empty($ids)){
$results = DB::table('trial')->whereIn( 'id', $ids)->get();
}
Removed the ->where(), the where clause had no condition.
Added the get(), otherwise the query wont return any results.
return view('search.searchhome',compact('results'));
changed data to results as that contains your data.
dd($data);
remove the dd(), this does nothing as the function returns before it.
(I would also suggest to look into collections, instead of looping over the first result set)

how to send this data from local storage to php online using jquery

This is my php codes to received and insert the data into the online database. I am very sure i these fabricated codes will not work but with you education and help i will get. thank you. insertdata.php
<?php
include 'connect.php';
include 'function.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["usersJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storedata($data[$i]->callid,$data[$i]->pid,$data[$i]->pname,$data[$i]->medstay_amt,$data[$i]->med_amt,$data[$i]->imv_amt,$data[$i]->othermc_amt,$data[$i]->emtrans_amt,$data[$i]->outpden_am,$data[$i]->otherps_amt,$data[$i]->herb_amt,$data[$i]->medban_amt,$data[$i]->othermp_amt,$data[$i]->assist_amt,$data[$i]->code,$data[$i]->date);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->pid;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->pid;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>
You can do something like this:
$(document).on("click", ".BTN_Submit_Task", function () {
var AllTasks = ls.GetAllArr(LocalstorageName);
var id = $(this).attr("rec_id");
var result = $.grep(AllTasks, function(e){ return e.rec_id === id; });
$.ajax({
url: "url/of/php/file.php",
type: 'post',
dataType: 'json',
data: {usersJSON: [result]},
done: function(response) {
console.log(response);
}
});
});
And BTW you probably want to make AllTasks variable global and assign it once, then you can call it from both functions.

AJAX : Getting two different JSON variable from php using ajax

I am need to directly get the variable from the response.php which contains the needed value. How can I the filter that JSON variable separately? Or if i merge both array into 1 JSON call then how do i get the different value
AJAX
function getMaleRanking(){
var mr = 'maleRangking';
var mf = 'femaleRangking';
$.ajax({
url : 'ajax/ajax_drill.php',
type : 'post',
cache : false,
data :{ mr : mr , mf : mf , event_id : event_id},
success:function(data){
var rankings = data;
//get the first json
//get the sencod json
}
});
}
getMaleRanking();
My php
echo json_encode(resultMergeMale, JSON_NUMERIC_CHECK);
echo json_encode(resultMergeFem, JSON_NUMERIC_CHECK);
You have to give response in json format for fetching valued in multiple paramater. Your php code should be
$response=array('mr'=>'','mf'=>'');
if(isset($_POST['mr'])){
foreach ($resultMergeMale as $key => $value) {
$firstval = $value;
//get this first val
$response['mr'] . =$firstval;
}
}
if(isset($_POST['mf'])){
foreach ($resultMergeFem as $key => $value) {
$secondval = $value
//get this seaond val
$response['mf'] .= $secondval ;
}
}
echo json_encode($response);
die();
You have to pass dataType:'json', so Jquery automatically convert JSON string into JSON object and you can access by its property. Your Ajax code should be
function getMaleRanking(){
var mr = 'maleRangking';
var mf = 'femaleRangking';
$.ajax({
url : 'ajax/ajax_drill.php',
type : 'post',
cache : false,
dataType:'json',
data :{ mr : mr , mf : mf , event_id : event_id},
success:function(data){
alert(data.mr);
alert(data.mf);
}
});
}
getMaleRanking();
Comma delimit the values, like this
if(isset($_POST['mr'])){
foreach ($resultMergeMale as $key => $value) {
$firstval = $value;
//get this first val
}
}
if(isset($_POST['mf'])){
foreach ($resultMergeFem as $key => $value) {
$secondval = $value
//get this seaond val
}
}
echo $firstval.",".$secondval
And then in your Ajax call,
success:function(data){
var rankings = data.split(",");
var firstval = rankings[0];
var secondval = rankings[1];
//your logic here
}

how to read a muiltidimensional associative array passed from php to ajax jQuery?

I'm devoloping a site that retrieve information about user location (name,lat,lng,address..) from a database with an ajax request performed with jQuery. I have fetched all the results into an associative arrays
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$conn = mysql_connect($servername,$username,$password);
if(!$conn){
die('Could not connect' .mysql_error());
}
mysql_select_db($dbname);
$query = " SELECT * FROM userevent ";
$result = mysql_query($query);
$a = array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
array_push($a,$row);
}
echo json_encode($a);
mysql_close($conn);
After fetching i get this type of array :
Array
(
[0] => Array
(
[ID] => 3823
[name] => Erik
[lat] => 63.2994
[lng] => 23.7497
[title] => b
)
[1] => Array
(
[ID] => 3824
[name] => George
[lat] => 43.2994
[lng] => 13.4494
[title] => a
)
)
in my .js file i have this :
function loadmap(){
$.ajax ({
url:'loaddata.php',
dataType:'json',
success: function(data){
alert(""+data[0]); //DOESN'T WORK ???????
},
})
}
How can I read my array now ?
data is likely coming back as a string, you can use JSON.parse to turn it into JSON.
function loadmap(){
$.ajax ({
url:'loaddata.php',
dataType:'json',
success: function(data){
data = JSON.parse(data);
alert(""+data[0]);
},
})
}
Heads up : Use print_r() function for printing out the output of
json_encode() php predefined function instead of the native echo.
PHP updated code
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$conn = mysql_connect($servername,$username,$password);
if(!$conn){
die('Could not connect' .mysql_error());
}
mysql_select_db($dbname);
$query = " SELECT * FROM userevent ";
$result = mysql_query($query);
$a = array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
array_push($a,$row);
}
print_r(json_encode($a));
mysql_close($conn);
You don't need to parse the array in the clientside if you are already using json_encode function. You can Access the array values as a normal javascript
object using the dot(.) operator.
Javascript Updated code snippet
function loadmap(){
$.ajax ({
url:'loaddata.php',
dataType:'json',
success: function(data){
alert(data.ID); //this one will print the value of ID key in the array
},
})
}

Categories

Resources