Passing PHP into jQuery [duplicate] - javascript

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 idea how to pass PHP value into a jQuery variable, I have done it in the past and it worked. But I tried the below code but for some reason it not working. I dont know where the problem lies.
I am trying to hide a custom virtuemart drop down cart I designed when the cart is empty.
jQuery(document).ready(function ($) {
var cart = "<?php if ($data->totalProduct) echo $data->cart_show; ?>"
jQuery('.btn-cart1').hover(if (cart === "") {
jQuery(this).find('.dropdown').hide();
}
else {
jQuery(this).find('.dropdown').hide();
jQuery('.btn-cart1').hover(
function() { jQuery(this).find('.dropdown').stop().show(500)},
function() { jQuery(this).find('.dropdown').stop().hide(500)})
}
});

PHP is server side scripting language and is executed well before your javascript executes on web browser.
The correct execution of your code depends on the values of $data->totalProduct & $data->cart_show after the PHP has been executed on your server side and the values are places in your javascript.
It is not a good programming practice and I would strongly suggest you to use AJAX instead to access the values of PHP variables.

Related

How to use a variable from page you loaded? [duplicate]

This question already has an answer here:
Extract Javascript variables of a page via PHP
(1 answer)
Closed 6 years ago.
Hello!
I want to use a variable on my website from a page I loaded using get:
$.get("fetchData.php", function( data ) {
//I want to use the variable `classes`
}, 'html');
The page I am loading has the following variable:
This can't just be copied since it changes every few weeks.
My question is how do I use that variable on my index.php?
So:
I am on index.php I load fetchData.php and I want to use the classes variable from the loaded page. How do I do that?
The easiest way is to use eval
$.get("fetchData.php", function( data ) {
eval(data);
console.log(classes);
}, 'html');

Deleting a row within SQL database webpage [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
My aim is for a user to click a button within a row to delete that row within the database.
The button is declared as so:
<td><button class="btn btn-default" onclick="removeStudent()" button id= <?php echo $productDetails["studentID"]; ?> type="button">Delete</button></td>
The remove function is as follows:
<script>
function removeStudent() {
$id = window.event.target.id.toString();
$sql = "DELETE FROM tableStudent WHERE studentID= '$id'" ;
if (mysqli_query($connection, $sql)) {
echo "Record deleted";
} else {
echo "Error deleting";
}
}
</script>
The webpage is connected to the database, and variable names are correct and working within other functions. Just delete function not working. Any help would be much appreciated.
It looks like you are mixing javascript and PHP here. I'm not sure you understand how PHP works. Any PHP code on your page is run before the page is ever sent to the user, so you can't put PHP stuff inside javascript function (well you can, but it will be run and turned into plaintext before the javascript is ever even read by the user's browser.) So your line where you go $id = window.event.target.id.toString(); won't work, since you are trying to set a PHP variable using javascript. Actually none of that code will do anything, since its not inside a <?php block. It will just cause errors in the browser console because it is invalid javascript code.
You need to make your javascript function make an ajax call to another PHP page, which actually does the delete

Run PHP function with JavaScript [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
I was going to run krimaction1, a PH function when the JavaScript runs, but I've not had any luck solving this and I'm not really good at JS. How can I run that PHP function in the JavaScript?
Here is the code I've tried so far
<?php
function krimaction1() {
echo"IT IS ALIVE!";
}
?>
<script>
$(function(){
$('#krim_1').click(function(){
alert(this.id);
var myTD = this.id.split('_')[1];
var newFrm = '<form id="myNewForm1"><input name="newdata" value="' +myTD+ '" /></form>';
$('body').append(newFrm);
$('#myNewForm').submit();
});
});
</script>
I've tried another method with this as my JS:
function myFunction() {
document.getElementById("ThisIsTheValue").value = "Johnny Bravo";
document.getElementById("SubmitForm").click();
}
but that code doesn't work either for me, as when I try to set the value with the JS and click it it doesn't do anything and I can't really see what's wrong.
It seems the action of myNewForm is the php page itself, so you can add
<?PHP
function krimaction1() {
echo "IT IS ALIVE!";
}
if (isset($_GET["newdata"])) { krimaction1(); }
?>
to the page to have it execute when the form is submitted
I use $_GET here since that is the default for the form you have created.
If you do NOT want to reload the page to see IT IS ALIVE, you need to AJAX the result

How to receive data in php sent from javascript [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I am sending some data from my pain page to app.php using javascript
$(document).on('click', '.app' , function(){
var data=$(this).attr("id");
window.location="application/app.php?data="+data; //data send in this statement
});
my php code is this :
<?php
if($_GET['data'])
{
echo $app_id=$_GET["data"]; receiving data
}
?>
It works sometime but now it is giving Notice in an alert box: Undefined index data in app.php. But it is showing the echo.
I want to know how I can receive the data I need using $_POST or $_GET. like we receive by making an Ajax call. But I haven't specified something like this in Javascript. is there any way to this?
I want to clarify that the data exists and it is non empty because echo is successfully printing that on the page
Try this:
<?php
if(!empty($_GET['data']))
{
$app_id = $_GET['data']; // receiving data
}
?>
Please be aware that passing data without validation is not secure. Reccomended reading: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
use isset() to first check if the key exists. data won't exist in $_GET when it's not passed via a parameter in the url
you probably want some logic that looks like this:
if (isset($_GET['data'])) {
if (!empty($_GET['data'])) {
$appId = $_GET['data'];
}
else {
// data exists, but it's empty
}
}
else {
// data does not exist
}
and maybe you even want to check if it's a valid id, like being numeric or something

How to call php codes inside javascript [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I want to check the inputs of a form if they are empty and then i want to use php codes for user registeration.
<script>
$('#submitbutton').click(function(){
if($('#usernameinput').val() == ''){
alert('Input is blank');
}
else {
//here i want to use php codes for example;
$bgl = new mysqli("localhost", "root", "", "users");
if ($bgl->connect_errno) {
echo "Failed to connect to MySQL: (" . $bgl->connect_errno . ") " . $bgl->connect_error;
}
$username = mysql_real_escape_string($_POST['username']);
.....
.....
..... /and so on..
}
});
</script>
In this case you most likely want to use $.ajax() to call a PHP page that supplies this information.
jQuery.ajax()
There is no such thing as php and javascript working together like that. Javascript in run on client side and php is run on server side. The best you can to is to pass and retrieve values to and from a php page and then use those values as intended.
You have a few options here. The first is to post the form to a PHP page after the JavaScript validations (just use the form action) or use Ajax and call the PHP page, as Robin says.
That's not posible, you can embed javascript into php code but not vice versa.
The best way to implement that is developing a REST service and retrieving data with AJAX.

Categories

Resources