Capture instance of PHP class and call an instance function from JS - javascript

I have a page that asks for a country code in a ComboBox, and I want it to load some other ComboBox with certain values that depend on the first one.
The secondary data should be loaded using a function inside a PHP class, whose instance I need to capture. I'm still not very familiar with AJAX and jQuery, so that's my problem.
My code is like this (I omitted the most obvious parts, of course):
new.html
<script src="findIDTypes.js"></script>
<form>
<select id="country_id" onchange="findIDTypes(this.id)">
<option value="AR">Argentina</option>
<option value="BR">Brazil</option>
</select>
</form>
dbfunctions.php
class DBConn {
public function GetInstance($host = FALSE, $user = FALSE, $pass = FALSE) {
static $_instance = FALSE;
if ($_instance === FALSE) {
if ($host == FALSE || $user == FALSE || $pass == FALSE) {
// Error! Can't instantiate
}
$_instance = new DBConn($host, $user, $pass);
}
// OK!
return $_instance;
}
public function findIDTypes($country_id) {
// Returns array of value pairs (Code, Description)
}
}
findIDTypes.js
function findIDTypes(value_to_search) {
// ???
}
What I need my AJAX/jQuery (not sure which) function to do is:
Capture the instance of DBConn
Call the instance function "findIDTypes()" in the PHP class
Retrieve the array of (C,D) pairs and load them, one by one, on the secondary combobox
What exactly do I need to do to complete steps 1 and 2, if it's possible at all?
Thanks! :)

php and javascript are entirely different, and while you can use php to generate javascript code before the page is rendered, you cannot call php functions from javascript.
This is because php runs on the server, and javascript (which the exception of Node.js!) runs in the browser.
To solve this, you need to expose your php as an API using HTTP GET or POST methods.
Steps
Build your php page to accept $_GET url query parameters or $_POST parameters, in one form or another.
Decide upon a method of communicating your data on the server end back to your browser's javascript/ajax. For this, I highly recommend json for an innumerable number of reasons. It easily integrates with php via json_encode() and json_decode(), and javascript via JSON.parse() and JSON.stringify().
Once you've established your "API" as it were in php, you can easily use jQuery's $.ajax to send and retrieve data to your php. Since your example is relatively simple, it may be as easy as something like http://yoursite.com/?init=DBConn_GetInstance and handling the $_GET['init'] function, then outputting the results of your function.

Related

How to pass resource from php to javascript

So I have three different separate files:
functions.php (all functions for the database)
main.html (my main program)
main.js (all javascript functions)
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
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
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
}
});
First of all include jquery latest version from cdn
Create an API Url, and use POST method
site.com/api/insert.php // to insert into table
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

Sending array from php to javascript, parsing PHP variables to JS

I want to be able to pickup variables from php example: public var $PHPVariable = "Hello World"; or something in that way. But how will I possible send this to javascript without XML HTTP(S) requests?
PHP File example
<?php
public var $secure_connection = $secure['ssl']['type']['connection']['valid_id'] // This is equal to (int)25
public var $userRank = $_SESSION['user']['active']['secure']['rank']; // Returns Admin or Default
public var $userFullName = $_SESSION['user']['unactive']['secure']['require']['name']['first'.'middle'.'last']
?>
JavaScript file / document
function get(variable, type){
if(!empty(variable) && !empty(type)){
if(!exist(variable)){ // the exist function will check if the public variable exist in the php setting file.
return 'The variable does not exist!';
}
if(type=='output'){
return recieve(variable, 'As String'); // the recieve function will collect the data from the public variable.
}
if(type=='setting'){
return recieve(variable, 'As Setting') // returning the recieve function as a setting will basicly mean it can return anything such as string/array/integer/boolean
}
}else{
return 'ERROR: Please fill in required fields!';
}
}
if(get('secure_connection', 'setting')==25){/* Returns true */}
if(get('userRank', 'setting')=='Admin'){/* Returns true */}
if(get('userFullName', 'output')){/* Returns the variable as a string no matter what the php variable was in ex int/boolean*/}
Take in mind I want to do this without XML http(s) requests!
Thanks for taking your time help! Richard.
EDIT
I know it is possible sending JSON Requests to a PHP Object class, which could solve this solution but it is not secure enough for my website, though it allows the user to even edit their own rank into other ranks or change SQL Connection properties of databases and change the row values, etc. Just with enough knowledge of using the (example) Chrome Console to use the function to change the php files content. Which will result resolving no ones problems.

Passing data from PHP to JS and JS to PHP

Hi I'm trying to learn PHP and javascript, therefore I tried to do an exercise about passing data but I didn't understand the js function and currently unable to do anything.
Here is the code
php-code.php
$v1=$_GET['v1'];
$v2=$_GET['v2'];
$v3=$_GET['v3'];
//Some operations about them
echo $output;
my-js.js
var v1 = $('#v1 option:selected').val();
var v2 = $('#v2 option:selected').val();
var v3 = $('#v3 option:selected').val();
//This is where I want to pass these variables to my php file and get the output
//But i don't know how
js-execute.php
//this is where my js gets the variables at first
PHP is a server-side language while JavaScript is a client-side one. This means that PHP will be executed when someone requests a page, but the browser will only get the result of the PHP code. On the other hand, JavaScript is sent to the browser and the browser will execute it at the appropriate time (when the page loads or when an event happens). That's why if you look at the source code of a page, you will be able to see the JavaScript code, but never the PHP code.
If you want to pass values from JavaScript to PHP, you will need to make a remote call to a PHP file. PHP isn't like JavaScript – once it's done running its code, it won't be able to respond to anything without a reload of the page.
The easiest way to send something to a PHP file and fetching the result with JavaScript can probably be achieved with JQuery. It has a function $.get which will fetch a given URL. Just be sure to properly validate the input on the server side – never trust user input.
JavaScript (using JQuery to send v1, v2 and v3 to page.php)
function requestPage(v1, v2, v3) {
$.get('page.php', {'v1':v1, 'v2':v2, 'v3':v3}, function(data) {
alert(data);
});
}
PHP (a trivial example)
// Be sure to properly validate input!
if(isset($_GET['v1']) && is_scalar($_GET['v1'])) {
echo strrev($_GET['v1']);
}

How to check if table is empty using cakephp and AJAX?

how do we check if table is empty with cakephp and ajax? In my index.ctp I have an image that when clicked, it will inform the user if the table is empty or not. If it's empty, an alert box will appear, and if it's not, it will be redirected to another page.
<?php
echo $this->Html->image('movie.png', array('onclick'=>'check()'));
?>
JAVASCRIPT:
function check(){
//check browser comp, create an object
object.GET("GET", url, false);
//rest of the code here
}
MoviesController.php
function index(){
//something here
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
I know how to do it using the normal PHP coding, but with cakephp, and since I am new, I dont know yet. For regular PHP coding, I used the GET method for AJAX, and I can specify the URL for the PHP query inside the GET function. I don't know how to do it using cake.
You need to set the layout to AJAX then render your view. I strongly recommend not to use the index() method for this. Instead you can define a whatever() method in the MoviesController:
function whatever(){
//It is not a bad idea to do this only for GET - use the RequestHandlerComponent
$this->layout = 'ajax';
$moviecount=$this->Movies->find('count');
$this->set('moviecount', $moviecount);
}
The in the view file whatever.ctp:
echo json_encode(array('moviecount' = $moviecount));
//It is a good idea to add an isset() ternary check here like:
// echo isset($moviecount) ? json_encode(array('moviecount' => $moviecount)) : json_encode(false);
Notice that I am creating an array and encoding it to JSON. This is the way to convert variables to and from JSON. To decode use json_decode() of course.
The Client-side code really depends on what you're using to make the AJAX call but let us say that the call succeeded and you got the data back in the data variable:
//Make the AJAX call to example.com/movies/whatever via GET
//Check what data is but it should definitely be an array
if (data['moviecount']) {
//If moviecount is 0 it will go in the else statement - 0 i falsey
window.location = 'example.com/redirect/url';
} else {
alert('No records');
}
I advice against using alert() to inform the user that there are no records. Better put it somewhere in the page - in some div or whatever. Since this is an AJAX request it could be repeated many times. Consecutive use of alert() is not really user-friendly in this case.

Howto: PHP/Javascript communication

As I'm developing my WebIDE, I keep coming up with questions that I cannot answer myself. This is because the project is supposed to help others create what they would "normally" create, but faster (i.e. as automated as possible). In this light, my question is how to you implement a PHP backend?
Here is what I do. I like to create "functions" that the client JavaScript can call. Usually, I send (via POST and JSON) a variable called "action" which holds the name of the "function" I am calling (as well as any arguments I wish to send it). The PHP code, then, looks something like this:
if(issset($_POST['action'])) {
//function foo(arg1,arg2)
if($_POST['action'] == 'foo') {
$arg1 = $_POST['arg1'];
$arg2 = $_POST['arg2'];
//do stuff
}
}
I can still reference other real functions I create in PHP, but I find that this is a nice way to organize everything and easy to implement in both JavaScript and PHP.
What do you do?
Edit 1: Ok, based on the first two answers to this question, I do not think I am explaining myself well.
I am asking how do you create a PHP back end. The idea is that you have your AJAX client written in JavaScript (or maybe something else, it doesn't matter), and then it will call your backend PHP with POST or GET data. Based on this data, your backend will do what it needs to do (maybe it will simply update the database, and maybe even return information, again: it doesn't matter).
The question now is: how do you tell it what to do? What do you send via POST/GET and how do you interpret it in your backend?
I send all data to the backend in a big GET array.
actionpage.php?action=post&parameters[parameter1]=value1&parameters[parameter2]=value2
If you print_r($_GET), on the PHP side you'll see:
array(
"action" => "create",
"parameters" => array("parameter1"=>"value1","parameter2"=>"value2")
)
What this does is allow you to loop through your parameters. You can say in the pap
if($_GET['action'] == 'create'){
foreach($_GET['parameters'] as $key=>$value){ //something
The question now is: how do you tell
it what to do? What do you send via
POST/GET and how do you interpret it
in your backend?
Choose your own conventions. For example use an "action" value in your JSON data that tells the action, then add more parameters. You can spy on various websites's Ajax messages with Firebug extension in Firefox if you want to see what other websites do.
For example the Json POST data could be:
{
action: "create",
fields: {
firstname: "John",
lastname: "Doe",
age: 32
}
}
To which you could reply with the ID of the newly created record.
To delete the record:
{
action: "delete",
keys: {
id: 4654564
}
}
etc.
In the php ajax handler you could have something as simple as a switch:
$jsonData = Services_Json::decode($_POST['json']);
switch ($jsonData->action)
{
case "save":
if (validate_json_data($jsonData->fields))
{
UsersPeer::create($jsonData->fields);
}
break;
case "delete":
/* etc */
}
// return a json reply with
$jsonReply = new stdClass;
$jsonReply->status = "ok";
$jsonReply->statusMessage = "Record succesfully created";
echo Services_Json::encode($jsonReply);
exit;
Javascript, say prototype Ajax.Request responder function will output the error message in a specially created DIV if "status" is not "ok", etc...
I use a front page controller which handles my routing. If you set up mod-rewrite you can have very clean endpoints where the first segment of your url refers to the controller (class) and then the subsequent segments would refer to the methods inside followed by the parameters being passed to the method.
http://domain.com/class/method/param1/param2
this website will answer all your ajax questions. I found it really helpful.
http://ajaxpatterns.org/XMLHttpRequest_Call
You need to organize functions? It's called 'class'.
/// todo: add error processing
$name=$_GET['action'];
$args=json_decode($_GET['args']); /// or just subarray, doesn't matter
/// 'Action' is constant here but in reality you will need more then one class for this
/// because you will want modules in your framework
if(method_exists('Action',$name))
call_user_func_array(array('Action',$name),$args);
else { /* incorrect parameters processing */ }
/// Ajax-available functions are here
class Action
{
public static function action1()
{
echo 'action1';
}
public static function action2()
{
echo 'action2';
}
}
I do something very similar. What you need is a JSON object to pass back to the javascript. When you are done with your PHP, you can call json_encode to pass an object back to the front end. From there you can do more with it in Javascript or format it however you want.
There is more information on a similar question here:
Best way to transfer an array between PHP and Javascript
Edit: After reading your edit, I think what you are doing is fine. When you send the AJAX request from Javascript include a variable like "action", or whatever youd like. From there you can check what the action is via a case and switch statement.
I usually write the php functions as normal functions.
fn1(arg1, arg2){
//do stuff here
}
fn2(arg3){
//do stuff here
}
I pass the name of the function in a variable called action. Then do this:
foreach($_POST as $key => $value)
$$key = $value;
To assign create variables of the same name as the arguments.
Then use a switch-case to call the appropriate function like so:
switch($action){
case 'fn1':fn1(arg1,arg2);
break;
case 'fn2':fn2(arg3);
break;
}
Is this what you are looking for?
Edit: You could use the PHP SOAP and XML-RPC extension to develop a webservice, where if you specify the function name in the SOAP request, that function will be automatically executed (you don't have to write the switch-case or if). I've used it in Java, but am not sure how exactly it works in PHP.

Categories

Resources