Pass div id into PHP variable - javascript

I have passed a javascript variable into a div id element in HTML. I am now trying to send that div id to a php variable so I can access it.
However, when I try a POST request it is not grabbing what is assigned to div id. Any help is appreciated, thanks.
<?php
session_start();
$un = $_POST["result"];
echo "the username is". $un;
?>
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
if (typeof(Storage) !== "undefined")
{
var getUser = document.getElementById("result").innerHTML = sessionStorage.getItem("username");
}
else
{
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>

First of all, to make a post request you'll need to be using XMLHttpRequest. You really should be using a GET request in a separate file, though.
PHP file, named getId.php:
<?php
session_start();
$_SESSION["id"] = $_GET["id"];
?>
JavaScript code, to retrieve data:
var getData = function( url, callback ) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
callback(xhr);
};
xhr.open( "get", url, true );
xhr.send();
};
getData('./getId.php?id=' + /* id goes here */, function(json){
if(json.status == 200){
data = json.response;
//Do something with data...
}
})
And finally, to reference the session data, back in the HTML file:
<?php
session_start();
echo "value of username is: " . $_SESSION["id"];
?>

Related

php file's code not executing through ajax call

I have a button in my PHP file, and when I click on that button, I want another PHP file to run and save some data in a MySQL table. For that I am using AJAX call as suggested at this link (How to call a PHP function on the click of a button) which is an answer from StackOverflow itself.
Here is my show_schedule file from which I am trying to execute code of another PHP file:
$('.edit').click(function() {
var place_type = $(this).attr("id");
console.log(place_type);
$.ajax({
type: "POST",
url: "foursquare_api_call.php",
data: { place_type: place_type }
}).done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
});
});
here 'edit' is the class of the button and that button's id is being printed in the console correctly.
here is my foursquare_api_call.php file (which should be run when the button is clicked):
<?php
session_start();
include('connection.php');
if(isset($_POST['place_type'])){
$city = $_SESSION['city'];
$s_id = $_SESSION['sid'];
$query = $_POST['place_type'];
echo "<script>console.log('inside if, before url')</script>";
$url = "https://api.foursquare.com/v2/venues/search?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&v=20180323&limit=10&near=$city&query=$query";
$json = file_get_contents($url);
echo "<script>console.log('inside if, after url')</script>";
$obj = json_decode($json,true);
for($i=0;$i<sizeof($obj['response']['venues']);$i++){
$name = $obj['response']['venues'][$i]['name'];
$latitude = $obj['response']['venues'][$i]['location']['lat'];
$longitude = $obj['response']['venues'][$i]['location']['lng'];
$address = $obj['response']['venues'][$i]['location']['address'];
if(isset($address)){
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude, address) VALUES ($name, $latitude, $longitude, $address)");
$result = $statement->execute();
}
else{
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude) VALUES ($name, $latitude, $longitude)");
$result = $statement->execute();
}
}
}
?>
none of the console.log is logged in the console and also the 'temp' table is not updated. Can anyone tell me where I am making mistake? Or is it even possible to execute the code of a PHP file like this?
Your JavaScript is making an HTTP request to the URL that executes you PHP program.
When it gets a response, you do this:
.done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
}
So you:
Alert something
Show a model
At no point do you do anything with data, which is where the response has been put.
Just sending some HTML containing a script element to the browser doesn't cause it to turn that HTML into a DOM and execute all the script elements.
You'd need to do that explicitly.
That said, sending chunks of HTML with embedded JS back through Ajax is messy at best.
This is why most web services return data formatted as JSON and leave it up to the client-side JS to process that data.
to return the contents of php code you can do something like this
you can use any call to this function
function check_foursquare_api_call(place_type) {
var place_type= encodeURIComponent(place_type);
var xhttp;
//last moment to check if the value exists and is of the correct type
if (place_type== "") {
document.getElementById("example_box").innerHTML = "missing or wrong place_type";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("example_box").innerHTML = xhttp.responseText;
$('#userModal_2').modal('show');
}
};
xhttp.open("GET", "foursquare_api_call.php?place_type="+place_type, true);
xhttp.send();
}
this will allow you to send and execute the code of the foursquare_api_call file and return any elements to example_box, you can return the entire modal if you want,
you can use any POST / GET method, monitor the progress, see more here
XMLHttpRequest

Get data php with ajax without display it

Is it possible to get data php with Ajax without display them ? Simply stock data in JS variable?
I need this data to manipulate dates but no show it.
When I tried to simply return data without echo, etc. Data ajax in JS is empty
Ps : sorry my English is bad
try it this way
File *.php
<?php
$var_1 = null;
$var_2 = null;
/** ... */
$response = new stdClass;
$response->var_1 = $var_1;
$response->var_2 = $var_2;
echo json_encode($response);
?>
File *.html or *.js
<script>
var state = {};
$.ajax({
url: 'getData.php',
type: 'post',
dataType: 'json',
success: function (response) {
console.warn(response);
state = response;
}
});
</script>
Assuming you are trying to pass data from a PHP file to HTML/JS where it happens that your PHP file is also included in the HTML that's why it's displaying the echo (if I understood correctly!)
Using AJAX PHP example from w3school.
HTML sample file:
<?php include "PHP_SAMPLE_FILE.php" ?>
<header>
<meta name="temp_files" content="<?= htmlspecialchars($jsonData) ?>">
<!-- The rest of HTML content -->
JS sample file:
if (str.length == 0) {
// do something if there was nothing entered
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText.includes('{')){
result = JSON.parse(this.responseText);
// do something if response is JSON
} else {
// do something if response is null
}
}
}
xmlhttp.open("GET", "PHP_SAMPLE_FILE.php?q="+str, true);
xmlhttp.send();
}
PHP sample file:
$q = $_REQUEST["q"] ?? $_POST["q"] ?? "";
$sql = "GET SOMETHING FROM DATABASE";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json[] = $row;
}
}
$jsonData = json_encode($json ?? null);
if($q != ""){
echo $jsonData;
}
What happens exactly is that once the page loads initially it won't display the output of the PHP query as we have surrounded the echo with an if statement that requires to have query value (q) to search and it shouldn't be empty (""). Of course, assuming that once the page is loaded the data is shared with the client-side through defined PHP variables using various approaches, using a meta tag in the header for instance.
Once the data is received from the PHP file through echo, we use the JSON.parse function to parse it as in this scenario JS receives it as a string.
Hope that helped :)!

Passing php variable to javascript in a different file

I'm having problems with passing php variables to javascript.
It does pass through the variable that is declared at the top, but I don't know how to call the function to get the new version of variable after the IF statement is done.
$info = "A message";
if (true){
$info = 'Message to be passed';
}
The script that is used to pass the php variable to javascript file:
<script type='text/javascript'>
var info = "<?php echo $info; ?>";
</script>
I was wondering what could I do to fix this problem?
The simple way (this requires both files to be PHP files):
<?php
require_once "your_php_file_here.php"; // Change to your PHP file here
?>
<script type='text/javascript'>
var info = "<?php echo $info; ?>";
alert(info);
</script>
This will only allow you to get the value on page load. You need to reload the page if you want it to get a new value.
The (in my opinion) better way (the file can be HTML) using Ajax:
<script type='text/javascript'>
var info;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'your_php_file_here.php'); // Change to your PHP file here
xhr.onload = function() {
if (xhr.status === 200) {
info = xhr.responseText;
alert(info);
} else {
alert('Request failed: ' + xhr.status);
}
};
xhr.send();
</script>
This can be put in a function and called as many times as you want. It can get the new value without the need to reload the page.
For this to work, you need to change your PHP code to:
$info = "A message";
if (true){
$info = 'Message to be passed';
}
echo $info;
I did not add support for IE6 and below because I think it's about time we stop supporting browsers that lost support by their developers many years ago.

Trying to update a database with javascript/PHP doesn't work

I'm trying to update a database using javascript and PHP, this is my index.html code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<input type="text" id="descriptioninput">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="addToDB()">Add to database</button>
<script>
function addToDB()
{
var descriptioninput = document.getElementById('descriptioninput').value;
var budgetin = document.getElementById('budgetin').value;
var budgetout = document.getElementById('budgetout').value;
$.ajax ( {
type: 'POST',
url: 'addtodb.php',
data:{descriptioninput:descriptioninput, budgetin:budgetin, budgetout:budgetout},
success:function (data) {
// Completed successfully
alert('success!');
}
});
</script>
</body>
</html>
Here's my addtodb.php code:
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "budgetdb";
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn === TRUE)
{
$descriptioninput = $_GET['descriptioninput'];
$budgetin = $_GET['budgetin'];
$budgetout = $_GET['budgetout'];
$query = "INSERT INTO budget (description, budgetin, budgetout) VALUES ('$descriptioninput', '$budgetin', '$budgetout')";
$conn->query($query);
$conn->close();
}
?>
But it appears as if my PHP script doesn't run. No changes appear in my database. I've tried to do warning() in the PHP file and alert it it using.done(function(text)), but nothing is displayed.
This is happening because you are doing the ajax request using POST method in js but you are trying to get the variables using the GET method in PHP. Switch it to GET and it will work.
Be aware of SQL Injection. You can prevent it either by using prepared statements or escaping the string as:
$descriptioninput = $conn->real_escape_string($_GET['descriptioninput']);
Also, the first if condition is not valid. You just need to do it like if ($conn) instead of if ($conn === TRUE)
I could be wrong but i believe description may be a reserved keyword in mySQL. try encapsing it
INSERT INTO budget (`description`, `budgetin`, `budgetout`) VALUES ('$descriptioninput', '$budgetin', '$budgetout')
Change ajax type to GET
$.ajax ( {
type: 'GET',
url: 'addtodb.php',
data:{descriptioninput:descriptioninput, budgetin:budgetin, budgetout:budgetout},
success:function (data) {
// Completed successfully
alert('success!');
}
});
its a little messy with your mix between ajax and JS. Try using this getHTTP function for regular JS.
function httpGet(theUrl){
//FETCH Data From Server
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", theUrl , false );
xmlhttp.send();
return xmlhttp.responseText;
}
then just build your url as +addtodb.php?param1="+param1value+"&param2="+param2value

Trouble with php variables and ajax javascript

ok I have edited this to another couple of questions I've asked on a similar issue, but I really am in a rush so thought I'd start a new one, sorry if it bothers anyone.
first I have a php script on test.php on the apache server
<?php
//create connection
$con = mysqli_connect("localhost", "user", "password", "dbname");
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Then I've got this ajax script set to fire onload of page a webpage written in html. so the load() function is onload of the page in the body tag. This script is in the head.
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
ok so what I want is the $n1 variable in the php script to be used in the javascript ajax code. Where the script is, but I'm not sure where or how to make use of the variable, I've tried a few things. All that happens right now is the innerHTML of itemNameLink1 just disappears.
I'm quite new so any advise would be appreciated, thanks.
The response (this is what you echo in php) returned from request you can get by responseText attribute of XMLHttpRequest object.
So first your JS code should be:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = xmlhttp.responseText;
}
}
}
now in php echo $n1 variable:
....
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
// echo it to be returned to the request
echo $n1;
Update to use JSON for multiple variables
so if we do this:
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$response = array
(
'name' => $name,
'color' => $color,
'price' => $price
);
echo json_encode($response);
Then in javascript we can parse it again to have data object containing 3 variables.
var data = JSON.parse(xmlhttp.responseText);
//for debugging you can log it to console to see the result
console.log(data);
document.getElementById("itemNameLink1").innerHTML = data.name; // or xmlhttp.responseText to see the response as text
Fetching all the rows:
$row = mysqli_fetch_array($grab); // this will fetch the data only once
you need to cycle through the result-set got from database: also better for performance to use assoc instead of array
$names = $color = $price = array();
while($row = mysqli_fetch_assoc($grab))
{
$names[] = $row['name'];
$color[] = $row['color'];
$price[] = $row['price'];
}
$response = array
(
'names' => $names,
'color' => $color,
'price' => $price
);
You can dynamically generate a javascript document with php that contains server side variables declared as javascript variables, and then link this in the head of your document, and then include this into your document head whenever server side variables are needed. This will also allow you to dynamically update the variable values upon page generation, so for example if you had a nonce or something that needs to change on each page load, the correct value can be passed upon each page load. to do this, you need to do a few things. First, create a php script and declare the correct headers for it to be interpreted as a script:
jsVars.php:
<?php
//declare javascript doc type
header("Content-type: text/javascript; charset=utf-8");
//tell the request not to cache this file so updated variables will not be incorrect if they change
header('Cache-Control: no-cache, no-store, must-revalidate'); // HTTP 1.1.
header('Pragma: no-cache'); // HTTP 1.0.
header('Expires: 0'); // Proxies.
//create the javascript object
?>
var account = {
email: <?= $n1; ?>,
//if you need other account information, you can also add those into the object here
username: <?= /*some username variable here for example */ ?>
}
You can repeat this for any other information you need to pass to javascript on page load, and then reference your data using the namespaced javascript object (using object namespacing will prevent collisions with other script variables that may not have been anticipated.) wherever it is needed as follows:
<script type="text/javascript>
//put this wherever you need to reference the email in your javascript, or reference it directly with account.email
var email = account.email;
</script>
You can also put a conditional statement into the head of your document so it will only load on pages where it is needed (or if any permission checks or other criteria pass as well). If you load this before your other scripting files, it will be available in all of them, provided you are using it in a higher scope than your request.
<head>
<?php
//set the $require_user_info to true before page render when you require this info in your javascript so it only loads on pages where it is needed.
if($require_user_info == TRUE): ?>
<script type="text/javascript" href="http://example.com/path-to-your-script/jsVars.php" />
<?php endif; ?>
<script type="text/javascript" href="your-other-script-files-that-normally-load" />
</head>
You can also do this for any other scripts that have to load under specific criteria from the server.
You should define the PHP variable. And use that variable in your javascript:
<?php
$n1 = "asd";
?>
<html>
<head></head>
<body>
<div id="itemNameLink1"></div>
<script>
function load()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/test.php', true);
xmlhttp.send(null);
//Note you used `onreadystatecahnge` instead of `onreadystatechange`
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("itemNameLink1").innerHTML = '<?=$n1?>';
}
}
}
load();
</script>
</body>
</html>

Categories