www.webdeveloper.com
Results 1 to 7 of 7

Thread: How can I do this with javascript?

  1. #1
    Join Date
    Dec 2012
    Posts
    15

    Question How can I do this with javascript?

    Imagine a MySQL table that has columns:
    Car-------------- color-------------------price
    mazda---------------white -----------------$10
    jeep------------------blue-------------------$12


    I have a PHP form that has a drop down menu (to select CAR) and one input box (for quantity) and button to calculate total price (quantity x price).
    When a visitor selects a car I need to picks up value for price from the same MySQL tables.

    This is while the visitor is still on the same page (before he click on calculate total button), so it can not be done with PHP. How do I do this with Javascript?
    It seems like a simple task but I am very new with js and can not think of a way to access the database without including password and other information for database in the javascript whch can be seen in source code and is a security issue.
    any suggestions or help is greatly appreciated.
    Thank you in advance
    JayJava
    Last edited by JayJava; 01-10-2013 at 12:16 PM.

  2. #2
    Join Date
    Dec 2012
    Posts
    95
    You'll need to make a PHP page that picks up a variable given by POST or GET and queries the database for the value, then echoes out the value, then you'll need to use AJAX in the JavaScript to send the car the user chooses to that PHP page, the value will then be returned in the AJAX response.

    A quick example would be this

    JavaScript:
    Code:
    var ajax = new XMLHttpRequest();
    var value;
    var carSelect = document.getElementById('carSelect');
    carSelect.addEventListener('change',getValue);
    function getValue(e) {
       var car = carSelect.value;
       ajax.open("GET","getcarvalue.php?car="+car,true);
       ajax.send();
       ajax.onreadystatechange = function() {
          if(ajax.readyState == 4) {
                value = ajax.responseText;
                //do whatever you want with the car value
          }
       }
    }
    php:
    Code:
    $dbUsername = "root";
    $dbPass = "";
    if(isset($_GET['car'])) {
        $dbHandle = new PDO("mysql:host=localhost;dbname=cars",$dbUsername,$dbPass);
        $query = $dbHandle->prepare("SELECT price FROM cars WHERE car = ?");
        $query->execute($_GET['car']);
        $result = $query->fetch(PDO::FETCH_ASSOC);
        echo $result['price'];
    }

  3. #3
    Join Date
    Dec 2012
    Posts
    15

    My code

    Thank you iBeZi for trying to help.
    I guess I am too ignorant of JS to understand what you mean.
    I include my code here maybe you can tell me if what I am trying to do is possible with your method or not?

    This form in on a page called cars.php and after visitors select three cars and enter the quantity for each I need to pick up price of each car from mySQL database and do a calculation to get total, show it in the text box bellow.
    Then the user clicks on the save button and information is sent to another php page that saves it.

    problem is that I can not run a querry on MYSQL with PHP and show in the same page before users go to save , that's why I am trying to use javascript.
    What do you think?
    thanks a million in advance.
    Jay


    ===================================================
    <script type="text/javascript">
    <!--
    function GetTotal()
    {
    Var TotalPrice=0;
    for (var i=1;i<=3;i++)
    {
    var ThisCar = document.frm1["selectCar["+i+"]"].value;

    //THIS IS WHERE THE PROBLEM IS
    // have to get this from database for now I say 100
    var CarPrice="100";

    var ThisPrice;
    ThisPrice = parseFloat(document.frm1["Quantity["+i+"]"].value) + parseFloat(CarPrice);
    TotalPrice=TotalPrice+ThisPrice;
    }
    document.frm1.txtTotal.value=TotalPrice;

    return
    }
    //-->
    </script>

    <form name=frm1 action=save.php method=POST>

    1. <select name=selectCar[1]>
    <value=mazda>mazda</option>
    <value=jeep>jeep</option>
    <value=toyota>toyota</option>
    </select>
    quantity: <input type=text name=Quantity[1] onblur=GetTotal()><br>

    2. <select name=selectCar[2]>
    <value=mazda>mazda</option>
    <value=jeep>jeep</option>
    <value=toyota>toyota</option>
    </select>
    quantity: <input type=text name=Quantity[2] onblur=GetTotal()><br>

    3. <select name=selectCar[3]>
    <value=mazda>mazda</option>
    <value=jeep>jeep</option>
    <value=toyota>toyota</option>
    </select>
    quantity: <input type=text name=Quantity[3] onblur=GetTotal()><br><br>

    Your total is estimated at:
    <input type=text name=txtTotal>
    <br><br>

    <INPUT id=cmdSend name=cmdSave type=submit value="Save">
    </form>
    ====================================================

  4. #4
    Join Date
    Dec 2012
    Posts
    95
    You can't access a MySQL database directly through JavaScript, you have to use AJAX to get content from another page asynchronously (without reloading the page), you have to make a PHP page which you'll send the selected cars to through AJAX to get the prices, you could even do this and get the total price directly from the PHP page like this.

    PHP:
    Code:
    $dbUsername = "root";
    $dbPass = "";
    if(isset($_GET['car1']) && isset($_GET['car1qt']) && isset($_GET['car2']) && isset($_GET['car2qt']) && isset($_GET['car3']) && isset($_GET['car3qt'])) {
        $dbHandle = new PDO("mysql:host=localhost;dbname=cars",$dbUsername,$dbPass);
        $query = $dbHandle->prepare("SELECT price FROM cars WHERE car = ?");
        for($i = 1; i <= 3; i++) {
           $query->execute($_GET['car'+$i]);
           $result = $query->fetch(PDO::FETCH_ASSOC);
           $price = $result['price'];
           $totalPrice += $price * $_GET['car'.$i.'qt'];
        }
        echo $totalPrice;
    }
    JavaScript:
    Code:
    <script type="text/javascript">
    <!--
    function GetTotal()
    {
    Var TotalPrice=0;
    
    var car1 = document.frm1["selectCar[1]"].value;
    var car1Qt = document.frm1["Quantity[1].value;
    var car2 = document.frm1["selectCar[2]"].value;
    var car2Qt = document.frm1["Quantity[2"].value;
    var car3 = document.frm1["selectCar[3]"].value;
    var car3Qt = document.frm1["Quantity[3]".value;
    
    var ajax = new XMLHttpRequest();
    ajax.open("GET","getcarpricetotal.php?car1="+car1+"&car1qt="+car1Qt+"&car2="+car2+"&car2qt="+car2Qt+"&car3="+car3+"&car3qt="+car3Qt,true);
    ajax.send();
    
    ajax.onreadystatechange = function() {
       if(ajax.readyState = 4) {
          var totalPrice = ajax.responseText;
          document.frm1.txtTotal.value=totalPrice;
       }
    }
    
    return	
    }
    //-->
    </script>
    
    <form name=frm1 action=save.php method=POST> 
    
    1. <select name=selectCar[1]>
    <value=mazda>mazda</option>
    <value=jeep>jeep</option>
    <value=toyota>toyota</option>
    </select>
    quantity: <input type=text name=Quantity[1] onblur=GetTotal()><br>
    
    2. <select name=selectCar[2]>
    <value=mazda>mazda</option>
    <value=jeep>jeep</option>
    <value=toyota>toyota</option>
    </select>
    quantity: <input type=text name=Quantity[2] onblur=GetTotal()><br>
    
    3. <select name=selectCar[3]>
    <value=mazda>mazda</option>
    <value=jeep>jeep</option>
    <value=toyota>toyota</option>
    </select>
    quantity: <input type=text name=Quantity[3] onblur=GetTotal()><br><br>
    
    Your total is estimated at:
    <input type=text name=txtTotal>
    <br><br>
    
    <INPUT id=cmdSend name=cmdSave type=submit value="Save">
    </form>

  5. #5
    Join Date
    Dec 2012
    Posts
    15

    Thank you

    Thank you IBiZi you re a great help eveytime I post a question.
    I was doing some search regarding this problem and came across some videos on youtbe showing how to use jquery.js library to do this. What do you think about jquery?

    I repeated the experimen they where doing. The thing works but here is no reference or call to any functon as far as I can tell. Any iea as why this should work?

    There are two pages data.php and index.php. Visitor sees only the index.php page.

    data.php
    <?php
    $dbhost = "**********";
    $dbuser = "***************";
    $dbpass = "--------------";
    $dbname = "===============";
    $db = mysql_connect($dbhost,$dbuser,$dbpass);
    mysql_select_db("$dbname",$db) or die ("<br>Could not open database: $dbname: ".mysql_error() );

    $name=$_POST['name'];
    $query = "SELECT age FROM tblPeople WHERE name='$name'";
    $reslt = mysql_query($query);
    $numr = mysql_num_rows($reslt);
    $RecoRow = mysql_fetch_array($reslt);
    $age=$RecoRow[age];
    print $name. "'s age is: ".$age;
    ?>
    ==========================
    index.php

    <html>
    <head>
    <script type="text/javascript" src=jquery.js>
    </script>
    <script type="text/javascript">
    function get(){
    $.post('data.php',{name:form.name.value},
    function(output){
    $('#age').html(output).show();
    });
    }
    </script>
    </head>

    <body>
    <p>
    <form name=form>
    <input type=text name=name><input type="button" value=Get onclick="get();">
    </form>
    <hr>
    <div id=age>result</div>
    </body>
    </html>

  6. #6
    Join Date
    Dec 2012
    Posts
    95
    I'm honestly not a fan of JQuery, I avoid it whenever I can, it's a huge and very powerful library, but it's unnecessary unless you need to use it a lot. It works by taking loads and loads of JavaScript features and hiding them behind functions within the JQuery library to make it easier to use them, you can do most things without it though.

    Without JQuery the test you've made here would look a little something like this.

    Code:
    <html>
    <head>
    <script type="text/javascript" src=jquery.js>
    </script>
    <script type="text/javascript">
    function get(){
    var ajax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP.3.0');
    ajax.open("POST","data.php",true);
    ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    ajax.send("name="+form.name.value);
    ajax.onreadystatechange = function() {
         if(ajax.readyState == 4) {
              document.getElementById('age').innerHTML = ajax.responseText;
         }
    }
    }
    </script>
    </head>
    
    <body>
    <p>
    <form name=form>
    <input type=text name=name><input type="button" value=Get onclick="get();">
    </form>
    <hr>
    <div id=age>result</div>
    </body>
    </html>
    Sure, it's a little bit more complicated than the JQuery root, but it saves the user having to download the entire JQuery library just to use one small part of it.

  7. #7
    Join Date
    Dec 2012
    Posts
    15
    Thanks again iBeZi

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles