Solved

Passing PHP array to Javascript through XmlHttp

Posted on 2007-11-21
10
529 Views
Last Modified: 2010-04-21
Hello,
I have a global javascript array and I'm trying to fill that array from a php script through Ajax but it is not working form .. appreciate your help

Here sample of the code

// ==============   .js file ================//

var sel_rule = [];

function view_array(arg1){
      var url="php_file.php"
      url=url+"?arg1="+arg1
      url=url+"&sid="+Math.random() // prevent using cache

      swmxmlHttp=GetXmlHttpObject()
      swmxmlHttp.onreadystatechange = view_array_stateChanged;
      swmxmlHttp.open("GET",url,true)
      swmxmlHttp.send(null)
}
functionview_array_stateChanged(){
      if (swmxmlHttp.readyState==4 || swmxmlHttp.readyState=="complete")
      {
            document.getElementById("array_view").innerHTML= swmxmlHttp.responseText       
               
               alert(sel_rule.length);  // This should show the number of elements in the array but I always get 0
      }
}


// ============  php_file.php    ================== //
<?
    $arg1 =  $_GET["arg1"];
  // query database

  // fill the javascrip array with query results.. I'm using fix values here
   echo "<script>
             sel_rule[0] = 22222
             sel_rule[1] = 24444
             sel_rule[2] = 22555
            </script>";
?>


Thanks in advance
0
Comment
Question by:sking5292
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20330584
sking5292,

Does the PHP script only send that code in the response?

The problem is the script isn't being run by the browser.  Even with the script tags it is just treated as html or text.  If that is all the PHP script send in the "responseText" then I suggest you use JSON.  I don't have time for an example of this right now but I will be happy to provide one if you need it.  Basically you send the array in a little different format and then use the Javascript to get it in an array.  A little more work but JSON is great. :)

Let me know if you have any questions or need more information.

b0lsc0tt
0
 
LVL 1

Expert Comment

by:alexgcm
ID: 20331241
You coud do your php like this:

echo "22222,24444,22555";


And your javascript like this:

functionview_array_stateChanged(){
      if (swmxmlHttp.readyState==4 || swmxmlHttp.readyState=="complete")
      {
            var sel_rule = swmxmlHttp.responseText.split(",");
            alert(sel_rule.length);  // This should show the number of elements in the array but I always get 0            }
}



Also you could use JSON or XML and parse the result.
0
 

Author Comment

by:sking5292
ID: 20331491
b0lsc0tt,
Thanks for your reply,

Yes, the php code is returning that array only.

I have never used JSON before, so I did some research on how to it use to get this done, so do you think I can do this by creating JSON object in php and use javascript eval() function to excute it?

if that's not the case, I appreciate an example ..

Thank you
0
 

Author Comment

by:sking5292
ID: 20331624
alexgcm,
I wish it's that simple, the problem is I'm trying to return multiple complicated arrays (hash key arrays)
 
  sel_ruls['icmp']=[1111,222,333]
  sel_ruls['icmp_info']=[5561,255,443]

  un_selected_ruls['dns']=[555,5566,666]

regards


 
0
 
LVL 82

Accepted Solution

by:
hielo earned 125 total points
ID: 20331659
Try this:

// ==============   .js file ================//

var sel_rule = [];

function view_array(arg1){
      var url="php_file.php"
      url=url+"?arg1="+arg1
      url=url+"&sid="+Math.random() // prevent using cache

      swmxmlHttp=GetXmlHttpObject()
      swmxmlHttp.onreadystatechange = view_array_stateChanged;
      swmxmlHttp.open("GET",url,true)
      swmxmlHttp.send(null)
}
functionview_array_stateChanged(){
      if (swmxmlHttp.readyState==4 || swmxmlHttp.readyState=="complete")
      {
              eval(swmxmlHttp.responseText);  
               alert(sel_rule.length);  // This should show the number of elements in the array but I always get 0
      }
}

// ============  php_file.php    ================== //
<?
    $arg1 =  $_GET["arg1"];
  // query database

  // fill the javascrip array with query results.. I'm using fix values here
   echo "
             sel_rule[0] = 22222;
             sel_rule[1] = 24444;
             sel_rule[2] = 22555;
          ";
?>
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 82

Expert Comment

by:hielo
ID: 20331742
If you want to use JSON notation:

// ==============   .js file ================//

var sel_rule = null;

function view_array(arg1){
      var url="php_file.php"
      url=url+"?arg1="+arg1
      url=url+"&sid="+Math.random() // prevent using cache

      swmxmlHttp=GetXmlHttpObject()
      swmxmlHttp.onreadystatechange = view_array_stateChanged;
      swmxmlHttp.open("GET",url,true)
      swmxmlHttp.send(null)
}
functionview_array_stateChanged(){
      if (swmxmlHttp.readyState==4 || swmxmlHttp.readyState=="complete")
      {
              eval("sel_rule ="+seswmxmlHttp.responseText+";");  
               alert(sel_rule.sel_ruls.icmp.length);  // This should show the number of elements in the array but I always get 0
      }
}

// ============  php_file.php    ================== //
<?
    $arg1 =  $_GET["arg1"];
  // query database

  // fill the javascrip array with query results.. I'm using fix values here
   echo "
{
{
      'sel_ruls':
      {
            'icmp':[
                  1111
                  ,222
                  ,333
            ]

            ,'icmp_info':[
                  5561
                  ,255
                  ,443
            ]
      }
}
,{
      'un_selected_ruls':{
            'dns':
            [
                  555
                  ,5566
                  ,443
            ]
}
}
          ";
?>
0
 
LVL 82

Expert Comment

by:hielo
ID: 20331783
You couls also format you strings by putting some delimeters and processin on the client. Take a look at this:

// ==============   .js file ================//

var sel_rule = null;

function view_array(arg1){
      var url="php_file.php"
      url=url+"?arg1="+arg1
      url=url+"&sid="+Math.random() // prevent using cache

      swmxmlHttp=GetXmlHttpObject()
      swmxmlHttp.onreadystatechange = view_array_stateChanged;
      swmxmlHttp.open("GET",url,true)
      swmxmlHttp.send(null)
}
functionview_array_stateChanged(){
      if (swmxmlHttp.readyState==4 || swmxmlHttp.readyState=="complete")
      {
              data = String(seswmxmlHttp.responseText).replace(/\s/g);
                data = data.split(";");
                for( var i=0;i<data.length;++i)
                {
                            var k = data[i].split("^");
                        sel_rule[ k[0] ]=null;
                        sel_rule[ k[0] ][ k[1] ]=null;
                        sel_rule[ k[0] ][ k[1] ]= k[2].split(",");
                }
               alert(sel_rule.sel_ruls.icmp.length);  // This should show the number of elements in the array but I always get 0
      }
}

// ============  php_file.php    ================== //
<?
    $arg1 =  $_GET["arg1"];
  // query database

  // fill the javascrip array with query results.. I'm using fix values here
   echo "
sel_ruls^icmp^1111,222,333;
sel_ruls^icmp_info^5561,255,443;
un_selected_ruls^dns^555,5566,666;
";
?>
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20331793
It wouldn't have to be a PHP JSON object.  I honestly don't know off the top of my head if PHP has one.  If so it might make this easier.  The key is to have the PHP response like that posted in hielo's last comment.  It comes to the AJAX and Javascript just as "text" but in that style it can easily be converted by Javascript and quickly becomes an array, etc.

Let me know how that post by Hielo gets you going.  I will be busy still for a few hours but can make some code, etc after that if you give me an idea of what you need.  There is lots of info on JSON on the Internet too but it can be a little overwhelming. :)

bol
0
 

Author Closing Comment

by:sking5292
ID: 31410447
eval function is all I needed

Thanks hielo
0
 

Author Comment

by:sking5292
ID: 20331985
Thank you guys, that was helpful
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
This article discusses four methods for overlaying images in a container on a web page
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now