How to get Session value which is an array in JavaScript? - javascript

I have a session set in a php page which stores an array as follows:
firstpage.php
$_SESSION["Counts"]=$some_array;
echo print_r($_SESSION["Counts"]);
Output:
Array ( [Finance] => Array ( [0] => 0 [1] => 3 [2] => 0 [3] => 0 [4] => 1 )
[Human resources] => Array ( [0] => 1 [1] => 5 [2] => 1 [3] => 0 [4] => 0 )
[Infrastructure] => Array ( [0] => 0 [1] => 3 [2] => 1 [3] => 0 [4] => 0 ) ) 1
Retrieving the session data in .js page
SecondJSpage.js
<script type="text/javascript">
var sessionValue= new Array();
var s= new Array();
var s1= new Array();
sessionValue = '<?php $_SESSION["Counts"]; ?>';
document.write(sessionValue); //Does not output anything
for( s1 in sessionValue) {
for( s in s1) {
document.write(s); //Does not output anything
document.write("<br />");
}}
</script>
Only arrays are not being retrieved. A simple session variable is getting displayed. How to solve this problem?

change this line up a little bit..
sessionValue = <?php echo json_encode($_SESSION["Counts"]); ?>;

Use json_encode() for this purpose (Javascript can handle JSON).
Check the manual: http://php.net/json_encode

You cannot echo an array.
<?php echo $_SESSION["Counts"]; // this is an array ?>
And you can't execute PHP within a .js file either (trying to parse PHP within SecondJSpage.js)

Related

Autocomplete from array and get the corresponding id

Just wondering if someone knows a way to be able to autocomplete an input field after you type 3 letters then also get the id of the corresponding value?
I tried something like this with the UI Jquery:
It works great with the test array, but not with the real array im trying to use. Is it because the format is wrong? I include the array before json_encode and after.
var test = ["1899 Hoffenheim vs Borussia Dortmund", "SD Eibar vs Granada CF", "Fiorentina vs AS Roma"];
var availableTags = <?php echo json_encode($testArray); ?>;
console.log(availableTags);
$( "#test" ).autocomplete({
source: test
});
});
Before json_encode
Array
(
[0] => Array
(
[id] => 33820950
[match] => 1899 Hoffenheim vs Borussia Dortmund
)
[1] => Array
(
[id] => 33820951
[match] => SD Eibar vs Granada CF
)
[2] => Array
(
[id] => 33820952
[match] => Fiorentina vs AS Roma
)
[3] => Array
(
[id] => 33820991
[match] => Hibernian vs Rangers
)
[4] => Array
(
[id] => 33821044
[match] => RKC Waalwijk vs FC Twente
)
[5] => Array
(
[id] => 33821045
[match] => Middlesbrough vs Stoke City
)
[6] => Array
(
[id] => 33821108
[match] => Deportivo La Coruña vs CD Tenerife
)
[7] => Array
(
[id] => 33821138
[match] => Zaglebie Lubin vs Legia Warszawa
)
[8] => Array
(
[id] => 34096342
[match] => Everton vs Arsenal
)
[9] => Array
(
[id] => 34096343
[match] => Aston Villa vs Southampton
)
)
After json_encode
[{"id":"33820950","match":"1899 Hoffenheim vs Borussia Dortmund"},{"id":"33820951","match":"SD Eibar vs Granada CF"},{"id":"33820952","match":"Fiorentina vs AS Roma"},{"id":"33820991","match":"Hibernian vs Rangers"},{"id":"33821044","match":"RKC Waalwijk vs FC Twente"},{"id":"33821045","match":"Middlesbrough vs Stoke City"},{"id":"33821108","match":"Deportivo La Coru\u00f1a vs CD Tenerife"},{"id":"33821138","match":"Zaglebie Lubin vs Legia Warszawa"},{"id":"34096342","match":"Everton vs Arsenal"},{"id":"34096343","match":"Aston Villa vs Southampton"}];
Update:
Sorry, I misunderstood you at first. I guess you want to save all text values of the key match to a json array. So I take your $testArray, loop through it and assign everything to a new array that it matches the format.
Try this:
<?php
$array = [];
$i = 0;
$id = 0;
$ids = '[';
$availableTags = '[';
foreach($testArray as $val) {
$id[] = "\"".$val[$i]['id']."\"";
$array[] = "\"".$val[$i]['match']."\"";
$i++;
}
$id = implode(', ', $id);
$array = implode(', ', $array);
$availableTags .= $array . '];';
$ids = $id . '];';
?>
var availableIds = <?= $ids; ?>
var availableTags = <?= $availableTags; ?>
console.log(availableTags);
$( "#test" ).autocomplete({
source:
return {
label: availableTags,
value: availableIds
};
});
});
Finished working code. Where you can search for the match and both match and the corresponding id gets saved.
<form action="" method="POST" >
<input id="match_search" name="match_search" onChange="this.form.submit()">
<input id="match_id" name="match_id" hidden>
</form>
<?php
if (isset($_POST['match_search'])) {
$match = $_POST['match_search'];
$match_id = $_POST['match_id'];
echo $match.'<br>';
echo $match_id;
}
?>
<script>
var availableMatches = <?=json_encode($testArray); ?>;
$(function() {
$("#match_search").autocomplete({
delay: 0,
source: availableMatches,
select: function(event, ui) {
$('#match_search').val(ui.item.label);
$('#match_id').val(ui.item.value);
return false;
},
focus: function(event, ui) {
$("#match_search").val(ui.item.label);
return false;
}
});
});
</script>

