Results 1 to 3 of 3

Thread: Php in javascript?

  1. #1
    Join Date
    Apr 2006
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Php in javascript?

    Hello,

    I've got a problem with my javascript function. I'd like to make sql query from it and pass its result back to function. What more I need to pass javascript variable to php select. Function must be in javascript bacause it's called by onchange event.

    [Code]
    function foo(my_var)
    {
    <?php
    $MyVar = "?>document.write(my_var);<?php";
    $MyVar = str_replace("?>", "", $MyVar2);

    mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('database');
    $result = mysql_query("SELECT * FROM tableA WHERE id = $MyVar")
    while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $var2 = $row[0]."=".$row[1];
    }
    mysql_free_result($result);
    echo $var2;
    ?>
    }

    Can I do sthg like that or is it totally wrong? How can I make it work?

    Thanks in advance.

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Can I do sthg like that or is it totally wrong?
    It's rather wrong. PHP cannot be called by a client-side event, although you can use it to generate Javascript that will be. The easiest way to do this is to create a form that will be submitted to the PHP script.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  3. #3
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,164
    Thanks
    265
    Thanked 690 Times in 678 Posts

    Default

    The other way is using Ajax, but that's more complex.

    Either way, through JS in the background (ajax) or refreshing/submitting a form/clicking a link, you need to make the page reload to have the php get reevaluated.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •