Merge two arrays into one continually gives me error in php - javascript

for a wordpress-based real estate ad client site I have developed a system for sending advertisements via e-mail to subscribed clients.
To avoid sending the same advertisement several times, I have created a flag system that highlights whether the advertisement has already been sent or not.
To register the advertisements sent, I use the ID and in a specific column I go to register the IDs of the advertisements selected with a checkbox, the data is transferred through a javascript function.
Here the jquery section code:
var checkboxVals = $('.listing_multi_id'); // This for id of post(advert) checked
var email_to = $('#lead_email').val(); // This tell me the email to send.
var lead_id = $('#lead_id').val(); // This tell me the col ID in DB of my client
var already_ID = $('#annunci_inviati').val(); //This tells me which ids are already present in the database row as sent
var vals = $('.listing_multi_id:checked').map(function() {return this.value;}).get().join(',') // This create array of ids of post(advert) checked
// And all information is sent through json post
$.ajax({
type: 'POST',
dataType: 'json',
url: ajaxurl,
data: {
'action': 'houzez_match_listing_email',
'ids': vals,
'email_to': email_to,
'id_lead': lead_id,
'already_inviati': already_ID,
},''''
Here the php section code:
// I have omitted all the information that does not concern the question, the function I am using is much more complex and structured than the one you see
$listing_ids = sanitize_text_field($_REQUEST['ids']); // Array with the ids of post
$already_inviati1 = sanitize_text_field($_REQUEST['already_inviati']); // Array with the ids of post already sent
// Here transform the array in array with INT ids
$strings_array = explode(',', $already_inviati1);
foreach ($strings_array as $each_number=>$id) {
$already_inviati2[] = $id;
}
// up to here
// Here check if the is the first sent or not
if (isset($already_inviati1)) {
$merged = array_merge($already_inviati2,$listing_ids);
$annunci_inviati = maybe_serialize($merged);
} else
{$annunci_inviati = maybe_serialize($listing_ids);}
// Here save the value in database
$id_cliente = $_POST['id_lead'];
$data_table= $wpdb->prefix . 'crm_enquiries';
$data = array(
'annunci_inviati' => $annunci_inviati
);
$format = array(
'%s'
);
$where = array(
'lead_id' => $id_cliente
);
$where_format = array(
'%d'
);
$wpdb->update( $data_table, $data, $where, $format, $where_format );
// FINE SCRIPT
As you can see, the script works if it is the first sending of the mails, so if the column is empty.
On the second send, it goes into error, the array is merged but when I go to check its value it becomes this:
// I use a hidden input in html to check ids already sent
<input type="hidden" id="annunci_inviati" value="array (
0 => 0, // Old IDs are lost by becoming numbers
1 => 1, // Old IDs are lost by becoming number
2 => 2, // Old IDs are lost by becoming number
3 => 0, // Old IDs are lost by becoming number
4 => 53161, // the new id selected
5 => 53153, // the new id selected
6 => 53144, // the new id selected
)">
How can I solve?

You are trying to merge a string with an array. Try the below which ensures the input values are correctly converted to arrays.
/**
* #var array Array of listing ID's.
*/
$listing_ids = !empty( $_REQUEST[ 'ids' ] ) ? array_map( 'intval', explode( ',', $_REQUEST[ 'ids' ] ) ) : [];
/**
* #var array Array of ID's for post already sent.
*/
$already_sent = !empty( $_REQUEST[ 'already_inviati' ] ) ? array_map( 'intval', explode( ',', $_REQUEST[ 'already_inviati' ] ) ) : [];
/**
* #var array Merge the listing ID's and already sent ID's for storing.
*/
$merged = array_unique( array_merge( $listing_ids, $already_sent ) );
/**
* #var int|null The client record to update.
*/
$id_cliente = !empty( $_POST[ 'id_lead' ] ) ? (int)$_POST[ 'id_lead' ] : null;
if ( $id_cliente ) {
$data_table = $wpdb->prefix . 'crm_enquiries';
$wpdb->update( $data_table, [
'annunci_inviati' => maybe_serialize( $merged )
], [
'lead_id' => $id_cliente
], [
'%s'
], [
'%d'
] );
}

Related

laravel array data fill into google chart

Here is my array fetched from database. I need to that array data fill into google data chart. I tried few ways but I couldn't do that. please some one help me to do that.
code// dd($dates);
here dataTable.addRows section I need to replace, 1st picture displaying dataList.
please help me.
viewerController.php
public function show(){
$dates = collect();
foreach( range( -6, 0 ) AS $i ) {
$date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
$dates->put( $date, 0);
}
// Get the post counts
$persons = Person::where( 'created_at', '>=', $dates->keys()->first() )
->groupBy( 'date' )
->orderBy( 'date' )
->get( [
DB::raw( 'DATE( created_at ) as date' ),
DB::raw( 'COUNT( * ) as "count"' )
] )
->pluck( 'count', 'date' );
// Merge the two collections; any results in `$posts` will overwrite the zero-value in `$dates`
$dates = $dates->merge( $persons );
return view('layouts.chart',compact(['dates']));
}

How to render multiple row in a cell in Datatables from a different table?

I am creating a table using datatables and I am having some trouble rendering data in it. My Table structures are.
TABLE_1
|------|------|-------|
| ID | NAME | PHONE |
|------|------|-------|
TABLE_2
|------|------------|----------|
| ID | TABLE_1_ID | CATEGORY |
|------|------------|----------|
This is my PHP code
$db = new Database; // Database connection
$sql = "SELECT a.*, b.* FROM TABLE_1 a, TABLE_2 b WHERE a.ID = b.TABLE_1_ID";
$exe = $db->select($sql);
$result = array();
foreach ($exe as $rows) {
$result[] = $rows;
}
echo json_encode($result);
This is my JavaScript
$('#example').DataTable({
ajax: {
url:"data.php",
dataSrc:""
},
columns: [
{data:"NAME"},
{data:"CATEGORY"}
]
});
Up to this point everything is working fine, the data is perfectly loaded. But the problem is, suppose I have only one row in TABLE_1 and 5 rows in TABLE_2 where TABLE_1.ID = TABLE_2.TABLE_1_ID and bcoz of this my datatable is generating 5 rows but I want all the categories in a single cell and I want only one row instead of 5.
I am thinking of doing some stuff inside the render function, like
$('#example').DataTable({
ajax: {
url:"data.php",
dataSrc:""
},
columns: [
{data:"NAME"},
{
data:"ID",
render: function(data, type, row){
// Some stuff to render 5 Category in a single cell
// Using the ID from row.ID (maybe)
// how to return 5 CATEGORY in this cell
}
}
]
});
But I really don't know the process and google + stackoverflow + datatables forum is little bit confusing for me bcoz I am not good in Javascript.
Can you guys help me achieve this? What type of code or what code I have to write inside the render finction to display 5 CATEGORY in a single cell.
Thanks in advance.
You can transform your data in your application layer so that in resultant array you will have only rows for table a along with related category names.
First you need an ordered result set like
select a.id,
a.phone,
a.name,
b.category
from table_1 a
join table_2 b
on a.id = b.table_1_id
order by a.id asc
Then loop through all records and cook your data set
$result = [];
$currentParent = false;
$data = null;
foreach ($rows as $row) {
/*
* if id is changed then its a different record
* prepare data for new row and create a comma separated string of category names
*/
if ($currentParent != $row['id']) {
if($data != null){ // for first and intermediate rows
$result[]= $data;
}
$data = ['name'=> $row['name'], 'category'=> ''];
$currentParent = $row['id'];
}
$data['category'] = empty($data['category']) ? $row['category']: $data['category'] .", ". $row['category'];
}
$result[]= $data; // add data for last row
echo json_encode($result);
The resultant array would look like
Array
(
[0] => Array
(
[name] => item 1
[category] => Cat 1, Cat 2, Cat3
)
[1] => Array
(
[name] => item 2
[category] => Cat 1, Cat 2, Cat3
)
[2] => Array
(
[name] => item 3
[category] => Cat 1, Cat 2, Cat3
)
)
Another shorthand way but not preferred is to apply aggregate methods on query level like if you are using MySQL you can use group_concat but it has a restriction of max character limit (which is adjustable).

How to parse a JSON data that has been received by a PHP scipt

I have sent data from my php script using `json_encode' function.
if I console.log(resp) below is the O/P I get.
data: "{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}" status: "success"
however, if I console.log(resp.data) I get the below data
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}
Now I'm trying to display this data in the data tables for which I am using the below code.
$('#grpList').DataTable().row.add([
resp.data.dept_name,
resp.data.city_name,
resp.data.emp_id,
resp.data.emp_name
]).draw(false);
I'm receiving the following error
DataTables warning: table id=grpList - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
when I am single handed displaying only console.log(resp.data.dept_name) it says undefined
I'll be having multiple JSON response if the data increases, for now, I only have two. I'm not able to figure out how to display multiple data using a loop and appending it to the data table.
I'm using below php code to generate JSON
$jsonArray = "";
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$jsonArray .= json_encode(
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
Because resp.data is an array of objects. You need to get the index first - let's say index 0, or the first object in the array:
$("#grpList").DataTable().row.add([
resp.data[0].dept_name,
resp.data[0].city_name,
resp.data[0].emp_id,
resp.data[0].emp_name
]).draw(false);
And if you want the second object:
$("#grpList").DataTable().row.add([
resp.data[1].dept_name,
resp.data[1].city_name,
resp.data[1].emp_id,
resp.data[1].emp_name
]).draw(false);
Of course, row.add() accepts an array argument as well - so this would work too:
$("#grpList").DataTable().row.add(resp.data).draw(false);
The issue is on server side.
You define $jsonArray as a string ! That's wrong.
Try this instead:
$jsonArray = []; // An ARRAY here!
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
array_push($jsonArray, json_encode( // Use array_push here
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
EDIT
I don't if the above works... Since I did not test it.
But here's how I would have writen it (I guess you'll have more chances with it):
$jsonArray = [];
if($data->num_rows > 0) {
while($row = $data->fetch_assoc()) {
// A temp array to rename the one of the keys...
$tempArray = [];
$tempArray = ["dept_name"] = $row['department_name'];
$tempArray = ["city_name"] = $row['city_name'];
$tempArray = ["emp_id"] = $row['emp_id'];
$tempArray = ["emp_name"] = $row['name'];
// Push to the jsonArray now...
array_push($jsonArray,$tempArray);
}
// And finally the result array... To be json encoded
$result = [];
$result = ["status"] = "success";
$result = ["data"] = jsonArray;
echo json_encode($result);
}
Note that without renaming one key and if there's only 4 data per rows from the DB... You could have done array_push($jsonArray,$row); directly, without using the $tempArray.
So try this... AND then apply Jack's answer. ;)

Call array from php

If i want to call an array from php into typescript also in an array form how i can do it
this is my php code :
$AccessQuery = "SELECT name,lastname,phone,email
FROM user
INNER JOIN access ON id
WHERE id
$userQuery = mysqli_query($localhost, $AccessQuery) or trigger_error(mysql_error(), E_USER_ERROR);
while ($AccessQueryRow = mysqli_fetch_assoc($userQuery)) {
$AccessData[] = array(
'id' => $AccessQueryRow['id'],
'code' => $AccessQueryRow['code'],
);
};
$arr = array(
"user_access_details" => $AccessData,
);
echo json_encode($arr);
I try this in order to encoded and use each one as a variable in an array
var jsonData = JSON.parse(data);
what i really want is how i can put each menu_id in an array field :
arr= {id1,id2}
the same for the code
how i can put each menu_id in an array field : arr= {id1,id2}
If you only care about the ids, ignore the code values. Get the array of the shape you want in PHP.
while ($AccessQueryRow = mysqli_fetch_assoc($userQuery)) {
$AccessData[] = $AccessQueryRow['id'];
};
echo json_encode($AccessData);
On the client side:
var jsonData = JSON.parse(data);
The result will be the array of just ids.

ajax, json, external url load data

i have a problem, help please
i have 2 sites and i want send data each other
first site :
var site_adres = $(location).attr('href');
var myArray = site_adres.split('/');
var site_adi_al = myArray[2];
$.getJSON('xxx.com/site/admin.php?site_adres='+ site_adi_al +'',
{},
function (data) {
$.each( data, function ( i, val ) {
var id=val['id'];
var site_adi=val['site_adi'];
$(".site_adi").append('<li>'+id+' >> <a href="'+site_adi+'"
target="_blank">'+site_adi+'</a></li>');
});
second site:
$site_adi = $_GET["site_adi"];
/* query */
$query = mysql_query("SELECT * FROM site WHERE site_adi = '$site_adi'");
if ( mysql_affected_rows() ){
$row = mysql_fetch_object($query);
$json = array(
"id" => $row->id,
"site_adi" => $row->site_adi
);
}else{
$json["hata"] = "Nothing !";
}
header("access-control-allow-origin: *");
echo json_encode($json);
result zero, what is wrong, help please
You have two basic problems (aside from the security issues explained in the comments on the question).
You are sending site_adres but reading $_GET["site_adi"]. You can't use different names for the same thing without explicitly writing code to link them somehow.
You are looping over data with $.each( data, function ( i, val ) { as if it was an array of objects, but your PHP is only sending a single object (which isn't in an array). You should be accessing the properties of data directly and not using each or val.
You should set up CORS on your webservers to allow them to fetch data from each other, since you're using php, i'm gonna assume you're using apache:
Header set Access-Control-Allow-Origin "*"
replace the * with the ip adress of your other website and vice versa.

Categories

Resources