PHP Array Length always 5

I am querying MS SQL Server and storing the results in a json array, then passing the results to Javascript. My issue is that based off if a variable isset the array length SHOULD be either 4 or 5 length. However, the array is ALWAYS showing a length of 5.
This is the php that I am using.
<?php
$sql = "Select ";
if (isset($_GET['namepull'])) {
$sql .= "name,";
}
$sql .= " address, city, state, zip from employeefile";
$db->setQuery($sql);
$rows = $db->loadRowList();
$output = array();
foreach ($rows as $row) {
array_push($output, $row);
}
echo $sql;
$jsondata = json_encode($output[0]);
?>
Which to me the below query strings should show an array length of
4 = Select address, city, state, zip from employeefile
5 = Select name, address, city, state, zip from employeefile
Now the issue that I have is when it hits the below <script> a length of 5 is always produced, regardless of the query. How should I modify the <script> so that an accurate count is returned?
<script>
var arrayfromphp = <?php echo $jsondata; ?>;
alert (arrayfromphp.length);
</script>
If I perform a console.log(arrayfromphp) the last element when the count should be 4 is always undefined x 1
Edit
If I use var_dump below is the output I get (which is what I expect)
Array ( [0] => XXXXXXXXX [1] => New York [2] => New York [3] => 33333 )
Array ( [0] => Jackie [1] => XXXXXXXXX [2] => New York [3] => New York [4] => 33333 )
Edit Again
It appears the issue is stemming from how I am populating a Javascript array from the php array. See edit below with notes above lines
var arrayfromphp = <?php echo $jsondata; ?>;
//Shows accurate count of 4
console.log(arrayfromphp);
var values = [];
if (arrayfromphp.length = 5) {
for (var i = 1; i < arrayfromphp.length; i++) {
values.push(arrayfromphp[i]);
}
} else if (arrayfromphp.length = 4) {
for (var i = 0; i < arrayfromphp.length; i++) {
values.push(arrayfromphp[i]);
}
}
//Shows 5
alert(arrayfromphp.length);
//Shows 5 with undefined x 1
console.log(arrayfromphp);

JSON Array parsing in PHP and updating in the database

