Select query using javascript paraments - javascript

I am trying to do a select query using a javascript parameter ($userCard) obtained in the same function ( Code Below ). But an undefined variable error is given, how can pass the parameter in the query ?
<script>
function count() {
$card = "V010";
$userCard = document.getElementById('visitorID');
if($userCard.value.length == 4){
<?php
$connection = connectToSql();
$query = "SELECT * FROM visitorsystem.visitor WHERE cardNo = '$userCard' ";
$result = mysqli_query($connection,$query)
or die("Error in query: ". mysqli_error($connection));
if(mysqli_fetch_assoc($result) >0)
{
echo "Card in Use";
}
?>
}
}
</script>

If I read your question correctly, you are wildly miss reading the usage of PHP and Javascript.
Javascript is a client language, while PHP is executed on the server.
To pass a js argument to a PHP page you have to use a form on your html and retrieve it using $_POST or $_GET variable in PHP
I recommend you go check this Difference between Javascript and PHP

You have the operations of client and server mixed up.
PHP can echo variables to static assets like .html or .js because the PHP compiler runs from the server before the file gets sent to the client.
Once the PHP was compiled and sent to the client, the only way to communicate back to the server is to:
Make an AJAX request
Refresh the page

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.

How I Can move variable from JavaScript into a php Query?

Here is my Code I want to move my Variable of "Hellow"
from JavaScript
to PHP Query at:
document.write("<?php $result = mysql_query("SELECT Urdu FROM translate where English= 'Variable'"); ?>");.
Kindly any help?
<script type='text/javascript'>
var Variable = "Hellow";
document.write("<?php
$db = mysql_connect("localhost","root","");
mysql_select_db("Dictionary",$db);
?>");
document.write("<?php $result = mysql_query("SELECT Urdu FROM translate where English= 'Variable'"); ?>");
document.write("<?php
while($row = mysql_fetch_array($result))
{
echo $row['Urdu'] ;
}
mysql_close($db);
?>");
</script>
You can't/should not do what you propose. JS is executed client side, while PHP is a server side language, and even if it is possible to send a file to the server and execute it, it would come with a host of security issues.
What you could do however is to make a get/ajax request that sends your variable to a php script, but remember to clean up the variable before using it in any mysql query.
What you are trying to do won't work because the PHP processing happens earlier in the stack than the Javascript. You will need to use ajax to send data back to the server once the page has loaded.
jQuery can make this pretty easy for you. Look up $.ajax methods for jquery.

PHP json_encode then getJSON issue in javascript

Sorry if this is still another thread on the subject but I am struggling since hours but could not find the solution.
I am trying to get data from a Mysql database, create a JSON with php, then parse this JSON in javascript.
Here is my json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
Then I try to parse it into java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
when I replace localhost/json.php by the result in a file data.json, it works, when I open localhost/json.php with firefox, I can see the JSON table...so I do not know why it does not work with localhost/json.php.
Is my php code or javascript code wrong ?
Thanks in advance for your help !
Try this method
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})
Try This in php
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);
I think your web application server (like Apache or nginx) sends Content-Type: text/html by default or something of that sort for your json.php file. On the other hand, it looks like $.getJSON method requires a application/json content type field.
Try adding:
header("Content-Type: application/json");
to the top of the json.php file.
Edit - additional info:
I couldn't find in the original documentation of the $.getJSON method whether it, in fact, requires the specific Content-Type so I looked into the source code:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
Here is the line of source code for jQuery 1.7.1 (which is the version you said that you use, I hope) for getJSON and as you can see, it calls jQuery.get with the last argument set to "json".
In turn, the jQuery.get documentation reveals that this argument means:
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
from: http://api.jquery.com/jQuery.get/
Thus, when you call $.getJSON("/url/to/file", ...) that first argument is expected to be a JSON. If you add the PHP code from the top of my answer, your web application server will mask the output of the php file as a JSON.

$jquery.post() PHP and Mysql

So I half got jQuery's ajax ($.post) to work. But, for some reason, I haven't been successful with finding the right online article to explain to me how PHP retrieves the ajax data that is sent. I've found some stuff on json_decode, but upon me doing that to basically decode it, it wont work (and yes, I am using json for the $.post command).
Here is my javascript code
$.post("notificationNum.php", {"user":"1"},
function(data){
$(".example-number").html(data.amount);
}, "json");
Here is my PHP code
<?php
session_start();
//link to db info here
$user_id_got = json_decode($_REQUEST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>
Mind you all, I've also tried using the $_POST command instead of the $_REQUEST. Any ideas how to send data to the PHP file so I can use it?
"json" in your jQuery call is how your php should write its output, not how jQuery sends it. Use normal $_REQUEST in your php:
$user_id_got = $_REQUEST['user'];
try this
notificationNum.php
<?php
//link to db info here
$user_id_got = intval($_POST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>

Categories