Craig Wayne
Craig Wayne

Reputation: 5060

calling php and javascript functions with one button

This is what I'm trying to achieve, but my Googling hasn't helped:

I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.

PS I understand that PHP is server side as opposed to JS. But surely this is possible.

Upvotes: 1

Views: 411

Answers (5)

Craig Wayne
Craig Wayne

Reputation: 5060

Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post. W3Schools PHP & AJAX communication

Upvotes: 0

Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17471

Option 1

Pass a php array with all possible values to the client side using something like this on the client side:

var opt_values = [<?php echo $php_values; ?>]; //javascript array

or

var opt_values = <?php echo json_encode($php_values); ?>; //json object

Option 2

Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:

PHP function:

$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))     
{
    $bus = array(
        'id' => $row['id'],
        'text' => $row['name']
    );
    array_push($json, $bus);
}

return = json_encode($json)

Jquery

$('#button-id').click(function(){
//adds a new row to a table dynamically
    $.ajax({
        type: "get",
        dataType: "json",
        url: "/get_values.php",
        success: function (response) {
            var $el = $("#myselect"); //get the select
            $el.empty(); // remove old options
            //Append the new values
            $.each(response, function(key, value) {
              $el.append($("<option></option>")
                 .attr("value", value.id).text(value.text));
            });
        }
    });
});

Upvotes: 1

Itai Sagi
Itai Sagi

Reputation: 5615

here's a simple implementation of such a thing using jQuery's ajax and php.

html

<select data-source-url="/category/list"></select>

javascript using jQuery

$("select[data-source-url]").each(function(){
    var url = $(this).attr("data-source-url");
    var el = $(this);
    $.get(url, function(data){
        for (i=0;i<data.length;i++){
            el.append("<option>" + data[i] + "</option>");
        }
    },"json");
});

category/list endpoint (a php script)

$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";

echo json_encode($list);

a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.

Please note that on initial load of the page, the select box will be empty.

Upvotes: 2

Eric Freese
Eric Freese

Reputation: 1482

Javascript cannot connect directly to a database.

You want AJAX. A basic flow for this functionality looks like this.

  1. Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
  2. In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.

Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.

Upvotes: 1

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

yes ofcourse you can. for storing s php variable in a js ariable you can do like this. before storing it into js variable store the required value in your php variable

var value = '<?php echo $value;?>';

Upvotes: 1

Related Questions