How to string replace a symbol from array and split? - javascript

I have
$dataSavedBlocks = get_user_meta( $user_id, 'jsonBlock');
var_dump($dataSavedBlocks);
Which gives:
array(1) { [0]=> string(534) "{"date":"3/25/20","ricoverati_con_sintomi":999,"terapia_intensiva":251,"totale_ospedalizzati":1250,"isolamento_domiciliare":1526,"totale_attualmente_positivi":2776,"nuovi_attualmente_positivi":257,"dimessi_guariti":54,"deceduti":142,"totale_casi":2972,"tamponi":17868} | ,{"date":"3/25/20","ricoverati_con_sintomi":82,"terapia_intensiva":19,"totale_ospedalizzati":101,"isolamento_domiciliare":311,"totale_attualmente_positivi":412,"nuovi_attualmente_positivi":17,"dimessi_guariti":12,"deceduti":18,"totale_casi":442,"tamponi":3019} | " }
I tried:
$dataSavedBlocks = get_user_meta( $user_id, 'jsonBlock');
$dataCustom = implode("| ,", $dataSavedBlocks[0]);
$dataCustom = str_replace("| ,",",",$dataCustom);
$dataCustom = explode(",", $dataCustom);
var_dump($dataCustom);
I get:
Warning: implode(): Invalid arguments passed in ...
array(1) { [0]=> string(0) "" }
I need a correct json to parse it in js:
var customJsonData = JSON.parse('<?php echo $dataCustom; ?>');
But I have | , as a separator and I cannot exclude it for other reasons when I save it. What am I doing wrong?

All you need to do is to replace | with an empty string and to wrap the result in square brackets:
$jsonBlock = '{"date":"3/25/20","ricoverati_con_sintomi":999,"terapia_intensiva":251,"totale_ospedalizzati":1250,"isolamento_domiciliare":1526,"totale_attualmente_positivi":2776,"nuovi_attualmente_positivi":257,"dimessi_guariti":54,"deceduti":142,"totale_casi":2972,"tamponi":17868} | ,{"date":"3/25/20","ricoverati_con_sintomi":82,"terapia_intensiva":19,"totale_ospedalizzati":101,"isolamento_domiciliare":311,"totale_attualmente_positivi":412,"nuovi_attualmente_positivi":17,"dimessi_guariti":12,"deceduti":18,"totale_casi":442,"tamponi":3019} | ';
$json = '[' . str_replace(' | ', '', $jsonBlock) . ']';
var_dump($json);
The result would be:
string(530) "[{"date":"3/25/20","ricoverati_con_sintomi":999,"terapia_intensiva":251,"totale_ospedalizzati":1250,"isolamento_domiciliare":1526,"totale_attualmente_positivi":2776,"nuovi_attualmente_positivi":257,"dimessi_guariti":54,"deceduti":142,"totale_casi":2972,"tamponi":17868},{"date":"3/25/20","ricoverati_con_sintomi":82,"terapia_intensiva":19,"totale_ospedalizzati":101,"isolamento_domiciliare":311,"totale_attualmente_positivi":412,"nuovi_attualmente_positivi":17,"dimessi_guariti":12,"deceduti":18,"totale_casi":442,"tamponi":3019}]"
const json = JSON.parse('[{"date":"3/25/20","ricoverati_con_sintomi":999,"terapia_intensiva":251,"totale_ospedalizzati":1250,"isolamento_domiciliare":1526,"totale_attualmente_positivi":2776,"nuovi_attualmente_positivi":257,"dimessi_guariti":54,"deceduti":142,"totale_casi":2972,"tamponi":17868},{"date":"3/25/20","ricoverati_con_sintomi":82,"terapia_intensiva":19,"totale_ospedalizzati":101,"isolamento_domiciliare":311,"totale_attualmente_positivi":412,"nuovi_attualmente_positivi":17,"dimessi_guariti":12,"deceduti":18,"totale_casi":442,"tamponi":3019}]');
console.log(json);

JS can handle the string
const str = `{"date":"3/25/20","ricoverati_con_sintomi":999,"terapia_intensiva":251,"totale_ospedalizzati":1250,"isolamento_domiciliare":1526,"totale_attualmente_positivi":2776,"nuovi_attualmente_positivi":257,"dimessi_guariti":54,"deceduti":142,"totale_casi":2972,"tamponi":17868} | ,{"date":"3/25/20","ricoverati_con_sintomi":82,"terapia_intensiva":19,"totale_ospedalizzati":101,"isolamento_domiciliare":311,"totale_attualmente_positivi":412,"nuovi_attualmente_positivi":17,"dimessi_guariti":12,"deceduti":18,"totale_casi":442,"tamponi":3019} | " }`
.replace(/\|/g,"").replace(/ " }/,"")
console.log(JSON.parse("["+str+"]"))

This is what I had to do and worked
<?php
$user_id = get_current_user_id();
$dataSavedBlocks = get_user_meta( $user_id, 'jsonBlock');
$dataCustom = json_encode($dataSavedBlocks[0]);
$dataCustom = str_replace('|', '', $dataCustom);
$dataCustom = stripslashes($dataCustom);
?>
js
var myJson = '<?php echo $dataCustom; ?>';
var result = myJson.substring(1, myJson.length-1);
var customJsonData = JSON.parse("["+result+"]");

Related

How can I get similar count of data

I want to get set if statement of no. of count of array from database. I already have a if statement checking the count but I am unable to use it in my file.
Help me replicate the count if statement here. I want to wrap pro_type and is_pro in if statement of no. of counts similar in reaferandearn page .
My function where I need if count statement :
users.php file
public function update_valid_refer_point($id){
global $db;
$user_balance = $db->where('id',$id)
->getOne('users',array('balance'));
$_POST['pro_type'] =4;
$_POST['is_pro'] =1;
$bal =$user_balance['balance']+500;
$updated = $db->where('id', $id)
->update('users', array('pro_type' => 4,'is_pro' => 1,'balance' => $bal));
return TRUE;
}
The file where I have similar if count statement but I have no idea how to use it above :
referandearn.php
if(count($data['refferal_data']['data']) > 0){
for($u=0; $u<count($data['refferal_data']['data']);$u++){
$userFirstName = $data['refferal_data']['data'][$u]->first_name;
$userLastName = $data['refferal_data']['data'][$u]->last_name;
$userName = $userFirstName.' '.$userLastName;
$userProfilePhoto = $data['refferal_data']['data'][$u]->avater;
$refferalDate = date('d - M - Y',strtotime($data['refferal_data']['data'][$u]->refferalDate));
$userRefferalCode = $data['refferal_data']['data'][$u]->refferalCode;
?>
<li>
<img src="<?php echo $userProfilePhoto;?>" width="75" height="75" viewBox="0 0 24 24" style="margin-right: 15px; border-radius: 50%;"/>
<?php echo $userName."<br>".$refferalDate;?>
</li>
<?php
}
}else{
?>
<li>
<?php echo 'No reffered user yet';?>
</li>
<?php
}
?>
referandearn controller :
Class Referearn extends Theme {
public static function LoadreffralUsers() {
global $_AJAX, $_CONTROLLERS;
$data = '';
$ajax_class = realpath($_CONTROLLERS . 'aj.php');
$ajax_class_file = realpath($_AJAX . 'loadmore.php');
if (file_exists($ajax_class_file)) {
require_once $ajax_class;
require_once $ajax_class_file;
$_POST['page'] = 1;
$loadmore = new Loadmore();
$refferal_users = $loadmore->refferal_users();
parent::$data['refferal_data'] = $refferal_users;
/*if (isset($refferal_users['html'])) {
$data = $refferal_users['html'];
}*/
}
return $data;
}
}
And loadmore referusers function :
function refferal_users() {
global $db, $_BASEPATH, $_DS,$_excludes;
if (self::ActiveUser() == NULL) {
return array(
'status' => 403,
'message' => __('Forbidden')
);
}
$error = '';
$page = 0;
$perpage = 7;
$html = '';
$html_imgs = '';
$template = '';
if (isset($_POST) && !empty($_POST)) {
if (isset($_POST[ 'page' ]) && (!is_numeric($_POST[ 'page' ]) || empty($_POST[ 'page' ]))) {
$error = '<p>• ' . __('no page number found.') . '</p>';
} else {
$page = (int) Secure($_POST[ 'page' ]) - 1;
}
}
if ($error == '') {
$limit = $perpage;
$offset = $page * $perpage;
//$query = GetRefferalUserQuery(self::ActiveUser()->id, $limit, $offset);
//exit;
//$refferal_users = $db->rawQuery($query);
$sql = 'SELECT U.id,U.online,U.lastseen,U.username,U.avater,U.country,U.first_name,U.last_name,U.location,U.birthday,U.language,U.relationship,U.height,U.body,U.smoke,U.ethnicity,U.pets,U.gender, RU.refferalDate, RU.refferalCode FROM users U INNER JOIN refferalusers RU ON RU.refferalBy = U.id ';
$sql .= ' WHERE RU.refferalTo = '.self::ActiveUser()->id.' AND ( ';
$sql .= ' U.verified = "1" AND U.privacy_show_profile_random_users = "1" ';
// to exclude blocked users
$notin = ' AND U.id NOT IN (SELECT block_userid FROM blocks WHERE user_id = '.self::ActiveUser()->id.') ';
// to exclude liked and disliked users users
$notin .= ' AND U.id NOT IN (SELECT like_userid FROM likes WHERE ( user_id = '.self::ActiveUser()->id.' OR like_userid = '.self::ActiveUser()->id.' ) ) ';
$sql .= ' ) ';
$sql .= ' ORDER BY U.id DESC LIMIT '.$limit.' OFFSET '.$offset.';';
$random_users = $db->objectBuilder()->rawQuery($sql);
$theme_path = $_BASEPATH . 'themes' . $_DS . self::Config()->theme . $_DS;
//$template = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'random_users.php';
//$template1 = $theme_path . 'partails' . $_DS . 'find-matches' . $_DS . 'matches_imgs.php';
if (file_exists($template)) {
foreach ($random_users as $random_user) {
if($random_user->id!=(int)auth()->id){
ob_start();
require($template);
$html .= ob_get_contents();
ob_end_clean();
}
}
}
return array(
'status' => 200,
'page' => $page + 2,
'html' => $html,
'data' => $random_users
);
} else {
return array(
'status' => 400,
'message' => $error
);
}
}

How to pass variables in a url using javascript and receive them using php?

What I am trying to do is to pass in variables from javascript to a php file using the url. The php is suppose to then parse the url into a json string and then store the json string on a separate text file. The php will then return the json string to the javascript for it to display. After a lot of testing I do believe my code isn't opening the php file or the php isn't parsing the url correctly.
here is the javascript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
obj = this.responseText;
var data = JSON.parse(obj);
alert(data);
txt += "<tr><th>Student Id</th><th>Student Name</th><th>Type</th></tr>";
for (x in data.student){
txt += "<tr><td>" + data.student[x].id + "</td>";
txt += "<td>" + data.student[x].lname + ", " + data.student[x].fname + "</td>";
txt += "<td>" + data.student[x].type + "</td></tr>";
}
document.getElementById("display").innerHTML = txt;
}
xhttp.open("GET", "assign13.php?type="+type+"&fname="+fname+"&lname="+lname+"&id="+id+"&fname2="+fname2+"&lname2="+lname2+"&id2="+id2, true);
xhttp.send();
alert("all done");
}
Here is the php file:
<?php
class student{
public $type;
public $fname;
public $lname;
public $id;
function setAll($type, $fname, $lname, $id){
$this->$fname = $fname;
$this->$type = $type;
$this->$lname = $lname;
$this->$id = $id;
}
}
$s1 = new student();
$s2 = new student();
$type = $_GET["type"];
$fname = $_GET["fname"];
$lname = $_GET["lname"];
$id = $_GET["id"];
$f2 = $_GET["fname2"];
$l2 = $_GET["lname2"];
$i2 = $_GET["id2"];
$s1->setAll($type, $fname, $lname, $id);
$s2->setAll($type, $f2, $l2, $i2);
if ($type == "duet"){
$directory = array($s1, $s2);
}
else{
$directory = array($s1);
}
$str = json_encode($directory);
file_put_contents("../data/data.txt", $str);
echo $str;
?>
You have errors on your php class, it should be like this.....
<?php
class student{
public $type;
public $fname;
public $lname;
public $id;
function setAll($type, $fname, $lname, $id){
$this->fname = $fname;
$this->type = $type;
$this->lname = $lname;
$this->id = $id;
}
function getAll(){
return [
'fname' => $this->fname,
'type' => $this->type,
'lname' => $this->lname,
'id' => $this->id,
];
}
}
$s1 = new student();
$s2 = new student();
$type = "A";
$fname = "B";
$lname = "C";
$id = "12";
$f2 = "Test";
$l2 = "Test";
$i2 = "10";
$s1->setAll($type, $fname, $lname, $id);
$s2->setAll($type, $f2, $l2, $i2);
if ($type == "duet"){
$directory = array($s1->getAll(), $s2->getAll());
}
else{
$directory = array($s1->getAll());
}
$str = json_encode($directory);
echo $str;
?>

