Can I call the function from php class using jquery ajax? - php

I begin with an object-oriented programming in php.
I want to do the logging - using ajax and jquery.
EDIT: Can I call the function ajax from file jquery.php - using jquery AJAX?
//FILE jquery.php
class jquery {
public function ajax() {
echo "result";
}
}

If you make an ajax call similar to this :
http://example.com/ajax.php?firstParam=1
Within your ajax.php file you can do something like this :
switch($_GET['firstParam']){
case "1":
callYourFunction();
break;
case "2":
someOtherFunction();
break;
}
This is a very stripped down example... In a real world case you would have to take security into account and sanitize any information you are getting from outside your server (i.e. from a user).
The names I have given are only place holders - you can change the function/variable names to whatever you feel comfortable with.
I hope this sheds some light on your conundrum.

Not sure if you completely understand what AJAX is, but it's an acronym for Asynchronous JavaScript and XML. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behaviour of the existing page. That's it.
This I believe is what you're looking for (though its not OOP, but im not writing an entire OOP login to try answer your question)
File: login.php
<?php
$db = new PDO("mysql:host=localhost;dbname=database", SQL_USER, SQL_PASS );
$stmt = $db->prepare('SELECT user_id, user_activated FROM users WHERE ( username = AND user_password = ? LIMIT 1');
$stmt->execute( array( $_POST['u'], $_POST['p'] ) );
if( $stmt->rowCount() == 1 )
{
// Authentication session storage stuff here
echo 'Logged in';
}
else
{
echo 'bad login';
}
?>
So you could have a HTML page with something like:
<div id="results"></div>
<input type="text" id="txtUsername" /> <br />
<input type="password" id="txtPassword" /><br />
<button id="cmdLogin">Login</button>
<script>
$(document).ready(function(){
$("#cmdLogin").click(function(){
$u = $("#txtUsername").val();
$p = $("#txtPassword").val();
$.ajax({
type: "POST",
url: "http://yoursite.com/login.php",
data: "u="+u+"&p="+p
}).done(function(results) {
$("#results").html(results).hide().fadeIn();
});
});
});
</script>
Also, keep in mind this code is un-tested and written it as replying to this, so don't treat this as a solution to what you're wanting, but rather a resource to help you to implement what it is you're asking for.

You cannot call a class directly - but you can fetch the result of an execution.
Here an example how you can call it nearly direct - but don't use this for critical login code.
<?php
$ftcn = $_GET['getname'];
$bc = new ReallyBadCode();
$bc->$ftcn();
class ReallyBadCode{
function test(){
}
function __call($name, $args){
$this->$name($args);
}
}

Related

How to organize your code PHP

I am new to PHP and I am wondering how is the best way to organize your code. I have been trying to do something with a form (form.php) on the client side to talk to a remote server using PHP (testexec.php). I have come down to the issue where my testexec.php needs to access a variable from the form.php file and so now I am wondering if I should just put all my code in form.php so I don't have to call variables from a different php file. How would you guys organize your code in this situation.
form.php
<div class="box1">
<form method="post">
<label class="col">Up/Dowb</label>
<span class="col">
<input type="radio" name="option" id="r1" value="1" />
<label for="r1">Up</label>
<input type="radio" name="option" id="r2" value="2" />
<label for="r2">Down</label>
</span>
<span class="col">
<input type="submit" class="button"/>
</span>
</form>
</div>
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(".button").click(function(event){
if ((document.getElementsByName("gateway")[0].value == '')) {
alert('Gateway Required!');
return false;
}
else if (document.querySelectorAll('input[type="radio"]:checked').length < 1) {
alert('Please Choose Up/Down Value!');
return false;
}
else {
//alert('Sucess!');
event.preventDefault();
$.ajax({
url:"testexec.php",
type: "POST",
data: {option: $('input[type=radio]:checked').val()},
dataType: "text",
success:function(result){
$('#div1').html(result)
}
});
return true;
}
});
</script>
<div id="div1"></div>
</body>
</html>
testexec.php
$gateway = '';
$user = 'user';
$pwd = 'pass';
function cleanInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ( $_SERVER['REQUEST_METHOD'] == 'POST'){
$gateway = cleanInput($_POST['gateway']); //need to get the value of gateway from form.php
//create the ssh connection
if ($connection = #ssh2_connect($gateway, 22)) {
ssh2_auth_password($connection, $user, $pwd);
if(isset($_POST['option']) && $_POST['option'] == 1) {
$stream = ssh2_exec($connection, "/tmp/user/testscripts/up.sh");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo '<pre>' . stream_get_contents($stream_out) . '</pre>';
}
if(isset($_POST['option']) && $_POST['option'] == 2) {
$stream = ssh2_exec($connection, "/tmp/user/testscripts/down.sh");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo nl2br(stream_get_contents($stream_out));
}
}
}
?>
So now i have to somehow get the value of 'gateway' from my form.php for the following code to work:
$gateway = cleanInput($_POST['gateway']);
So I was wondering if this is good practive to seperate things like this?
I see no advantage in combining the scripts. There is no magic to $_POST. It only exists when a script has been the TARGET of a POST, and it doesn't matter if the target is the same script that originally had rendered the form, or a different script.
The only advantage to combining form code into a self-posting, all-in- one version, is when you have iterative error handling.
In that situation, frequently you want to do some server side validation, and if the form doesn't validate, need to send a response with the another form with an error, and usually with the original form elements already filled in, and typically with some visual indication as to which elements caused the problems.
It's much cleaner to have this all in one place, so you aren't reinventing the wheel with the form.
However, moreover, any script is cleaner and easier to read when you separate logic from presentation.
This is a big reason why people use template libraries like smarty or twig, an why every MVC framework comes with some sort of template system.
Even in your case, you could move the form data into it's own seperate script and include it with something like:
require_once('form_frm.php');
In your case, form.php has no logic whatsoever currently, so I see no major advantage to doing this at the moment.
I would recommend however, that you consider each function you are using, and why you are using it.
Stripslashes() for example, appears to have no value to you in this script, and in fact, stripslashes has had very little use for many years now, as magic_quotes_gpc() was deprecated long ago.
Escaping was a function of SQL database string handling, and due to the issues with different character sets and localization, if you needed to add escape characters, there were better database specific methods like mysql_real_escape_string() which take into account the character set of the client data and database.
At this point in time, most everyone knows that you should be using bind variables for adding string data to SQL queries, which essentially eliminates the need for any escaping of quotes, so there is no need for add slashes or mysql_real_escape_string() whatsoever, and the world is better for it.
If you are not calling addslashes(), why are you calling stripslashes()?

How to pass server data into React component

I'm just learning React, and while I understand many of the basics there is one concept I haven't seen anyone cover: how do I take information loaded via the server-side language (e.g. PHP) and use it when loading up the React view?
I would have expected that I'd just have the RenderDom call in my php view, such as:
// In the pre-compiled JSX file
var Greeting = React.createClass({
render: function() {
<div>
<h1>Hello, { this.props.username }</h1>
</div>
}
});
// In my PHP view
<script type="text/jsx">
ReactDOM.render( <Greeting username="<?php echo $username; ?>"/>, document.body );
</script>
But that doesn't work; nothing is displayed. I'm thinking that's because the text/jsx script area doesn't get executed...but of course if I remove that there's a syntax error.
Soo...I'm just wondering, what's the typical method for taking data loaded up from the DB and passing it into a React component?
Method 1: Define a global variable.
In your main PHP file:
<script>
window.reactInit = {
username: <?php echo $username; ?>
};
</script>
In your component:
class Greeting extends React.Component {
constructor(props) {
super(props);
this.username = reactInit.username;
}
}
If you use Redux, you may find this method particularly useful. Because ANY of your reducers can access this global variable during building of the initial state.
Method 2: Use data-* attributes.
<div id="app" data-username="<?php echo $username; ?>"></div>
All data-* attributes are passed by using {...app.dataset}.
const app = document.getElementById('app');
ReactDOM.render(<Greeting {...app.dataset} />, app);
Now you can access your server data as ordinary props.
class Greeting extends React.Component {
constructor(props) {
super(props);
console.log(this.props.username);
}
}
This method is not so flexible as the previous one, but seems to be more consistent with React philosophy.
The React way would be to load in the data via a RESTful API.
However, you could look into serverside rendering of React components with PHP V8JS. Not sure how stable it is, but if, it would be a very good/better alternative to the AJAX call on the client. It would look somewhat like this:
// the library
$react_source = file_get_contents('/path/to/build/react.js');
// all custom code concatenated
$app_source = file_get_contents('/path/to/custom/components.js');
$rjs = new ReactJS($react_source, $app_source);
$rjs->setComponent('MyComponent', array(
'any' => 1,
'props' => 2
)
);
/// ...
// print rendered markup
echo '<div id="here">' . $rjs->getMarkup() . '</div>';
If you actually want to render this in the browser, you can use plain Javascript instead of JSX:
<?php $username = 'Eric Andre'; ?>
<script type="text/javascript">
ReactDOM.render(React.createElement(Greeting, { username: "<?php echo $username; ?>" }), document.body);
</script>
Another option would be to transform the JSX into plain Javascript with babel-browser and use <script type="text/babel">. Keep in mind that babel-browser is not in active development anymore and also not intended for production use.
<?php $username = 'Eric Andre'; ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js"></script>
<script type="text/babel">
ReactDOM.render( <Greeting username="<?php echo $username; ?>"/>, document.body );
</script>
You could also take a look at https://github.com/erikras/react-redux-universal-hot-example for some examples on how to call RESTful APIs from a client.
Specifically it uses superagent to make the AJAX calls:
https://github.com/visionmedia/superagent

ajax call to check duplicate data

Here is the form to have ajax check out user existence.
<!DOCTYPE html>
<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.fail(function()
{
$('#user').html("This user already exists");
}
);
}
</script>
</html>
And here is the userexists.php module
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username=$_POST('username');
$sql="SELECT username FROM ".TABLENAME." WHERE username=".$username;
$query=mysql_query($sql);
if(0!=mysql_numrows($query))
{
//
}
else
{
}
?>
But I am stuck to really figure out how the ajax function actually works, what should I enter the blank field after I know that the entered username has been used, for example ? I don't understand ajax at all.
[UPDATE]
Thank you, I understand it now, I have got several answers, don't know which one to choose as the best reply. No option to choose all.
You have a lot of mistakes in your code, try codes below:
<!DOCTYPE html>
<html>
<head><title>Register new user!</title>
<script src="jquery-1.7.1.min.js"></script>
</head>
<body>
Username:
<input type="text" name="username" id="username"/><span id="user"></span><br/>
Password:
<input type="password" name="password" id="password"/><br/>
<input type="button" value="Register" name="submit" id="submit" onclick="register_user();"/>
</body>
<script>
function register_user()
{
$.ajax({
type: "POST",
data: {
username: $('#username').val(),
},
url: "userexists.php",
success: function(data)
{
if(data === 'USER_EXISTS')
{
$('#user')
.css('color', 'red')
.html("This user already exists!");
}
else if(data === 'USER_AVAILABLE')
{
$('#user')
.css('color', 'green')
.html("User available.");
}
}
})
}
</script>
</html>
And for your php code:
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn=mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username = mysql_real_escape_string($_POST['username']); // $_POST is an array (not a function)
// mysql_real_escape_string is to prevent sql injection
$sql = "SELECT username FROM ".TABLENAME." WHERE username='".$username."'"; // Username must enclosed in two quotations
$query = mysql_query($sql);
if(mysql_num_rows($query) == 0)
{
echo('USER_AVAILABLE');
}
else
{
echo('USER_EXISTS');
}
?>
Since you're new to AJAX, let me try and help you a bit better with some explanations as we go.
AJAX stands for Asynchronous Javascript And XML. Using it, you can make a request to another page and have your original page behave differently according to the results returned by the other page.
So how is this useful? Well; You could set an onblur even on a 'username' field to check a remote script to see if a username is already in use. (Which you are already doing in your current setup. Good work!)
Firstly; the .fail() is telling your current page "If the ajax request fails, lets do this code". This is called a callback. A callback is a function of javascript code to execute when the asynchronous request is finished.
So what you want to actually do is use the .done() method. This tells your jQuery request "Hey, when you're done doing this request, do this chunk of code. While you're doing that, im going to sit here and handle anything else that happens".
So you can see there is a slight difference between using .done() and .fail(), however I can see how you can be easily confused with .fail() being new to ajax.
So lets get back to your current problem. Lets modify the ajax to something more like this:
$("#submit").click(function()
{
$.ajax({
type: "POST",
data: "username="+$("#username").val(),
url: "userexists.php"
})
.done(function(response){
$('#user').html(response);
});
});
What this does is bind an onclick handler for your submit button with the id "submit". So now you can remove onclick="register_user". Secondly, it says, "Hey webpage, go send userexists.php the username textbox value with the parameter name username. When you've finished that request, set the html of #user to the response.
So off it goes and does it.
Now your PHP file, you can do:
<?php
// connection to the db
define(IPHOST,"localhost");
define(DBPASSWORD,"");
define(DBUSER,"root");
define(DATABASE,"ajaxtest");
define(TABLENAME,"at");
$conn = mysql_connect(IPHOST,DBUSER,DBPASSWORD) or die(mysql_error());
mysql_select_db(DATABASE) or die(mysql_error());
$username = mysql_real_escape_string($_POST['username']); // Stop some MySQL injections
$sql="SELECT username FROM ".TABLENAME." WHERE username='$username'";
$query=mysql_query($sql);
if(mysql_numrows($query) == 0)
{
echo 'Username is available!'
}
else
{
echo 'Sorry, username is in use.';
}
?>
So once your script does its query, if it finds a result it will say in the HTML div "Username is available!". Otherwise, if it finds a match, it says "Sorry, username is unavailable".
Hope this helps you understand ajax a little better!
It's technically up to you. (For example) You could return a "1" for "user exists" and "0" for "user doesn't exist", or return a more detailed XML. The client app (Javascript) will read the returned result and print out an appropriate message to the user.
The .fail method should be used in case your function actually fails (server side error etc). So it doesn't seem appropriate for what you're trying to do. I would put in your ".done()" code a test of the returned values as described above and print out the correct message.
Javascript:
.done(function ( data ) {
if(data == "0")
alert("Your username is OK");
else
alert("Your username is already used");
});
PHP:
if(0!=mysql_numrows($query))
{
echo "0";
}
else
{
echo "1";
}
Function .fail in ajax is used when server return unexpected datas. But your php code dont return anything. Use something like this:
function register_user()
{
$.ajax(
{
type:"POST",
data:username,
url:"userexists.php"
})
.done(function(_return)
{
if(_return)
{
if(_return['status']=='yes')
{
$('#user').html(_return['msg']);
}
}
})
.fail(function());
}
And in php:
if(0!=mysql_numrows($query))
{
$return = array('status'=>'yes',
'msg'=>"User alredy exist");
echo json_encode($return);
return true;
}
Now you can add more conditions with many statuses and parse it in javascript.

Querying a function in functions.php?

I have a jQuery code that is going to check when the user is near the bottom of the page. That's not the problem though. This jQuery is going to send a AJAX request, giving it some details on what to load when the user is near the bottom of the page. The code looks a bit like this at the moment:
$("<div>").load('?ajax=y&offset=something', function() {
$(".empty-div").append($(this));
setTimeout(function(){ console.log('after', $(document).height()); }, 0);
setTimeout(function(){ console.log('after', $(window).height()); }, 0);
});
My main problem is that I don't know what to query or how to go about sending the information to the PHP function in functions.php. For example, I have at the moment this as my PHP function (until it's working):
function get_posts_page() {
if(isset($_GET['offset'])) {
echo"Hello!";
}
}
I'm aware the wordpress has add_action and all that but I have no idea what I would apply as an action to either function to make the PHP recieve the data the Javascript is sending. Is there a URL where all functions are parsed or something? Thanks for any help in advance. So how do I get the data from the Javascript to the PHP function in functions.php, in my theme directory?
I just made a video to show you how to use the add_action request in WordPress. You can watch it here.
Here's my javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
$('#branding img').click(function() {
$.post('<?php bloginfo('siteurl') ?>/wp-admin/admin-ajax.php', {
action: 'my_unique_action',
offset: 5
}, function(data) {
$('#content').prepend('<p>' + data + '</p>');
});
});
</script>
And the php that I used in functions.php
// Make sure it runs when the user is logged in,
// and when they are not.
add_action('wp_ajax_my_unique_action', 'get_offset');
add_action('wp_ajax_nopriv_my_unique_action', 'get_offset');
function get_offset() {
if( isset($_POST['offset']) ) {
echo 'Your ajax request was successful. Here was your offset: <strong>' . $_POST['offset'] . '</strong>';
}
die;
}
Reference: http://codex.wordpress.org/AJAX_in_Plugins
You're trying to call a PHP function from Javascript, correct?
You'll need some logic on some page which calls get_posts_page(). Either you can create a new page getPostsPage.php?offset= or you can put some logic in functions.php, something like
if(isset($_GET['function']) {
switch($_GET['function']) {
case 'get_posts_page':
get_posts_page();
}
}
However, the former approach is recommended; you don't want someone to be able to modify the function parameter and access deleteAllPosts() maliciously.
Therefore:
// getPostsPage.php
require PATH . 'functions.php';
get_posts_page(); //checks $_GET['offset']
And remember to fail gracefully (do not expose an error message) if 'offset' is not set, or whatever.

Load PHP function with jQuery Ajax

I have a file which is loaded at the top of my document, which is called Videos.php. Inside that file are several functions, such as getYoutubeVideos. On some pages, I need to call upon that function several times (up to 50), and it of course creates major lag on load times. So I have been trying to figure out how to call that function in, only when it is need (when someone clicks the show videos button). I have very little experience with jQuery's ajax abilities. I would like the ajax call to be made inside of something like this:
jQuery('a[rel=VideoPreview1).click(function(){
jQuery ("a[rel=VideoPreview1]").hide();
jQuery ("a[rel=HideVideoPreview1]").show();
jQuery ("#VideoPreview1").show();
//AJAX STUFF HERE
preventDefault();
});
Ok I have created this based on the responses, but it is still not working:
jQuery Code:
jQuery(document).ready(function(){
jQuery("a[rel=VideoPreview5]").click(function(){
jQuery("a[rel=VideoPreview5]").hide();
jQuery("a[rel=HideVideoPreview5]").show();
jQuery.post("/Classes/Video.php", {action: "getYoutubeVideos",
artist: "Train", track: "Hey, Soul Sister"},
function(data){
jQuery("#VideoPreview5").html(data);
}, 'json');
jQuery("#VideoPreview5").show();
preventDefault();
});
jQuery("a[rel=HideVideoPreview5]").click(function(){
jQuery("a[rel=VideoPreview5]").show();
jQuery("a[rel=HideVideoPreview5]").hide();
jQuery("#VideoPreview5").hide();
preventDefault();
});
});
And the PHP code:
$Action = isset($_POST['action']);
$Artist = isset($_POST['artist']);
$Track = isset($_POST['track']);
if($Action == 'getYoutubeVideos')
{
echo 'where are the videos';
echo json_encode(getYoutubeVideos($Artist.' '.$Track, 1, 5, 'relevance'));
}
$.post('Videos.php', {
'action': 'getYoutubeVideos'
}, function(data) {
// do your stuff
}, 'json');
In your php code, do something like this:
$action = isset($_POST['action'])? $_POST['action'] : '';
if($action == 'getYoutubeVideos')
{
echo json_encode(getYoutubeVideos());
}
Then data in your JavaScript function will be the array/object/value returned by getYoutubeVideos().
I would do the JS part like ThiefMaster describes, but the php part would i handle a little bit different.
I would do something like this:
if(isset($_POST['action'], $_POST['par1'], $_POST['par2'])
{
$action = $_POST['action'];
$result = $this->$action($_POST['par1'], $_POST['par2]);
echo json_encode(result);
}
But be careful, if you have some methods in the class which shouldn't be called by the user, trough manipulating POST data, then you need some way to whitelist the methods the JavaScript may call. You can do it by prefixing the methods i.e:
$this->jsMethod.$action(....);
or by simple if/switch condition.
Ok here is what ended up working:
PHP CODE
$Action = isset($_POST['action']);
if($Action == 'getYoutubeVideos')
{
getYoutubeVideos($_POST['artist'].' '.$_POST['track'], 1, 5, 'relevance');
}
JQUERY
jQuery.ajax({
type: "POST",
url: "/Classes/Video.php",
data: "action=getYoutubeVideos&artist=artist&track=track",
success: function(data){
jQuery("#VideoPreview1").html(data);
}
});
json encoding was annoying, not sure if json is hte better way of doing it, I could actually use the jQuery.post function as well, because the real problem was with the PHP. If anyone knows about any security problems with the method I am doing, please let me know. Seems fine though.

Categories