Sql queries doesnt work when inside a php function - javascript

So the main problem is, when i make some query just after a post[] or whatever and its just in the main code of the php (not in a function) it works perfectly fine..
But, when i try and have that query inside a php function,it never works, and kinda hiding any other code on the rest of the page... I have a few divs after that php and sql query code, and they just dont show when i try to query through the function..
<script type="text/javascript">
function callPhpVoteAdd(name) {
var result = <?php voteAdd(name); ?>;
alert(result);
return false;
}
</script>
<?php
echo '</br>';
$allsql = "SELECT * FROM voting ORDER BY votes DESC";
$result = mysqli_query($conn, $allsql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$votes = $row["votes"];
echo '<form method="post">
name: "' .$name. '" - votes: "' .$votes. '" <input type="submit" name="'.$name.'" value="'.$name.'" onclick="callPhpVoteAdd(this.name)"/><br>
</form>';
}
}
function voteAdd($name) {
if($conn->query("UPDATE voting SET votes = votes + 1 WHERE name = '".$name."' ") === TRUE) {
echo "<script>alert('fuck yeah');</script>";
}
echo "shit";
}
So the button pressed calls the js function, which calls the php function

I guess you're misunderstanding the way JS and PHP works. PHP works server side, and JS, in your case, client side. And so, PHP generate the script/page before it's sent to the browser, so when JS runs it, all the <?php ?> are already replaced by static data.
So, to put it shortly and simply, you just can't call a PHP function from JS after your page is loaded, the way you tried to (because the call isn't there anymore - check your source code from your browser).
You need either to :
use a form with an "action" attribute ; this will send the data to server, and call the php script set in "action", where you can handle the sent data, and then reload the page with the new/updated data,
use ajax (almost the same thing : this sends data to server and call a php script to handle them, but instead of reloading the page, the output of the PHP script - with the data you need - will be sent back to JS, to a callback function, where you'll be able to use them to modify the page).

Related

How to refresh page and send variable

i have a php page where i press a button to edit on another page the mysql db records:
page name 'distintaBase.php'
here there is a list of names that are products name. Each product cointains a list of components.
When i press the edit button for one product i'm redirect to the new page 'modifDistBase.php'.
the $dist_base variable is passed to the new page. I use it on the page title
<h2>Modifica distinta base <?php echo $_GET['dist_base']; ?></h2>
and then to load the mysql db
<?php
$dist_base = $_GET['dist_base'];
$sql = "SELECT $dist_base.Id, $dist_base.Designator, $dist_base.Quantity, $dist_base.Description, $dist_base.Package,
$dist_base.Manufacturer, $dist_base.Pn_Manufacturer, $dist_base.Pn_Utterson, $dist_base.Mounted
FROM $dist_base";
?>
pressing ADD button i add a new component
if(isset($_POST['add_item'])){
$designator = $_POST['designator'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$package = $_POST['package'];
$manufacturer = $_POST['manufacturer'];
$pn_manufacturer = $_POST['pn_manufacturer'];
$pn_utterson = $_POST['pn_utterson'];
$mounted = $_POST['mounted'];
$sql = "INSERT INTO $dist_base (designator,quantity,description,package,manufacturer,pn_manufacturer,pn_utterson,mounted)
VALUES ('$designator','$quantity','$description','$package','$manufacturer','$pn_manufacturer','$pn_utterson','$mounted')";
if ($conn->query($sql) === TRUE) {
echo '<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>';
} else {
echo "Errore: " . $sql . "<br>" . $conn->error;
}
}
there is something wrong probably on the javascript.
echo '<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>';
the new component is added to the database (for example with #5 id) but do not appear on the page modifDistBase.php
if i press refresh on the browser or f5 now i can see the new component (#5 id) but on the database a new one is added #6 with the same items as #5
PS
- header is already sent by menĂ¹ page
- have tried window.location.href with same result
Why don't you try with:
header('Location: modifDistBase.php?dist_base='.$dist_base);
instead of echo javascript you can redirect immediatelly to the page + the variable
there are some thing to fix on your code
Note the javascript you output with
echo '<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>';
will be precisely
<script>window.location.replace("modifDistBase.php?dist_base=" + $dist_base.value)</script>
Without checking the correctness of the js related to your goal, it's immediate to see you should write instead
echo '<script>window.location.replace("modifDistBase.php?dist_base="' . $dist_base . '")</script>';
to inject the php value into the javascript string.
(you've also forgot a double quote b.t.w)
If you have doubts regarding your javascript, you can inspect the page on the browser and look at it (right click and "inspect element" or "analyse element").
Mind it is not recommended that you take the user input and use it as it is in an SQL instruction. You should do some sanification and use a prepared statement or escape the values before putting them in the sql.
That said, the javascript redirection you do looks a bit odd, maybe you can redirect from the php script without asking the client to do so. Look at the header php function for instruction about redirection done server side.

How to access jQuery or javascript variable inside PHP script in the same file?

My javascript file is as follows. I want to use the value variable(stores the page number(pagination)) in my php script to do database related operations.
<script>
var selector = '.links';
$(selector).on('click', function(){
$(selector).removeClass('active');
$(this).addClass('active');
var value = $(this).text();
window.location.href="index.php?value";
});
</script>
My PHP script is
<?php
$link = mysqli_connect("localhost","root","","admin");
if(mysqli_connect_error()) {
die("There was an error connecting to the database");
}
$var = $_GET['value'];
$query = 'SELECT article_id, publisher, heading, date, views FROM admin LIMIT '.$var;
$result=mysqli_query($link,$query);
if ( false==$result ) {
printf("error: %s\n", mysqli_error($link));
}
echo '<div class="table-full" id="table1"><div class="table-responsive"><table class="table" data-sort="table">';
echo '<thead><tr><th>ARTICLE</th><th>PUBLISHER</th><th>HEADING</th><th>DATE</th><th>VIEWS</th></tr></thead><tbody>';
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo '<tr><td>' ."{$row[0]} "."</td>
<td>" . " {$row[1]} </td> ".
"<td>" . " {$row[2]} </td> ".
'<td style="min-width:88px">' . " {$row[3]} </td> ".
"<td>" . " {$row[4]} </td></tr> ";
}
echo "</tbody></table></div></div>";
mysqli_close($link);
?>
I am not very much comfortable with PHP but have a basic understanding
Thanks a lot!!! in advance to all those who tried to help me
PHP is a server side scripting language(runes on server) whereas javascript is a client side scripting language (runs on browser) so you can not simply use variable/value from one to another ,but there are means to do so.
So in order to send value to variable value to server you need to make a request to server ,you can either make a form submission request by putting the value of value in a hidden field of your form so it goes to server when user submits the form or you can make an AJAX request .
Putting value in form
<input type="hidden" name="pagination_page" value="" id="pagination_page_value">
and then set the value of this field using jquery.
$("#").val(value);
AJAX Approach:
$.get("savePaginationValue.php",{pagination_page_value:value}).done(function(data){
//Success do whatever you want.
}).fail(function(){
//Something bad happened.
});
and in savePaginationValue.php access this value easily using $_GET["pagination_page_value"]
you can use either GET or POST depending on your requirement .
hope it helps
You cannot use javascript variable in php. However you can use php variable within javascript. Javascript is client side and php is server side, if you want to use then send with ajax because its like sending from client to server.
Besides the proposal using Ajax you can also simply build a hidden formular(style="display:none") containing the variables you change by JavaScript and call a form submit from JavaScript to submit it to the server.
I think it's $(formName).submit();
Or if you don't have problem with showing what you send you can use GET like submission e.g. by saying location.href="some.page.php?variablenName=someValue"

How to pass javaScript values to PHP

How to pass javaScript values to PHP, my code is following
<script>
function a{
var b = a;
}
</script>
<button onclick="a(2)">Values</button>
<?php
$select = mysql_query("select * from tabl1 where id='values'"); // values comes here
echo $select;
?>
There's a lot of thing you could do.
Principal things you have to know is that javaScript run on the client side (browser), while PHP is running on the server.
Then If you want to pass a variable from your JS to your PHP you have to make a server call.
There's various way you can use in order to send variable from client to server.
As I understand from your example, it looks like your php code and your javascript on the same file. so maybe call your file another time will be enough for you.
Let's say your file's name is index.php.
<script>
function yourJavascriptFunction(id) {
window.location.href = "index.php?id=" + id;
}
</script>
Then in change your PHP code to this:
<?php
$select = mysql_query("select * from tabl1 where id='".$_GET['id']."'"); // values comes here
echo $select;
?>
$_GET will get the variable you've sent in your Js function.
Doing like this will refresh the page.
May be you don't want to refresh the page? Then look at the ajax way.
I hope it helps you

How to transfer a value on DB to JAVASCRIPT through PHP

<?php
// Connect to database server
mysql_connect("192.168.1.101/phpmyadmin/", "root", "praticas") or die (mysql_error ());
// Select database
mysql_select_db("logs_history") or die(mysql_error());
//---> at this point, I want yo pull a VALUE from a column called potencia_ativa and insert in
// the code JS below
mysql_query($strSQL);
// Close the database connection
mysql_close();
?>
//JS code-------------------------------------------------------------------------------------------
<div id="graphHolder" style="height:75%;width:100%"></div>
<script type="text/javascript">
setInterval(
function() {
var d1 = [];
for (var i = 0; i < parseInt(document.getElementById('number').value,10); i += 0.5) {
d1.push([ //----------> pull the value from the php/DB as a FLOAT
]);
}
$.plot("#graphHolder", [{
label: "Label",
data: d1,
lines: { show: true, fill: true }
}
]);
}, 1000);
</script>
Remember, PHP executes on the server and GENERATES the page that runs the Javascript on the client. Putting a value from PHP into the JS code is as simple as:
<script>
var foo = <?php echo json_encode('bar'); ?>;
</script>
If you need to send the PHP data over AFTER the page was generated and already send to the client, then you need to have the client execute an AJAX request to fetch that data from the server. Once PHP has shoved the page out the door, it's basically done and can't "reach out" to the client to do updates on its own.
Also: Note the use of json_encode(). You should NEVER dump output from PHP directly into a Javascript context without it. Anything else puts you at risk of generating JS syntax errors, which will kill the entire JS code block.
Why are you using Interval? Are you trying to update the displaying page data/value automatically after some time passed? That won't work, because if anything changes in database, It won't change in the displaying page, unless you use AJAX to call your php script and return some values, and then, change in the displaying page.
To get a value from PHP script to JAVASCRIPT, you just need to use the php clausule;
var test = <?php echo $variable; ?>
// echo for strings, ints, floats.
// print_r for arrays.
Of course, if your PHP script already injected the data into the page/the data is in the same page you're using JAVASCRIPT, assuming that you have already fetched the data, handled it and etc.

PHP inside Javascript in a registration form (for validation)

I'm developing a registration form for my site. Actually when a visitor choose an username, a php query to my MySQL DB is used to control if it's already used and if so, a javascript windowd appear.
Can i use a PHP query inside Javascript for displaing a real-time notice near the form (using HTML5)?
<script>
var username = document.getElementById('username');
var userdb = <? php control_username($username); ?>
var checkUsername = function () {
if (userdb.value == true) {
username.setCustomValidity('Username already used');
} else {
username.setCustomValidity('');
}
};
username.addEventListener('change', checkUsername, false);
</script>
and here there's the php function:
<?php function control_username($username){
$db=connessione_db();
$query = "SELECT username FROM utente WHERE username = '$username';";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[0]==$username){
return TRUE;
}
else{
return FALSE;
}
$query=NULL;
}
how can i do?
You can use AJAX or jQuery AJAX to send a request to a php page, Check if the username exists, return the result, and display it using Javascript again.
Here is the jQuery sample:
<script>
$.ajax({
type: 'POST',
url : 'checkUsername.php',
data: {'username' : $('#username').html()},
cache : false,
success: function(data){
if(data == 'exists')
//username exists
alert('username already exists!');
},
error: function(request , status , error){
alert(request.resposeText);
}
});
</script>
and this should be your checkUsername.php file:
<?php
$db=connessione_db();
$query = "SELECT count(*) as count FROM utente WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[count] > 0)
echo 'exists';
else
echo '';
PHP is run on the server, Javascript is run on the client's machine. Once your PHP script has generated a page and sent it to the user, it doesn't run any longer. Your client has no knowledge of a PHP script. It can't directly run, call, or read anything about your PHP script because it resides solely on the server (never on the client's machine). Your client's machine does, however, know about your Javscript since it has been sent along with the page. If you want to access PHP functionality from your page, you can either send a GET/POST call to the server and reload the page, or use AJAX to make the call in the background. Check out Jquery's implementation of AJAX calls, it makes using it pretty simple.
No you can't do it like that. PHP is serverside, Javascript clientside. The moment Javascript is executed is the code working clientside. All PHP code is fixed.
Compare it to the combination of HTML and PHP in an HTML page. It is fixed there as well. Same applies to PHP in Javascript.
Here are some answers from related questions on stackoverflow:
How to put php inside javascript?
How to embed php in javascript?
Here is an example from ajaxref, showing the basics:
http://ajaxref.com/ch3/asyncsend.html
This is another tutorial showing how an ajax call is handled:
http://code.tutsplus.com/articles/how-to-make-ajax-requests-with-raw-javascript--net-4855
I advice you to first understand this process and later on start using a framework like jQuery.

Categories

Resources