AJAX load specified function from php file - javascript

I am currently using the script below to fill some divs with data i need
function fillLeagues(){
var load = $.get('drawleague.php');
$(".really").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".really").html('failed to load');
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".really").html(res);
});
load.done(function() {
console.log( "Completed" );
});
}
I was wondering if it was possible to call a certain function in the drawleague.php file that will return the info since i don't wanna use say 10 php files to fill 10 divs for example.

Ajax & PHP are different technologies, which means they can only communicate in certain ways
This means that it doesn't matter if you have 1 or 100 files, if you can call the functions inside the file, you can keep it to one file
I would recommend this:
Params
jquery $.GET parameters passing in the url
You can pass parameters through your $.GET request to your PHP file. This means inside your PHP, you can take these params & determine the output
Because you havn't posted any PHP code, here's what you might be able to use:
<?
switch ($_GET["name"]) {
case "x":
return $image_x;
break;
}
}
?>

I'd suggest you use get parameters in order to achieve this behavior. Pass the function name via Get parameter and call it in your PHP file. Of course you need to create some kind of protection. See below (pretty provisoric).
<?php
$param = $_GET['p'];
$whitelist = [
'func1',
'func2',
'func3'
];
if(!in_array($param, $whitelist))
die("Sorry, no manipulating");
call_user_func($param);
function func1()
{
//Some stuff
}
function func2()
{
//Some stuff
}
function func3()
{
//Some stuff
}
?>
Then pass the param in your JS part:
var load = $.get('drawleague.php?p=func1');

Related

How do I get data from Javascript function and save it to a user's custom meta field in php?

I'm working with a service that automatically registers my user's devices with Onesignal.
I call the function on login by calling gonative_onesignal_info(); inside script tags (full function will be below). That registers devices perfectly fine with Onesignal.
Now, according to the service's documentation, I can POST it to my server via AJAX, which is what I'm struggling with. From the documentation for the service, if you call gonative_onesignal_info() like this:
function gonative_onesignal_info(info) {
console.log(info);
}
... info will look like this:
{
oneSignalUserId: 'xxxxxxx',
oneSignalPushToken: 'xxxxxx',
oneSignalSubscribed: true,
}
And here's my full function:
function onesignal_mobile_registration( $user_login, $user ) {
// Get user data
$user_id = $user->ID;
$user_email = $user->user_email;
?>
<script>
gonative_onesignal_info(info);
</script>
<?php
$oneSignalPushToken = ???;
update_user_meta( $user_id, 'oneSignalPushToken', $oneSignalPushToken);
}
add_filter( 'wp_login', 'onesignal_mobile_registration', 10, 2 );
So, how can I extract the oneSignalPushToken from that Javascript option, and store it in $oneSignalPushToken to be saved to my user? I think I need to use AJAX to pull it out, right? How would I do that?
You can't assign a php variable from javascript because php run in server but javascript run in browser. You must get $oneSignalPushToken value from a php source OR call a ajax from browser when send js data to php variable:
Script place:
<script>
var data = gonative_onesignal_info(info);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'test.php?oneSignalPushToken=' + data.oneSignalPushToken, true);
xmlhttp.send();
</script>
test.php
function onesignal_mobile_registration( $user_login, $user ) {
// Get user data
$user_id = $user->ID;
$user_email = $user->user_email;
$oneSignalPushToken = $_GET['oneSignalPushToken'];
update_user_meta( $user_id, 'oneSignalPushToken', $oneSignalPushToken);
}
add_filter( 'wp_login', 'onesignal_mobile_registration', 10, 2 );
It is important to understand what your code does:
The PHP part will render an HTML page
The JavaScript part will execute in the browser once the page is fully rendered and served
That means you won't be able to retrieve a JavaScript variable in the PHP thread that generates the page, for two main reasons:
JavaScript and PHP execution contexts are not shared at all
JavaScript will execute once the PHP thread has ended
What you have to do is expose an endpoint on your PHP server, let's say POST on a /token URL. You will call this endpoint from your JavaScript with some code like fetch('/token', { method: 'POST', body: info });, then retrieve the token from the $_POST global variable, and then execute your update_user_meta( $user_id, 'oneSignalPushToken', $oneSignalPushToken); line

PHP method calls from Javascript not showing up in Wordpress source

I am running a Wordpress website, and trying to call PHP methods from my Javascript code.
When a button is tapped, the saverFoo() Javascript method is called, and attempts to call the PHP method save_image_data().
function saverFoo() {
var dataURL = canvas.toDataURL();
<?php echo save_image_data(dataURL); ?>;
}
function loaderFoo() {
var loadedImage = <?php echo loadimagedata(); ?>;
console.log(loadedImage);
}
The PHP method's implementation is in the function.php file, and is simply attempting to save some image data (dataURL) in the user's meta
function save_image_data($imageData) {
global $current_user;
update_user_meta( $current_user->ID, 'user_design', $_POST['$imageData']);
}
function loadimagedata() {
global $current_user;
$old_notes = get_user_meta($current_user->ID, 'user_design', true);
return $old_notes;
}
Inspecting my web-page in Chrome, shows me an empty space where loaderFoo () (javascript) is supposed to be calling loadimagedata() (php) , and loadedImage is an undefined variable, when I try to log it, such as:
function loaderFoo() {
var loadedImage = ;
console.log(loadedImage);
}
Not sure what fundamental mistake I'm making here.
Always remember that PHP runs on the server side, and javascript on the client side. So we have an order here, the server receives the request PHP processes what it should process and render the page, only here Javascript will be executed.
In this example, when the 'saverFoo()' function is executed, this function <? Php echo save_image_data (dataURL); ?>; has already been written on the page. PHP will not be able to get the information contained in the dataURL variable, not on this way. To do this, we must make a request to the server with this desired information, but with an "image" is not trivial to do this, as there is a limit on the size of the post when using a normal String field.
function saverFoo () {
    var dataURL = canvas.toDataURL ();
    <? php echo save_image_data (dataURL); ?>;
}
PHP doesn't work that way. It is a pre-processor. It is all run and done server side and the resulting text/html/binary data/whatever is sent out to the client. In the case of a content type of text/html the browser will load it, parse it, render it, and run whatever javascript is called.
How you can mix PHP and JavaScript in-line like that would be to use PHP to fill in variables. For example
alert("<?php print($_SERVER['SCRIPT_FILENAME']); ?>");
would work because the client would see
alert("/path/to/foo.php");
and render that for the user.
To really interact with PHP using JavaScript, you'll want to look into using a http based REST type service and perhaps one of the various popular tool sets like Angular, Vue, etc.

two event functionality in one php file

Hi I'm new to php and jquery. Pardon my php vocabulary.
I have two events in my js file.
1) onsubmit: submits the user entered text to result.php which queries database and displays result. (result.php?name=xyz)
2) onkeyup: makes an ajax call to the same result.php which queries a url and gets json data. (result.php?key=xyz)
My question is if I can check for isset($_GET['key']) in result.php, query url and return json and the rest of the php is not parsed.
Basically is there anything like return 0 as in case of C programming.
The question may seem silly, anyway I can have 2 different php files, but I want to know if it's possible.
Thanks in advance :)
<form action = "result.php" method = "get">
<input type = "text" id = "name" >
<input type = " submit">
</form>
<script>
$('#name').on('keyup',function (e){
input_val = $(this).val();
$.ajax({
url: "result.php?key=" + input_val,
success: function(data){
alert(data);
}
});
});
</script>
If I well understand, you want to know a way to use only one PHP script being able to process either Ajax and "normal" (returning whole page) tasks.
So if yes, this can be easily achieve, using the following schema:
//... some initialization, if needed
if (isset($_GET['key'])) {
// ... do the job for creating the expected Ajax response, say $ajax_response
echo $ajax_response;
exit;
// nothing else will happen in the current script execution
}
// otherwhise you can do all "normal" job here, as usual...
From your question if i have understood properly , you want to return boolean from PHP to Ajax , you can just echo "success" or "failure" based on if condition , and catch that in ajax response and process it in JS.
You can use exit; or die(); to terminate php script. http://php.net/manual/en/function.exit.php

How to convert javascript variable into php variable?

