Page 1 of 3 123 Last
  • Jump to page:
    #1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    436
    Rep Power
    8

    Passing php array to javascript


    hi,

    I want to retrieve data from a database with php, then giving it to javascript to process when a button is clicked. The point is to add some lines with css to the script. I know it is not only php so if someone happens to know how to solve this, thank you in advance.

    This is what I got so far:
    the javascript:
    Code:
    function css_func_1(id, db_data)
    {
        document.getElementById("css_change").innerHTML="\
                db data" + db_data[index]['etc'] + "\n\
                id" + id + ";   
    // extra lines for the css
    }
    and the initial php document:

    PHP Code:
    <?php 

        
    require("../connection.php"); // connect to the database         
        
        
    $ids = array(12);
        
    $db_data_stmt $db->prepare('
            SELECT *
            FROM table
            WHERE id IN (' 
    implode(','array_fill(0count($ids), '?')) . ') 
        '
    );
        
    $db_data_stmt->execute($ids);
        
    $db_data $db_data_stmt->fetchAll();
        
    $parsed_db_data json_encode($db_dataJSON_FORCE_OBJECT);
           
    ?> 
    <html>
        <head>
            <script src="javascript.js"></script>
        </head>
        <body>
            <button type="button" onclick="css_funct_1(1, <?php echo $parsed_db_data;?>)">Button 1</button>
            <button type="button" onclick="css_funct_1(2, <?php echo $parsed_db_data;?>)">Button 2</button>
            <button type="button" onclick="css_funct_1(3, <?php echo $parsed_db_data;?>)">Button 3</button>
            <div id="css_change"></div>
        </body>
    </html>
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    189
    Rep Power
    0
    What I have done in the past is to place some php code in my html output section and echo out the lines and data needed to build a js array or whatever I have needed. If you can write the js code, you can write php code to mimic that js code.
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    436
    Rep Power
    8
    Well there is something weird about my script though, sometimes it works and sometimes it doesn't, at least when I delete the second var in the function (the array) but when I add it, the whole function doesn't even get reached...

    EDIT: The fact that the script doesn't run sometimes could be the refresh thing of my browser... Don't mind it, but the function itself doesn't get reached when an array is passed to it...
    Last edited by derplumo; July 31st, 2013 at 06:36 AM.
  6. #4
  7. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Hi,

    you need to start learning how to use the JavaScript console and debug your code. Sure, sometimes we can solve your problem just by looking at the code. But most of the time, bugs require active investigations. And that's something only you can do. Remember: We don't have access to your machine, and we (usually) don't replicate your whole system to investigate the problem ourselves.

    So get familiar with the developer tools of your browser and the console.log() method.

    What I do see is that you have a syntax error in your css_func_1(): The last string has no end delimiter. Is that the solution? I don't know.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  8. #5
  9. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    436
    Rep Power
    8
    Originally Posted by Jacques1
    What I do see is that you have a syntax error in your css_func_1(): The last string has no end delimiter. Is that the solution? I don't know.
    What do you mean by that

    I only know that even when I delete all the ";" in the buttons, I get this error

    Code:
    Uncaught SyntaxError: Unexpected token ;
    And I added this in the function:
    Code:
    console.count("Login called");
    but it didn't say anything in the log (of course because there is an error in it...)
  10. #6
  11. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Originally Posted by derplumo
    What do you mean by that
    This line:

    Code:
    id" + id + ";
    There's no closing quote for the string at the end. You have an opening quote, but you don't terminate the string.

    Oh, and your code is wide open to cross-site scripting. You'll see a side-effect of this if your rows contain strings, because the double quotes of the JSON strings will clash with the double quotes of the HTML attribute.

    Writing the same JSON array three(!) times into the document is also pretty much the most inefficient thing you could do.

    So I think it's time to take a different approach: Instead of dumping all data into the HTML document and letting the poor user wait until everything is finished, use Ajax to load the data from a PHP script providing JSON. Do that once and then have all css_funct_1 calls read from this piece of data (instead of unnecessarily duplicating the same data again and again).

    With the jQuery library, it's as simple as

    Code:
    $.getJSON('ajax/my_data.php', function(data) {
    	// data is the complete JSON array
    });
    And ajax/my_data.php simply echoes the JSON encoded array (don't forget to set the Content-Type header to application/json).
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  12. #7
  13. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    436
    Rep Power
    8
    Well I want to explain my idea again, maybe there is a simple solution for it.
    I have those buttons, and when someone clicks it, the will open a kind of window (this will be the css) in this window is the information from the database. Also there is a link to an other page that will execute some code and displays a message. So I want to get the data in the window, so I think it must be processed by the js?

    So, see if I get it, we'll get something like this:

    js:
    Code:
    $.getJSON('ajax/my_data.php', function(data) {
    	// data is the complete JSON array
    });
    function css_func_1(id, db_data)
    {
        document.getElementById("css_change").innerHTML="\
                db data" + db_data[index]['etc'] + "\n\
                id" + id;   
    	// extra lines for the css
    }
    the document:

    PHP Code:
    <?php  

        
    require("../connection.php"); // connect to the database          
        
    header('Content-type: application/json');
    ?>  
    <html> 
        <head> 
            <script src="javascript.js"></script> 
        </head> 
        <body> 
            <button type="button" onclick="css_funct_1(1);">Button 1</button> 
            <button type="button" onclick="css_funct_1(2);">Button 2</button> 
            <button type="button" onclick="css_funct_1(3);">Button 3</button> 
            <div id="css_change"></div> 
        </body> 
    </html>
    ajax/my_data.php:

    PHP Code:
    $ids = array(1,2);
    $db_data_stmt $db->prepare(
            SELECT * 
            FROM table 
            WHERE id IN (' 
    implode(','array_fill(0count($ids), '?')) . ')  
        '
    ); 
        
    $db_data_stmt->execute($ids); 
        
    $db_data $db_data_stmt->fetchAll(); 
        
    $parsed_db_data json_encode($db_dataJSON_FORCE_OBJECT); 
  14. #8
  15. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    No, you don't understand.

    You have a PHP script which echoes a JSON document. This script sends its content with the application/json type, because that's what it does: It provides JSON.

    It will look like this:

    ajax/my_data.php
    PHP Code:
    <?php   

    require '../connection.php'// connect to the database 

              
    header('Content-type: application/json'); 

    $ids = array(1,2); 
    $db_data_stmt $db->prepare('  
        SELECT *  
        FROM table  
        WHERE id IN (' 
    implode(','array_fill(0count($ids), '?')) . ')   
    '
    );  
    $db_data_stmt->execute($ids);  
    $db_data $db_data_stmt->fetchAll();  
    $parsed_db_data json_encode($db_dataJSON_FORCE_OBJECT);

    echo 
    $parsed_db_data;    // that's the relevant line!
    Your main script sends HTML, not JSON, so the application/json type would be wrong.

    And in your JavaScript, you need to actually do something with the JSON request. The general logic would work like this: When the user clicks on the button, you request the data from the my_data.php script by using $.getJSON(). This may take a while, depending on the size of the data. Once the data is ready, it's passed to the function of the $.getJSON() call:

    Code:
    function css_func_1(id)
    {
    	$.getJSON('ajax/my_data.php', function(data) {
    		// The data is ready to be inserted into the page...
    		console.log(data);
    	});
    }
    And within the inner function, you can insert the data into your page.

    Depending on the complexity of the "window" layout, it might make sense to have the PHP script build the whole HTML rather than just passing the raw JSON data.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  16. #9
  17. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    436
    Rep Power
    8
    Originally Posted by Jacques1
    Depending on the complexity of the "window" layout, it might make sense to have the PHP script build the whole HTML rather than just passing the raw JSON data.
    How do you mean?

    and in $.getJSON(ajax/my_data.php ajax is a new folder where the my_data.php put in right?

    Last but not least, how do I access the array?
  18. #10
  19. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Originally Posted by derplumo
    How do you mean?
    I mean that the PHP script could build the complete HTML for the window. So you'd get back the ready-made HTML, and all you'd have to do with JavaScript is display it -- as opposed to constructing the window from the raw JSON data.



    Originally Posted by derplumo
    and in $.getJSON(ajax/my_data.php ajax is a new folder where the my_data.php put in right?
    Yes.



    Originally Posted by derplumo
    Last but not least, how do I access the array?
    What array? The data array coming from the JSON script? That's a normal JavaScript array.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  20. #11
  21. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    436
    Rep Power
    8
    ok thanks, but is data global or must it be used inside this (so at the '// The data...'):

    Code:
    $.getJSON('ajax/my_data.php', function(data) {
    		// The data is ready to be inserted into the page...
    		console.log(data);
    	});
    And of course a dumb question, how do I include the JQuery lib?
  22. #12
  23. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    The processing must be done where the comment is, because that's when the data is ready.

    This function gets called when the Ajax request is finished and the JSON document has been received and decoded. After this, you can start inserting the data into your page.

    You might consider caching the data in order to avoid a new request whenever the button gets clicked.



    And of course a dumb question, how do I include the JQuery lib?
    Download it (the compressed file) and include it like a normal JavaScript file (with the script element).

    Comments on this post

    • derplumo agrees : Always helps me out :)
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  24. #13
  25. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    436
    Rep Power
    8
    what document do I have to download on the page? The 1.X or 2.X?

    And what does the console.log(data) do? Do I then see the values in my browsers 'debug'?

    Also I'm trying to debug with netbeans...
  26. #14
  27. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    Originally Posted by derplumo
    what document do I have to download on the page? The 1.X or 2.X?
    Read the explanation on the site.

    jQuery 2.x has the same API as jQuery 1.x, but does not support Internet Explorer 6, 7, or 8. All the notes in the jQuery 1.9 Upgrade Guide apply here as well. Since IE 6/7/8 are still relatively common, we recommend using the 1.x version unless you are certain no IE 6/7/8 users are visiting the site. Please read the 2.0 release notes carefully.


    Originally Posted by derplumo
    And what does the console.log(data) do? Do I then see the values in my browsers 'debug'?
    It writes a detailed description of the value to the JavaScript console of your browser. Similar to what var_dump() does in PHP.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  28. #15
  29. Mad Scientist
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2007
    Location
    North Yorkshire, UK
    Posts
    3,661
    Rep Power
    4123
    in modern browsers there is a javascript 'console'. It's hard for me to explain what a console is, if you're not familiar with the term (sorry -someone else may be able to explain).

    Open up a browser and hit the F12 function key and see what happens.

    I would recommend using Firefox and installing the firebug addon, this will jump up on F12ing in FF and will show you javascript errors, ajax requests and also allow you to inspect the DOM, icluding CSS etc. It's a very powerful tool and well worth the free download
    I said I didn't like ORM!!! <?php $this->model->update($this->request->resources[0])->set($this->request->getData())->getData('count'); ?>

    PDO vs mysql_* functions: Find a Migration Guide Here

    [ Xeneco - T'interweb Development ] - [ Are you a Help Vampire? ] - [ Read The manual! ] - [ W3 methods - GET, POST, etc ] - [ Web Design Hell ]
Page 1 of 3 123 Last
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo