Taccoman
Taccoman

Reputation: 69

How to pass resource from php to javascript

So I have three different separate files:

Now, I want to call a function in PHP through AJAX. To do that, I need to pass $conn.

$conn = sqlsrv_connect($serverName, $connectionInfo);

It's a resource, so I can't use json_encode.

The way I set the everything up now is that the php-file is required in the html so I can use the functions and when I change the value of a dropdown, the js is called.

How can I pass the $conn variable to Javascript?

Regards

Upvotes: 0

Views: 231

Answers (3)

Michael Curry
Michael Curry

Reputation: 989

It doesn't work like that.

You should never be directly making calls to the database from the front-end.

Think of it as three separate levels. Your HTML/JS is the front-end, your PHP is your server, and your Database is on its own level.

So when the user does something on the front-end, say changes the value of a field and you want to update that in the database the following actions should happen:

  • Event triggers on JS
  • AJAX is called as a result of the event being triggered
  • PHP server receives the AJAX request and executes code to modify database
  • (optional) PHP server sends something back to the front-end to tell it that the request was successful

Read up on the concept of MVC: https://developer.mozilla.org/en-US/docs/Web/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture

Upvotes: 2

user8033142
user8033142

Reputation:

First of all include jquery latest version from cdn

  1. Create an API Url, and use POST method

    site.com/api/insert.php // to insert into table
    
  2. Use $.post() api of jquery to send data

    var url = ""; // enter your URL HERE
    var postData = {};  // object of post data with table name, cols and values
    $.post(url, postData, function(data, status) {
           // do what ever you want with data        
    }) 
    

    ps: you can also create diff insertion / selection / update / delete api for different table. (recommended)

Read more about $.post() here

Upvotes: 0

Zain Farooq
Zain Farooq

Reputation: 2964

Try this in php code as I assume functions.php

$conn = sqlsrv_connect($serverName, $connectionInfo);
echo $conn;//Don't try echo anything other

In Javascript

$.ajax({
           type: "POST",
           url: "functions.php",

           success: function(data)
           {
               var conn = data; // here is your conn which comes from php file
           }
      });

Upvotes: 0

Related Questions