Im new in programming and Im trying to make a program that would register a selected space in my database. I want to convert js variable str into $phpvar php variable. Please help me
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
<?php
include "accounts/config.php";
$phpvar='"+str+"';
mysql_query("INSERT INTO sample (sample) VALUES ('".$phpvar."')");
//echo $phpvar;
?>;
})
});
As the previous speakers already explained, you need to think in terms of client-side running code and server-side running code.
Whenever you want to share a state between those two parts of your application you need some communication mechanism.
Client -> Server
For this you need to make a HTTP request. This can either be a post or a AJAX call. For the latter one just have a look at jquery.ajax as you're obviously already using jQuery anyway.
$.post({
"savesample.php",
{myPostVar: str}
}).done(function() {
alert("sample saved.");
});
Of course you need a serverside script to handle this request:
<?php
$yourVar = $_POST["myPostVar"];
// TODO use mysqli::escape_string or similar!!
mysql_query("INSERT INTO sample (sample) VALUES ('".$yourVar."')");
?>
Server -> Client
This is a lot easier. You can of course use ajax again (GET requests on your php file, which generates a nice javascript-compliant output like JSON).
Or just write your variable to an inline-script-tag:
<script>
<![CDATA[
var yourJsvar = '<?= $yourPhpVar ?>';
]]>
</script>
Further Reading
As your php file is an open gate for all kinds of misuse you should secure it using one-time authorization tokens. Once you are used to the basic concepts, go on with the following topics:
CORS
SQL injection
Authenticated AJAX calls
You'll want to POST to a PHP listener. You don't want PHP tags inside of a JS function in this way. The only reason for PHP tags inside of a JS function would be if you were getting data from PHP to JS, not the other way around.
Look up Jquery post for more information.
The order in which languages run is PHP -> HTML -> CSS -> Javascript. You can NOT go backwards from that order.
On the other hand, you can send Javascript information through an AJAX call. AJAX is an Asynchronous Javascript call which can communicate with PHP!
So for instance (using JQuery)
$.ajax({
url:"someurl",
type:"POST or GET",
data:{query:"SELECT * FROM table"}, //Any data to pass along? Like strings or data?
datatype:"JSON", //This is the return type of the information you want if any
success: successfulHandlerfunction()
error: errorHandlerfunction()
});
That is just some basic grounds. You can find more information on AJAX calls through http://www.w3schools.com/ajax/
I hope this helps!
JS
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
$.ajax({
type: "POST",
url: "save.php",
data: {items: str},
success: function(responce) {
alert(responce);
}
});
});
Create save.php file
<?php
include "accounts/config.php";
$items = $_POST['items']; // Validation HERE!!!
foreach ($items as $item) {
// Insert to DB
}
echo 'Saved';
?>
Separate languages = separate files. (if you can...)
In PHP always check user input.
Use PDO.
This is not possible because the js code is client side and php is server side. What you would need to do is to make an ajax request to a php script in order to send the data for the variable. Here is an example:
Client(browser):
$.ajax({url:"http://domain.com/accounts/config.php?variableToSend=variableValue",success:function(result){
alert("Variable was successfully sent.");
}});
Server(Apache)
config.php
<?php
$varToSend = $_GET["variableToSend"]
//Do whatever you want with the variable
?>

Call different PHP functions from javascript

I realize that calling database from JavaScript file is not a good way. So I have two files:
client.js
server.php
server.php has multiple functions.
Depending upon a condition, I want to call different functions of server.php.
I know how to call server.php, but how do I call different functions in that file?
My current code looks like this:
function getphp () {
//document.write("test");
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// data is received. Do whatever.
}
}
xmlhttp.open("GET","server.php?",true);
xmlhttp.send();
};
What I want to do is something like (just pseudo-code. I need actual syntax):
xmlhttp.open("GET","server.php?functionA?params",true);
Well based on that premise you could devise something like this:
On a sample request like this:
xmlhttp.open("GET","server.php?action=save",true);
Then in PHP:
if(isset($_GET['action'])) {
$action = $_GET['action'];
switch($action) {
case 'save':
saveSomething();
break;
case 'get':
getSomething();
break;
default:
// i do not know what that request is, throw an exception, can also be
break;
}
}
Just do something like this, i hope this will work
xmlhttp.open("GET","server.php?function=functioName&paramsA=val1&param2=val2",true);
You will most likely need to create the mechanism yourself.
Say the URL will look like server.php?function=foo&param=value1&param=value2
On the server side you will now have to check whether a function with such a name exists, and if it does, call it with these parameters. Useful links on how to do it are http://php.net/manual/en/function.function-exists.php and http://php.net/manual/en/functions.variable-functions.php
Otherwise, if you don't want to have it like this, you can always go with if/switch and simply check that if $_GET["function"] is something, then call something etc.
You can use jQuery too. Much less code than pure js. I know pure js is faster but jQuery is simpler. In jQuery you can use the $.ajax() to send your request. It takes a json structured array like this:
$.ajax({
url: "example.php",
type: "POST",
data: some_var,
success: do_stuff_if_no_error_occurs(),
error: do_stuff_when_error_occurs()
});
Here's a dynamic way to solve this issue:
xmlhttp.open("GET","server.php?action=save",true);
PHP Code:
<?php
$action = isset($_GET['action']) ? $_GET['action'] : '';
if(!empty($action)){
// Check if it's a function
if(function_exists($action)){
// Get all the other $_GET parameters
$params = array();
if(isset($_GET) && sizeof($_GET) > 1){
foreach($_GET as $key => $value){
if($key != 'action'){
$params[] = $value;
}
}
}
call_user_func($action, $params);
}
}
?>
Keep in mind that you should send the parameters in the same order of function arguments.
Let's say:
xmlhttp.open("GET","server.php?action=save&username=test&password=mypass&product_id=12",true);
<?php
function save($username, $password, $product_id){
...
}
?>
You can't write the API Call that way:
xmlhttp.open("GET","server.php?action=save&password=mypass&username=test&product_id=12",true);
Keep in mind that it's really bad to send "function namespaces" along with the parameters to a back-end. You're exposing your back-end and without proper security measures, your website will be vulnerable against SQL Injection, dictionary attack, brute force attack (because you're not checking a hash or something), and it'll be accessible by almost anyone (you're using GET using of POST and anyone can do a dictionary attack to try to access several functions ... there's no privileges check) etc.
My recommendation is that you should use a stable PHP Framework like Yii Framework, or anything else.
Also avoid using GET when you're sending data to the back-end. Use POST instead.

Categories