Though this is a textbook problem, but I'm not able to parse from json object. I have a json object coming from a page, and I need to extract the ID,fieldText value so that I can update the table.
Here is how I'm capturing the json and converting it into array, not sure how to extract the values.
if(isset($_POST['postData'])){
$json = json_decode($_POST['postData'],true);
foreach ($json as $key => $value)
{
print_r($key);
//print_r($value);
foreach ($value as $k => $val)
{
//echo "$k | $val <br />";
} }
I need to update the table with [ID] and [fieldText] :
Result should like this::(1:Hello World), (2:The rising Star),(3: Terminator)
My JSON object is like this:
Array(
[fieldName] => Array
(
[0] => fieldText[1]
[1] => fieldText[2]
[2] => fieldText[3]
)
[fieldText] => Array
(
[0] => HelloWorld
[1] => The rising Star
[2] => Terminator
)
[ID] => Array
(
[0] => 1
[1] => 2
[2] => 3
))
Hi it seems that there are three arrays in your JSON, I think it would be better to change the way you generate the JSON to make it simple to understand.
// assumes $arr as the $_POST['postData'] in your case
$arr = array("1"=>"Hello World", "2"=>"The Rising Star", "3"=>"Terminator");
$j = json_encode($arr);
$json = json_decode($j,true);
foreach ($json as $key => $value)
{
echo '('.$key.','. $value.')';
}
The results are :
(1,Hello World)(2,The Rising Star)(3,Terminator)
Hope this can help you.
Hope you can do something like this.
$jsonData = Array(
'Name' => Array
(
0 => 'Text1',
1 => 'Text2',
2 => 'Text3'
),
'Value' => Array
(
0 => 'HelloWorld',
1 => 'The rising Star',
2 => 'Terminator'
),
'ID' => Array
(
0 => 1,
1 => 2,
2 => 3
)
);
$length = count($jsonData['ID']);
for($j=0;$j<$length;$j++) {
echo "(".$jsonData['ID'][$j].": ".$jsonData['Value'][$j].")<br/>";
}
In my opinion you should make your life easier by modifying the json array you receive with $_POST['data'];. If I were in your shoes my json would've been exactly as you need it:
{ 1:'Hello World', 2:'The rising Star',3:'Terminator' }
But if you are not able to change it for any reason I think you could use something like this (basing this example on your code):
$jsonData = json_encode($_POST['json'], true);
$id = $jsonData['ID'];
$fieldText = $jsonData['fieldText'];
$arr = array();
for ($i=0; $i < count($id); $i++) {
$arr[(int) $id[$i]] = $fieldText[$i];
}
var_dump($arr);
Hope this helps you!

Pass city name from php to js (part 2)

Cont. on Show Malaysia cities based on states chosen
City data json ($cityJsonObject)
Array ( [0] => stdClass Object ( [cityId] => c1 [cityName] => Kajang [cityStateId]
=> s2 ) [1] => stdClass Object ( [cityId] => c2 [cityName] => Seputeh
[cityStateId] => s1 ) [2] => stdClass Object ( [cityId] => c3 [cityName] => Shah
Alam [cityStateId] => s2 ) [3] => stdClass Object ( [cityId] => c4 [cityName] =>
Klang [cityStateId] => s2 ) [4] => stdClass Object ( [cityId] => c5 [cityName] =>
Kepong [cityStateId] => s1 ))
code (cityName)
<?php
for($i = 0; $i < count($cityJsonObject); $i++)
{
echo $cityJsonObject[$i]->cityName;
//PASS VARIABLE TO JS
}
?>
<script type="text/javascript">
//GET VARIABLE FROM PHP AND DISPLAY CITY NAME
</script>
From above code, I can get the following:
Kajang
Seputeh
Shah Alam
Klang
Kepong
My question is how to pass the above city name into a variable and pass to js? How should I do?
You can use json_encode and output a string which will be parsed easily by javascript
Try this code
<?php
$array_to_js = array();
for($i = 0; $i < count($cityJsonObject); $i++)
{
$array_to_js[] = $cityJsonObject[$i]->cityName;
}
?>
<script type="text/javascript">
//GET VARIABLE FROM PHP AND DISPLAY CITY NAME
var js_array = <?php echo json_encode($array_to_js, JSON_HEX_QUOT) ?>;
</script>
<?php
echo '<script type="text/javascript">';
// your php code here maybe you can need json_encode(), I'm not sure I get what you mean.
echo json_encode($cityJsonObject);
echo '<script>';
?>

Creating a JSON array starting with index 1

I need to create a JSON array starting with index 1
Here is my code which picks the images from the websites
$image_urls = array();
//get all images URLs in the content
foreach($get_content->find('img') as $element)
{
/* check image URL is valid and name isn't blank.gif/blank.png etc..
you can also use other methods to check if image really exist */
if(!preg_match('/blank.(.*)/i', $element->src) && filter_var($element->src, FILTER_VALIDATE_URL))
{
$image_urls[] = $element->src;
}
}
//prepare for JSON
$output = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
echo json_encode($output); //output JSON data
data.images gives the array bu it starts with 0
Try
$output = array();
$output['1'] = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
echo json_encode($output); //output JSON data
Output would be:
{"1":{"title":(*page_title*),"images":(*img_url*),"content":(*page_body*)}}
Try using array_unshift
$image_urls = array_unshift($image_urls,null);//add an element at the zeroth index
unset($image_urls[0]);//remove the zero index
An single line solution to the image_url array:-
$arr=array(1,2,3,4,5,6);
$arr = array_combine(range(1, count($arr)), $arr);
echo '<pre>';print_r($arr);
Output :
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
)

Categories

Resources