Recall a Mysql query from javascript [duplicate] - javascript

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I've been trying to find out the response for this because I think it's not difficult to do, but I cannot find it.
I basically want to "recall" a mysql query that works. I have an HTML button and a span so I call a function in javascript which has a php code with the Mysql query and the result that is store in my span, works fine, but... Why I cannot click the button again to get the update results from Mysql table if I changed it ?
The syntax is something like ( in a single php file for test):
<script type="text/javascript">
function test(){
<?php include 'dbconnect.php';
$query = 'SELECT * FROM data';
$results = mysql_query($query);
while ($row = mysql_fetch_assoc($results)) {
$data = $data . "row[name]<br>";
}
mysql_close();
?>
testspan.innerHTML = <?php echo $data ?>';
}
</script>
<HTML><BODY>
<input type='button' onclick='test();'/><br>
<span id="testspan"></span
</BODY></HTML>
Resuming: when I click the first time the data appears but not the second time onwards so the Mysql query can be call just first time? anything related with the variables ?

Php is ServerSide... JS is ClientSide... you can't do code php in code JS you must use AJAX :https://api.jquery.com/jQuery.ajax/

Related

How to pass a php variable from a php file to js file? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have an html/php composite document that uses the login variable from a user. (This came from a separate php file on signin):
<html> Welcome <?php echo $login; ?> </html>
//Now when the user uses the chatbox, and clicks send, I would like to pass the data (inclusive of the username) from this html file to the .js so it can in turn pass onto another php file. (ps I tried the following but to no avail, as the .js file is external to the html/php composite):
$("#newMsgSend").click(function()//triggers script to send the message
{
$("#newMsgCnt").val(''); // clears the box when the user sends a message
var username = "<?php echo $login; ?>";
alert(username);
});
Your current code is likely introducing an XSS vulnerability. Instead, take advantage of the fact that valid JSON is valid JavaScript:
var username = <?php echo json_encode($login); ?>;
In some situations, it may also be better to use an XMLHttpRequest or WebSocket that requests the data from another URL (typically encoded as plain text, XML or JSON). One scenario for that would be notifying the user once new items have been added after the user loaded the webpage.
when the user logs in, create a session for that user and populate it with the data (such as username, email, phone number or whatever) from the database - as followings (assuming that the login is correct and authentic:
$_SESSION['user'] = $row; //where $row is the row of data returned from the db
Then whenever you want to access that information include the following at the top of the page:
session_start();
and then access the information such as
$userfirst_name=$_SESSION['user']['first_name'];
then your html will be something like:
<h1> Welcome <?php echo "$userfirst_name"; ?> </h1>
note that session start must be at the top of each page you are wanting to access the sessiobn variables. Then to clear the user details (such as when the user logs out you can use the following:
unset($_SESSION["user"]);
Thanks to both: Ivan Rodriguez Torres and phihag. I got a solution somewhere in the middle of both posts:
<input id="login" readonly type="text" <?PHP echo "value= '$login'/>"; ?>
Ivan's suggestion was somehow returning an "undefined" variable for me. The above works like a charm though. Hope its safe and doesnt lead to any problems.
Thanks again guys

send a varible through load functon [duplicate]

This question already has answers here:
Best way to pass parameters to jQuery's .load()
(2 answers)
Closed 10 months ago.
i would like to send a variable on the next page this is what i have at the moment
<? php
//some code
$ID = $_GET['ID'];
echo "<div id='show_here'></div>";
<script type ="text/javascript">
$(document).ready(function(){
setInterval(function(){
$('#show_here').load('fetch.php')
}, 3000);
});
</script>
so i would like to send the variable $ID in to the next page i assume it will be something like this .load(fetch.php?=id=$id') but it doesn't work can some one please help me out here
i think the first think is to define the variable id in the jQuery part but i do not know how to go about it please help
If I were you, I'd clean that code up properly before anything else.
<? php
//some code
$ID = $_GET['ID'];
?>
<div id='show_here'></div>
<script type ="text/javascript">
$(document).ready(function(){
setInterval(function(){
$('#show_here').load('fetch.php?id=<?php echo $ID; ?>') // we put the ID here
}, 3000);
});
</script>
In your fetch.php file, you'll need to access the $ID via $_GET again.
I'm sticking within the scope of your question here, but something to note is that you best sanitize that information. Especially if you're going to use it in a database query!
you can use
.load('fetch.php?id=<?php echo $id ?>');
or
.load('fetch.php' , {id : '<?php echo $id ?>'}) ;

Unexpected response while using php [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I'm developing irctc similar website similar project as college assignment. I'm providing user to search any train running on given date and validating from database. I'm using php and mysql and getting no error as well as invalid response from code. Please look at the code:
if (isset($_POST['btn_no'])) {
$current_date=date("Y-m-d");
$selected_date=$_POST['date'];
$no=$_POST['train_no'];
if ($selected_date>=$current_date) {
$query="SELECT train_no FROM `trains` WHERE train_no='$no'";
$found=$db->query($query);
$rows=$found->num_rows;
if ($rows==1) {
$_SESSION['train_id']=$no;
$_SESSION['date']=$_POST['date'];
header("Location: showtrain.php");
}
elseif ($rows==0) {
?>
<script>alert("Train no. invalid !")</script>
<?php
}
}
elseif ($selected_date<$current_date) {
?>
<script>alert("Wrong date");</script>
<?php
}
}
Every time <script> is executed.
From what I can tell you have an error in you query
$query="SELECT train_no FROM `trains` WHERE train_no='$no'";
WHERE train_no='$no'" will be looking for the string '$no' instead of the variable $no.
Consider trying something like to make use of the value of the variable instead of having MYSQL interprate $no as a string.
$query="SELECT train_no FROM `trains` WHERE train_no=$no";
or
$query="SELECT train_no FROM `trains` WHERE train_no=" . $no;

Check variable in javascript with php variable [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have the php page with javascript code inside it.
If I have php variable retrieved by back-end server, can it be passed in javascript code?
For instance, if I want to check the flag(php variable) inside the javascript code, do I need to hardcode it inside the javascript?
Below are the "checkServiceCategory"? (Should it be Dynamic or static)
<?php
foreach ($result as $id=>$value) {
if($value[0]->isServiceCategory)
return true;
}
OR
isEmptyUploadFile(function(r)
{
var checkServiceCategory=document.getElementById('category-group').value;
if(checkServiceCategory!=85 && (fileList == null || fileList.length == 0))
{
$("#uploadImgError").html('<em><span style="color:red"> <i class="icon-cancel-1 fa"></i> Please Upload at least one image!</span></em>');
location.href = "#uploadImgError";
return false;
}
else
Yes you can use php variables inside the javascript code and php variable is dynamic as
<?php $your_variable = "some value"; ?>
<script>
var js_variable = '<?php echo $your_variable; ?>';
alert(js_variable);
</script>
You can write PHP data into JavaScript before that JavaScript is loaded. So, for example:
<script>
var count = 0;
<?php
echo 'count = 5;';
?>
console.log(count); // Will give 5
</script>
You can do this because the PHP is run on the page before it is ever sent to the client. However, once the code is sent to the client, JavaScript and PHP cannot talk to each other. What you can do at that point is make AJAX requests via JavaScript from your client back to your server, and use PHP to respond to the AJAX request.
You can pass value from php to js like this.
var js_var = '<?php echo $some_php_variable; ?>';

passing variable from javascript to a php within same function [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am facing issue regarding passing javascript variables to php within same function. My code looks like this
else if(msg_type[i] == 'code' ){
var code_action = 'test';
<?php
function foobar_func(){
return "<script>document.writeln(action[i]);</script>";
}
add_shortcode( 'foobar', 'foobar_func' );
?>
}
what i am doing is passing that code_action variable of javascript and returning it to function without using ajax or jquery...is there any possible method to do so...??
any possibilities will be appreciated. Thank you
When you make a request to invoke this page, your <?PHP ?> block is executed in the server. It creates a processed output in the web page (in your code) and send it to the browser. Now the browser executes your <script> </script> blocks.
I hope you understand that passing variables from <script></script> to <?PHP ?> is impossible since the latter happened in the past.
But you can use it other way around by trying to pass variables from the PHP to JS.
When you write
<?PHP
$fromServer = "from php";
echo "<script> var fromServer = " . $fromServer . " </script>
?>
.. it passes data from your PHP to JS.
You can, however, use HTTP POST or GET method to pass data from JS to PHP to be used in the next session.

Categories