jQuery XMLHttpRequest calling External PHP form not submiting - javascript

I recently had a friend who specializes in ladder logic and not web programming, come to me requesting help with a project from her employer. While I use more traditional coding languages, I am far from an expert in jquery and php myself. The problem that we are having is that a php page with a jquery / html form inserted into a parent page via XMLHttpRequest, is not executing its "post" action from the parent page. The thing that makes this problem more difficult is that when page is run by itself outside of the parent page (loaded directly into the browser), it executes its "post" action fine. I have done many hours of searching and trial and error at this point but am stumped and now come to you for help. Below are the relevant bits of code. Any help you could provide would be greatly appreciated as nothing we've tried seems to work when it comes to executing the submit of the form when it is inserted via XMLHttpRequest.
Javascript Code From Parent Page inserting external form:
function showUser(str)
{
if (str=="")
{
document.getElementById("insertUserHere").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp.status==200)
{
document.getElementById("insertUserHere").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","ajax-userForm.php?q="+str,true);
xmlhttp2.send();
}
Code of External PHP page Inserted By xhmlhttprequest (ajax-userForm.php):
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
// JQUERY: Plugin "autoSubmit"
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
if (input.attr('type') == "checkbox")
{
if (input.attr('checked') )
{
value = 1;
}
else
{
value = 0;
}
}
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
}
// Load output into a P
else {
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-userForm INPUT').autoSubmit();
});
</script>
<!-- STYLE -->
<style type="text/css">
INPUT { margin-right: 1em }
</style>
</head>
<body>
<!-- CONTENT -->
<?php
$q = intval($_GET['q']);
/*
* DATABASE CONNECTION
*/
// DATABASE: Connection variables
$db_host = "localhost";
$db_name = "DBNAME";
$db_username = "root";
$db_password = "DBPWD";
// DATABASE: Try to connect
if (!$db_connect = mysql_connect($db_host, $db_username, $db_password))
die('Unable to connect to MySQL from ajax-form.');
if (!$db_select = mysql_select_db($db_name, $db_connect))
die('Unable to select database');
/*
* DATABASE QUERY
*/
// DATABASE: Get current row
//$result = mysql_query("SELECT * FROM user");
$result = mysql_query("SELECT * FROM user where Project_ID = '".$q."' ");
$row = mysql_fetch_assoc($result);
?>
<form id="ajax-userForm" class="autosubmit" method="post" action="ajax-updateUser.php">
<fieldset>
<legend>Update user information</legend>
<label>First Name:</label>
<input name="FirstName" value="<?php echo $row['FirstName'] ?>" />
<label>Last Name:</label>
<input name="LastName" value="<?php echo $row['LastName'] ?>" />
<label>Hometown</label>
<input name="Hometown" value="<?php echo $row['Hometown'] ?>" />
<label>Married</label>
<input type = "checkbox" id = "chkMarried" name="Married" <?php echo $row['Married'] == 1 ? 'checked':'unchecked' ?>/>
<label>Employed</label>
<input type = "checkbox" id = "chkEmployed" name="Employed" <?php echo $row['Employed'] == 1 ? 'checked':'unchecked' ?> />
<input id="where" type="hidden" name="Project_ID" value="<?php echo $row['Project_ID'] ?>" />
</fieldset>
</form>
<p id="notice"></p>
</body>
</html>
Code for Page (ajax-updateUser.php) Called by "post" Action in Code Above (ajax-userForm.php):
/*
* DATABASE CONNECTION
*/
// DATABASE: Connection variables
$db_host = "localhost";
$db_name = "DBNAME";
$db_username = "root";
$db_password = "DBPWD";
// DATABASE: Try to connect
if (!$db_connect = mysql_connect($db_host, $db_username, $db_password))
die('Unable to connect to MySQL from ajax-update.');
if (!$db_select = mysql_select_db($db_name, $db_connect))
die('Unable to select database');
$message = "Connection Successful";
//echo "<script type='text/javascript'>alert('$message');</script>";
// DATABASE: Clean data before use
function clean($value)
{
return mysql_real_escape_string($value);
}
/*
* FORM PARSING
*/
// FORM: Variables were posted
if (count($_POST) > 0)
{
$message = count($_POST);
//echo "<script type='text/javascript'>alert('$message');</script>";
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE user SET ".$col."='".$val."'
WHERE ".$w_col."='".$w_val."'")
or die ('Unable to update row.');
}
else
{
$message = "Nothing in Post";
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>

Couple things:
Missing a close quote on your
DBPWD
Your check for status 200 uses:
xmlhttp // whereas the rest is xmlhttp2
My theory, without more context -
You're not using a var keyword when declaring:
xmlhttp2=new XMLHttpRequest();
Which means that the request is attached to the window like this: window.xmlhttp2 = ... - could you be accidentally modifying the same identifiers elsewhere on the "parent" page? That would explain a shared state error and why it works only in isolation (you would have no other code implicitly modding window.xmlhttp2)
You could also be doing bad things with:
xmlhttp2.open("GET","ajax-userForm.php?q="+str,true);
Since I don't know what this path means.
Another one could be, do you have CORS headers set for the request from the external domain?
Cheers,
Andrew

Related

How to get the text value of a datepicker?

I am trying to get the text value of a datepicker so that I can store it in a MySQL database.
Here is a sample of my HTML code (index.php):
<div class="col-xl-6">
<input id="datepicker2" placeholder="Date">
</div>
<div class="col-xl-12">
<a href="#form3" class="popup-with-form">
<button type="submit" class="boxed-btn3" onclick="customFunction()">Next</button>
</a>
</div>
Here is the JavaScript code (within index.php):
<script>
function customFunction() {
var DateOfBirth = document.getElementById("datepicker2").value;
if (DateOfBirth != null && DateOfBirth !="") {
$.post("insert.php", {DateOfBirth : DateOfBirth },function(response){
console.log(response);
});
}
}
</script>
Here is the insert.php file code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$Date = isset($_POST['DateOfBirth'])?$_POST['DateOfBirth']:'';
$sql = "INSERT INTO datepick (SinceDate) VALUES ('"$Date"')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The issue I am having is that I am unable to get the text value of the datepicker. Does anyone know a solution to this?
I think the problem of the empty post in your insert.php script is the fact that your JS doesn't properly send the data to the php script. I played a bit with your example on my own dev environment and i managed to make it work.
The only thing i changed in your index.php is that i gave your button an id so i can call it from javascript and i moved the javascript code in a separate file. I've been running a content-security-policy for so long that i just can't leave inline js anymore.
index.php
<div class="col-xl-6">
<input id="datepicker2" placeholder="Date">
</div>
<div class="col-xl-12">
<a href="#form3" class="popup-with-form">
<button id="submit-button" type="submit" class="boxed-btn3">Next</button>
</a>
</div>
<script src="js.js"></script>
I will use native JS and with new ES6 synthax and will also remove your JS from inline event hanlers (better anyway). Also i will not be using the jQuery ajax but native javascript fetch. So i've put your js in a file called js.js
js.js
document.getElementById('submit-button').addEventListener('click', () => {
// pick the value of the input
const dateofBirth = document.getElementById('datepicker2').value;
// same as yours
if (dateofBirth != null && dateofBirth != '') {
// Using the new modern fetch api to send the request
fetch('insert.php', {
headers: {
// This is what was missing from your call
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'post',
// Building the data to send, basically you need a key value pair, so i gave it a 'data' key and value - the value of the input
body: new URLSearchParams({
'date': dateofBirth
})
})
.then(response => response.text())
.then(text => {
// log the response in the console, for debug
console.log(text);
})
}
});
Now, your insert.php file. You are wide open to SQL Injection attack with the current insert, so i have made some changes to include prepared statements.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Create connection, no need to check if it succeeded, we will be extending the error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$Date = isset($_POST['DateOfBirth']) ? htmlspecialchars($_POST['DateOfBirth']) : null;
if ($date !== null) {
// build the sql query for prepared statement
$sql = "INSERT INTO datepick (SinceDate) VALUES (?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $Date);
if ($stmt->execute()) {
echo "New record created successfully";
}
}
$conn->close();
?>
Change the attribute in the button tag, right now is submit, change it for button.
<button type="button" class="boxed-btn3" onclick="customFunction()">Next</button>

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

php function that sends message to XMPP server give no log and doesn't work

Im working on getting a webpage where users input a text in a form and click submit. From there it validates the input and sends it to a php function that uses JAXL 3.0 library to send the message to my XMPP server.
My problem is that when I call the JAXL function nothing just happens. it's like it can't finish the function as the next function never gets it's call. if I swap the order around the other functions gets called but it still doesn't finish the sendmessage() function.
I'm rusty/new in php and I can't get JAXL to provide a log or anything to debug where my issue is.
If anyone know how to debug this php/JAXL function properly it would be a large help.
I've searched the web around and looked at examples for JAXL but can't find my issue :/
EDIT: Tried some debugging with ECHO. I can't get a ECHO out if it's posted below my Create client. If I ECHO right above it works.
My Sendmessage function:
function sendping()
{
//get the form elements and store them in variables
$ping_text=$_POST["pingtext"];
// Config Details
$host = 'example.com';
$user = 'host';
$pass = 'password';
// Create Client
$client = new JAXL(array(
'log_path' => '/var/log/jaxl.log',
'jid' => $user.'#'.$host,
'pass' => $pass,
'log_level' => JAXL_INFO,
'auth_type' => 'PLAIN'
));
// Add Callbacks
$client->add_cb('on_auth_success', function() use ($host, $client, $ping_text) {
$client->send_chat_msg($host.'/announce/online', $ping_text);
$client->send_end_stream();
});
$client->add_cb('on_auth_failure', function($reason) use ($client)
{
$client->send_end_stream();
_info("got on_auth_failure cb with reason: $reason");
});
$client->add_cb('on_disconnect', function() use ($client)
{
_info("got on_disconnect cb");
});
// Startup Client
$client->start();
My hole .php page:
<?php
/*
Template Name: Stahp Ping
*/
require 'jaxl.php';
get_header(); ?>
<div id="hidden_div" style="display:none; margin-left:auto; margin-right:auto; margin-top:20px;
text-align:center;">
<p>Ping has been sent </p>
</div>
<div style="width:850px !important;
margin-left:auto;
margin-right:auto;
margin-top:20px;
text-align:center;" id="pingform">
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']);?>" method="post" name="stahpbox">
<textarea name="pingtext" rows="8" cols="60"></textarea>
<input type="submit" value="Send Ping" />
</form>
</div>
<script type="text/javascript">
function showHide() {
var div = document.getElementById("hidden_div");
var pingdiv = document.getElementById("pingform");
if (div.style.display == 'none') {
div.style.display = '';
pingdiv.style.display='none';
}
else {
div.style.display = 'none';
pingdiv.style.display = '';
}
}
</script>
<?php
function sendping()
{
//get the form elements and store them in variables
$ping_text=$_POST["pingtext"];
// Config Details
$host = 'example.com';
$user = 'user';
$pass = 'password';
// Create Client
$client = new JAXL(array(
'log_path' => '/var/log/jaxl.log',
'jid' => $user.'#'.$host,
'pass' => $pass,
'log_level' => JAXL_INFO,
'auth_type' => 'PLAIN'
));
// Add Callbacks
$client->add_cb('on_auth_success', function() use ($host, $client, $ping_text) {
$client->send_chat_msg($host.'/announce/online', $ping_text);
$client->send_end_stream();
});
$client->add_cb('on_auth_failure', function($reason) use ($client)
{
$client->send_end_stream();
_info("got on_auth_failure cb with reason: $reason");
});
$client->add_cb('on_disconnect', function() use ($client)
{
_info("got on_disconnect cb");
});
// Startup Client
$client->start();
}
//Validation and redirection to send to jabber
// Initialize variables and set to empty strings
$pingtextERR="";
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true; //Your indicator for your condition, actually it depends on what you need. I am just used to this method.
if (empty($_POST["pingtext"])) {
$pingtextERR = "Text is required";
$valid = false; //false
echo "<script type='text/javascript'>alert('$pingtextERR');</script>";
}
//if valid then redirect
if($valid){
echo "<script> showHide(); </script>";
sendping();
}
}
?>
Apprently the issue was that the PLAIN auth. isn't working for JAXL, so changed it to another AUTH and it worked fine.

Add a record to the database with XMLHttpRequest

I have the following form:
<form id="form" name="form">
<img id="close" src="images/3.png" onclick ="div_hide()">
<h2>Grade</h2>
<hr>
<input id="fn" name="fn" placeholder="Faculty number" type="number">
<select id="grade_type" name="grade_type">
<option value="test" selected="selected">Тест</option>
<option value="attendance">Attendance</option>
<option value="homework">Homework</option>
</select>
<input id="grade" name="grade" placeholder="Points" type="number">
Add record
</form>
When I click the submit button I want to add the points and the grade_type to the database. Therefore I am using JavaScript and PHP:
// Validating Empty Field
function check_empty() {
if (document.getElementById('grade').value == "") {
alert("Fill the fields!");
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
alert("xmlhttpreq");
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var grade = String(document.getElementById('grade').value);
var grade_type = document.getElementById('grade_type');
var grade_type_value = String(grade_type.options[grade_type.selectedIndex].value);
var fn = String(document.getElementById('fn').value);
xmlhttp.open("GET","getuser.php?grade="+grade+"grade_type="+grade_type_value+"fn="+fn,true);
xmlhttp.send();
document.getElementById('form').submit();
}
}
The contents of the getuser.php file are:
<?php
require "config.php";
$fn = $_GET["fn"];
$grade = $_GET["grade"];
$type = $_GET["grade_type"];
echo "<script type='text/javascript'>alert('$fn');</script>";
try {
$conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $e) {
die("Database connection could not be established.");
}
$sql = $conn->prepare("SELECT * FROM students WHERE fn = ?");
$sql->execute(array($fn));
if($sql->rowCount() > 0) {
$statement = $conn->prepare("INSERT INTO points (student_fn, type, grade, datetime)
VALUES (?, ?, ?, CURRENT_TIMESTAMP)");
$statement->execute(array($fn, $type, $grade));
}
else {
echo "<script type='text/javascript'>alert('No such fn');</script>";
}
$conn = null;
?>
However I think it never gets executed because I never see the result of the alert. I have never worked with XMLHttpRequest before so I don't even know whether my code is valid. I would greatly appreciate any help.
You can do this by using jquery.
$('#submit').click(function(){
$.ajax({
url: 'getuser.php',
type: 'GET',
data: $('#form1').serialize(),
success: function(result){
alert("Your data has been uploaded");
}
});
});
make sure that you need to add jquery file to your websitelike that

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