Autocomplete from array and get the corresponding id - javascript

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>

Related

How to get Session value which is an array in 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)

PHP dimensional array to Javascript array WITHOUT JSON

I'm trying to convert a PHP multidimensional array to a javascript array WITHOUT using json encoder because of the version of the server.
Exemple of a multidimensional Array :
Array (
[0] => Array (
[0] => 18
[1] => Région Grand EST
[2] => GE )
[1] => Array (
[0] => 17
[1] => Région Grand OUEST / NORD
[2] => GO N )
[2] => Array (
[0] => 25
[1] => Région Grand OUEST / SUD
[2] => GO S )
)
Currently for no multidimensional array i'm using this function :
function js_str($s) {
return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}
function js_array($array) {
if (is_array($array)) {
$temp = array_map('js_str', $array);
return '[' . implode(',', $temp) . ']';
}
return '[-1]';
}
But i can't use it for multidimensional, i'm trying to do somthing similar recursively to do it with any size of array.
To get a result like :
myArray = [[18, 'Région Grand EST', 'GE'],[17, 'Grand OUEST / NORD', 'GO N'], [25, 'Région Grand OUEST / SUD', 'GO S']];
It's really hard to find an answer without json_encode, thanks for your help.
(Yes i'm developping on a prehistoric server)
I would approach this problem with a recursive function like this:
function js_array($array) {
if (is_array($array)) {
$temp = array();
$output = '[';
foreach ($array AS $key=>$value) {
$temp[] .= "'$key':" . js_array($value);
}
$output .= implode(',', $temp);
$output .= "]";
} else {
$output .= "'$array'";
}
return $output;
}
What we're doing here is evaluating each element of the array to see if it is also an array. Each level drills down into itself until we are left with simple key:value pairs.
You can edit for special characters or to drop the array keys if you want.
Thx to Danielml01 for his help.
Here the solution used :
function js_array($array) {
if (is_array($array)) {
$temp = array();
$isObject = false;
foreach ($array AS $key=>$value) {
if (is_numeric($key))
$temp[] .= js_array($value);
else {
$isObject = true;
$temp[] .= "'$key':" . js_array($value)."";
}
}
if ($isObject)
$output = "{".implode(',', $temp)."}";
else
$output = "[".implode(',', $temp)."]";
}
else
$output = "'".$array."'";
return $output;
}

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>';
?>

PHP array and json_encode (separated with comma)

I am literally cracking my head to covert the PHP array to JavaScript array and convert the same in the correct format. This is what I have
My PHP array is stored in $data (this comes from a SQLserver query) which I am converting to a JavaScript array using json_encode.
Here is the code $javaarray = json_encode($data); When I echo the result this is what I am getting
{"VERTICAL":"PROVISIONING","dcount":381890}
{"VERTICAL":"BILL DELIVERY","dcount":171169}
{"VERTICAL":"BILLING","dcount":45197}
{"VERTICAL":"RISK AND CREDIT","dcount":51533}
{"VERTICAL":"CUSTOMER ACCOUNTING","dcount":136097}
{"VERTICAL":"AIRTEL MONEY","dcount":7826}
{"VERTICAL":"ANALYTICS","dcount":2946}
{"VERTICAL":"CONTROLS","dcount":5615}
Now I want to get the dcount part only to feed it back to my jQuery function in the following format
[381890,171169,45197,51533,136097,7826,2946,5615]
I tried working around with implode(), join() but somehow not getting even closer to the above format.
I am posting the
$array = array($data);
print_r($array);
result also
Array ( [0] => Array ( [VERTICAL] => PROVISIONING [dcount] => 381890 ) ) Array ( [0] => Array ( [VERTICAL] => BILL DELIVERY [dcount] => 171169 ) ) Array ( [0] => Array ( [VERTICAL] => BILLING [dcount] => 45197 ) ) Array ( [0] => Array ( [VERTICAL] => RISK AND CREDIT [dcount] => 51533 ) ) Array ( [0] => Array ( [VERTICAL] => CUSTOMER ACCOUNTING [dcount] => 136097 ) ) Array ( [0] => Array ( [VERTICAL] => AIRTEL MONEY [dcount] => 7826 ) ) Array ( [0] => Array ( [VERTICAL] => ANALYTICS [dcount] => 2946 ) ) Array ( [0] => Array ( [VERTICAL] => CONTROLS [dcount] => 5615 ) )
Try something like this
$dcounts = array();
foreach ($data as $row) {
$dcounts[] = $row['dcount'];
}
$javaarray = json_encode($dcounts);
$dcounts = json_encode(array_map(function($v) { return $v['dcount'] }, $javaarray));
$data = '{"VERTICAL":"PROVISIONING","dcount":381890}
{"VERTICAL":"BILL DELIVERY","dcount":171169}
{"VERTICAL":"BILLING","dcount":45197}
{"VERTICAL":"RISK AND CREDIT","dcount":51533}
{"VERTICAL":"CUSTOMER ACCOUNTING","dcount":136097}
{"VERTICAL":"AIRTEL MONEY","dcount":7826}
{"VERTICAL":"ANALYTICS","dcount":2946}
{"VERTICAL":"CONTROLS","dcount":5615}';
//split data into array
$keywords = preg_split("/[\n]+/", $data);
//convert into proper json format
$jsonobject = implode(',',$keywords);
$jsonobject = '['.$jsonobject.']';
//convert json into array
$array = json_decode($jsonobject);
//for each and save dcount value
$dcount = array();
foreach($array as $row){
$dcount[] = $row->dcount;
}
//again convert dcount values into json
$dcountjson = json_encode($dcount);
print_r($dcountjson);

Categories

Resources