php "||" assignment logic compared to Javascript

I was testing Heredoc and || functionality
function test()
{
$obj = [(object)['col1'=>'val1'],
(object)['col2'=>'val2'],
(object)['col3'=>'val3']];
$output = '';
$mystring = <<<EOT
a non empty string
EOT;
foreach($obj as $prop)
{
foreach($prop as $i)
{
$output .= <<<EOT
<div style='background-color:lightblue'>
\$head : {gettype($i)}
</div>
EOT;
}
}
$out = $output || $mystring || 'couldn\'t find something valuable';
echo $out;
}
test();
I get the output of
1
which represents a Boolean true.
I had it output the contents of $mystring at one point by putting the logic in brackets eg
echo ($output || $mystring);
and it used to output:
a non empty string
It stopped working straight after and I am not sure what change broke it.
In javascript:
function test()
{
var obj = [{'col1':'val1'},
{'col2':'val2'},
{'col3':'val3'}];
var output = '';
var mystring ="a non empty string";
for(var prop in obj)
{
for(var i in prop)
{
output +=
"<div style='background-color:lightblue'>" +
i + " : " + typeof prop[i] +
"</div>";
}
}
out = output || mystring || 'couldn\'t find something valuable';
document.write(out);
console.log("outputting \n\t" + out);
}
test();
It is slightly different from the php in terms of logic but the || during assignment works as expected. I get
0 : string
0 : string
0 : string
for the code above. If comment out the inner for loop like so
for(var prop in obj)
{
/*for(var i in prop)
{
output +=
"<div style='background-color:lightblue'>" +
i + " : " + typeof prop[i] +
"</div>";
}*/
}
I get the contents of "mystring" which is
a non empty string
and if I then change mystring to an empty string like so
mystring = ""; //"a non empty string";
I get
couldn't find something valuable
How does php's "||" during assignment work ?
Can someone explain it?
If you assign a conditional expression in php you always get a boolean (that is, strictly true or false), it does not work as in javascript where the "truthy" value gets assigned, so in PHP
$a = "";
$b = 42;
$c = ($a || $b); // == true
While in javascript
var a = "";
var b = 42;
var c = (a || b); // == 42
and this is, sadly, by language design.
As #billyonecas reports, it is also in the comments to the docs: http://php.net/manual/en/language.operators.logical.php#77411
To obtain a similar behaviour in PHP, we must do something like:
$a = "";
$b = 42;
$c = ($a ?: $b); // newer php version
$c = ($a ? $a : $b); // older php version
if you need to concatenate expression, use parethesis:
$c = ($a ? $a : ($b ? $b : "not found"));
With PHP, you can use ?:
$out = $output ?: $mystring;
Or in older versions of PHP:
$out = $output ? $output : $mystring;
You can also use empty() to get a more explicit code:
$out = empty($output) ? $mystring : $output;
http://php.net/manual/en/function.empty.php
Note: these ternary expressions are equivalent to if-else:
if(empty($output))
{
$out = $mystring;
}
else
{
$out = $output;
}
With nested ternary, add parentheses, as the default precedence is:
$out = $output ? $output : $mystring ? $mystring : 'default';
This is:
$out = ($output ? $output : $mystring) ? $mystring : 'default';
So you must do:
$out = $output ? $output : ($mystring ? $mystring : 'default');

Unable to insert Ajax return into HTML

I'm trying to use a PHP file to process serialized info from an Ajax request. I want to send back the value of each form field to be further manipulated by javascript (inserted into a div). The result is not being inserted into the HTML. When I alert the result I get {"return":["<p>form value for name<\/p>","<p>form value for description<\/p>"]} Any suggestions?
EDIT: Updated question with relevant HTML and revised PHP code.
HTML:
<div class="col-md-4">
<h5>Heading</h5>
<div id="formBasicResults"></div>
</div>
Javascript:
.on('success.form.fv', function (e) {
e.preventDefault();
var $form = $(e.target);
var bv = $form.data('formValidation');
$.post($form.attr('action'), $form.serialize())
.done(function (result) {
$('#formBasicResults').html(result.responseText);
alert(result);
},'json');
});
PHP:
if (!isset($_SESSION)) {
session_start();
if (!isset($_SESSION['token'])) {
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();
} else {
$token = $_SESSION['token'];
}
}
foreach($_POST as $key = > $value) {
$temp = is_array($value) ? $value : trim($value);
$_SESSION[$key] = $temp;
}
$expected = array(
'name' = > 'string',
'description' = > 'string',
);
foreach($expected AS $key) {
if (!empty($_POST[$key])) {
$ {$key} = $_POST[$key];
} else {${$key} = NULL;
}
}
foreach($expected AS $key = > $type) {
if (empty($_POST[$key])) {
$ {$key} = NULL;
continue;
}
if (!isset($ {
$key})) {
$ {$key} = NULL;
}
}
function safe( $value ) {
htmlentities( $value, ENT_QUOTES, 'utf-8' );
return ($value);
}
$name = $_POST['name'];
$description = $_POST['description'];
$return['result']=array();
if(!empty($name)){$return['result'][]= '<p>' . safe($name) . '</p>';}
if(!empty($description)){$return['result'][]= '<p>' . safe($description) . '</p>';}
echo json_encode($return);
try something like this:
$('#formBasicResults').html(result['return'][0]);
or
$('#formBasicResults').html(result['return'][1]);
Instead of this:
if ($_POST['token'] == $_SESSION['token'])
{$return['return']=array();
if(!empty($_POST['name'])){$return['return'][] = '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>';
if(!empty($_POST['description'])){$return['return'][] = '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
echo json_encode($return); }}
do this:
$return['responseText']='';
if ($_POST['token'] == $_SESSION['token'])
{
if(!empty($_POST['name'])){
$return['responseText'] .= '<p>' . htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8') . '</p>';
if(!empty($_POST['description'])){
$return['responseText'] .= '<p>' . htmlentities($_POST['description'], ENT_QUOTES, 'UTF-8') . '</p>';}
}
}
echo json_encode($return);

getting dynamically created XML values with AJAX in js file

I have created a dynamic xml file with php as follows
('Content-Type: text/xml');?>
<?php $newitem = $_GET["book"];
$action = $_GET["action"];
$qty=0;
$isbnVal="XYZ";
if ($_SESSION["Cart"] != ""){
$MDA = $_SESSION["Cart"];
if ($action == "Add"){
if ($MDA[$newitem] != ""){
$tempValue = $MDA[$newitem];
$value=$tempValue["qty"]+1;
$MDA[$newitem] =array("qty" => $value,"isbn" => $isbnVal);
}else{$MDA[$newitem] =array("qty" => 1,"isbn" => $isbnVal);}
}else{$MDA= "";}
}
else{$MDA[$newitem] =array("qty" => 1,"isbn" => $isbnVal);}
$_SESSION["Cart"] = $MDA;
ECHO (toXml($MDA));
function toXml($MDA){
$doc = new DomDocument('1.0');
$cart = $doc->createElement('cart');
$cart = $doc->appendChild($cart);
foreach ($MDA as $a => $b){
//echo "isbn".$b["isbn"];//echo "qty".$b["qty"]; $book = $doc->createElement('book');
$book = $cart->appendChild($book);
$title = $doc->createElement('title');
$title = $book->appendChild($title);
$value = $doc->createTextNode($a);
$value = $title->appendChild($value);
$quantity = $doc->createElement('quantity');
$quantity = $book->appendChild($quantity);
$value2 = $doc->createTextNode($b["qty"]);
$value2 = $quantity->appendChild($value2);
$isbn = $doc->createElement('isbn');
$isbn = $book->appendChild($isbn);
$value3 = $doc->createTextNode($b["isbn"]);
$value3 = $isbn->appendChild($value3);
}
$strXml = $doc->saveXML();
return $strXml;
}
then I'm calling these values in a javaScript file to display. I can get the first and last values from firstChild and lastChild. But I can't get whatever is in the middle. I tried it as follows.
spantag.innerHTML += " " +header[0].firstChild.textContent;
spantag.innerHTML += " " +header[0].getElementsByTagName('qty');
spantag.innerHTML += " " + header[0].lastChild.textContent + " <a href='#' onclick='AddRemoveItem(\"Remove\");'>Remove Item</a> ";
only the second code is not working. Plz tell me what I did wrong.Thanx in advance.

Categories

Resources