0

I've an application, developed using Yii2 framework. In my application, I've a view.php that has an element and a button. The element <div id="userId"> contain the id of login user, and I want to use the button to get data from column that called header_name from header_table in my SQL based on the id that has got from the element.

This is the code

View.php

<?php
   //some code
?>
<div id="userId" style="display: none"> <?php echo $userId; ?> </div> 
<p>
<button type="button" onclick="getHeader()"class="headerBtn">Use Saved Header</button>
<p>

and

upload_header.js

function getHeader(){
   var id = document.getElementById('userId').textContent;
}

I've successfully get the $userid from view.php in my upload_header.js. But I dont't know how to get the data from sql.

How do I can get data from SQL through javascript?

Thanks, any help will be appreciated :)

Note:

I've read How to get data from database in javascript based on the value passed to the function and try the suggestion, but it didn't solve my case. Thanks

Community
  • 1
  • 1
Blackjack
  • 1,016
  • 1
  • 20
  • 51
  • You don't need a `
    ` for that, you can for instance add the id as `data-id` attribute to the button. Anyway, you need AJAX. It allows you to request a resource from the server, in the background, without leaving the page. You'll request a php script, which in turn sends back the result of the db query.
    –  Jan 26 '17 at 13:43

2 Answers2

0

Use AJAX in getHeader function.

i.e.

$.ajax({url: "server_page.php?userId="+id, success: function(result){
        //Your Result here
    }});

You can return data in JSON format from server page and parse in ajax success area.

Nilesh
  • 62
  • 11
0

You can use ajax for this

upload_header.js

function getHeader(){
   var id = document.getElementById('userId').textContent;
   $.ajax({
       type:"POST", // or GET
       url:"<?= Url::to(['controller-name/function-name']) ?>",
       data:{id:id},
       success:function(response){
            console.log(response); //your data from sql
      }
   });
}

on_your_contoller.php

public function function-name(){
     $id = $POST['id'];
     return User::findOne($id);
}
saurssaurav
  • 715
  • 5
  • 16