Am trying to parse a php array into javascript but i found that only one element of the array was present in the javascript array. here is my code code -
<?php
-
include("../../connect.php");
-
$qry="select * from stock";
-
$rst=mysql_query($qry) or die("Error in Query.".$qry." ".mysql_error());
-
while($row=mysql_fetch_assoc($rst)){
-
$item=$row['item'];
-
$list[$item]=$row['price'];
-
}
-
foreach($list as $key =>$value){
-
echo $key."-";
-
echo $value."<br/>";
-
}
-
echo $list['coke'];
-
?>
-
<script type="text/javascript" language="javascript">
-
list = new Array("<?php echo $list[$item]; ?>")
-
alert(list);
-
</script>
-
the foreach loop worked just fine printing all the keys and values in the database but in the process of parsing it i seem to be doing something wrongly
cos the alert is only printing the value the last key "5000"
16 9305 Dormilich 8,658
Recognized Expert Moderator Expert
the problem is that a Javascript array is somewhat different from a PHP array. a Javascript array uses only numeric values as key. or put in other words, there is no such thing as an associative array in Javascript.
an associative array in Javascript is called: object. you have several options to define a (standard) object
- using the Object Literal - var obj_name = {
-
key1 : value1,
-
key2 : value2
-
// etc.
-
}
- create an object with “new”, applicable if you have a predefined set of keys - function MyObject(value)
-
{
-
this.key = value;
-
}
-
var obj_name = new MyObject("a value");
- create a new empty object and append the values - var obj_name = new Object;
-
obj_name.key1 = value1;
-
obj_name.key2 = value2;
-
// etc.
and regarding the output. calling $list[$item] is exactly one value.
i think i uderstand the 1st and last options but the array is being generated by values from a table in the database and i have no control over the size of the array and worse i dont think javascript have the foreach loop equivalent
Dormilich 8,658
Recognized Expert Moderator Expert @freefony wrong.
nevertheless, it doesn’t matter. since PHP long finished execution when JavaScript starts, you have to print each and every key - value combination by PHP (using method 1 or 3 (2 was for completeness))
-
echo "<script languege='javascript'>";
-
foreach($list as $key=>$val){
-
echo "var item=".$key;
-
echo "var price=".$val;
-
}
-
echo "</script>";
-
is there any chance that would work?
gits 5,390
Recognized Expert Moderator Expert @Dormilich
wouldn't that be similar to: - echo 'var obj_name = '.json_encode($php_array);
-
kind regards
Dormilich 8,658
Recognized Expert Moderator Expert @freefony
nope, you’d end up redeclaring 2 variables
@gits: looks like that.
gits 5,390
Recognized Expert Moderator Expert
i did ... and i thought ... even when i'm not a php-expert that for the current case: - echo 'var list = '.json_encode($list);
could do the job? it should create a string that is later on evaled by JavaScript as an object (or assoc array if you want to call it that) with all keys and values in the $list array?
kind regards
Hey the jason function is a powerful tool! but little problem tho i still cant get the javascript array. -
//these two lines works perfectly
-
$mylist=jason_encode($list);
-
var_dump($mylist);
-
//output: string(64) "{"coke":"70","Emzor Paracetamol BP":"2","Paracetamol BP":"5000"}"
but the following codes return nothing what am i doing wrong? -
echo "<script languege='javascript'>";
-
echo "var mylist=".json_encode($list);
-
echo "document.write(mylist)";
-
echo "var data=eval(mylist)";
-
echo "</script>";
-
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Sandman |
last post by:
Hello
I have been trying to wrap my head arouns this, but I can't seem to get it to
work the way I want it to. Could someone helpful please tell me how I get this:
<function>
<name>array_push</name>
<examples>
<example>
<name>A way to do it</name>
|
by: Sven Neuberg |
last post by:
Hi,
I have been handed the task of updating and maintaining a web
application, written in ASP and Javascript, that takes complex
user inputs in HTML form and submits them to server-side ASP
pages for processing. The problem is, the user inputs can
become very complex, and the way this application was developed,
the inputs are all concatenated into monstrously long strings
of text that are then submited as <hidden> inputs in HTML forms...
|
by: ralphNOSPAM |
last post by:
Is there a function or otherwise some way to pull out the target text
within an XML tag?
For example, in the XML tag below, I want to pull out 'CALIFORNIA'.
<txtNameUSState>CALIFORNIA</txtNameUSState>
|
by: Marc van Boven |
last post by:
I'm stuck with the following problem:
My nusoap-client calls a server-function giveCombination(). The
function giveCombination should return something like
array(
=> array(
'a_id' => 6,
'b_id' => 9,
'c_id' => 3,
|
by: djdave |
last post by:
My problem is that i need an algorithm parse parse HTML.
For an HTML page, my script has to parse all tags to get all forms
values, even if there is frame, iframe, ...
How can i do such a script ?
Thanks
| |
by: Paulers |
last post by:
Hello,
I have a log file that contains many multi-line messages. What is the
best approach to take for extracting data out of each message and
populating object properties to be stored in an ArrayList? I have tried
looping through the logfile using regex, if statements and flags to
find the start and end of each message but I do not see a good time in
this process to create a new instance of my Message object. While
messing around with...
|
by: Aaron |
last post by:
I'm trying to parse a table on a webpage to pull down some data I
need. The page is based off of information entered into a form. when
you submit the data from the form it displays a "Searching..." page
then, refreshes and displays the table I want. I have code that grabs
data from the page using cURL but when I look at the data it contains
the "Searching..." page and not the table that I want. below is the
code i have so far....Thanks...
|
by: Jasper |
last post by:
Hi, Maybe this is off-topic, but perhaps you can help. I'm looking for ideas
on how to parse a data file.
I dont know XML but I know it parses data in text format.
I have a structured data file of the general form shown below. I dont have
any definition of the data. Basically it looks like it is hierarchical,
token/data pairs defined by brackets and square brackets.
I would like to parse this out into some sort of data object(s) in...
|
by: Philip Semanchuk |
last post by:
On Oct 12, 2008, at 5:25 AM, S.Selvam Siva wrote:
Selvam,
You can try to find them yourself using string parsing, but that's
difficult. The closer you want to get to "perfect" at finding URLs
expressed in JS, the closer you'll get to rewriting a JS interpreter.
For instance, this is not so hard to understand:
"http://example.com/"
but this is:
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |