I need to change a session value inside a JavaScript function so I decided to use AJAX. However, the call does not seem to be working. What is wrong?
Index page setting default session value:
session_start();
if( is_null($_SESSION['lang']) ){
$_SESSION['lang'] = 'english';
}
AJAX call on index page:
var request = new XMLHttpRequest();
request.open('GET', 'setlang.php?entry=0', false);
request.send();
The setlang.php file:
$entry = $_GET['entry'];
if($entry == 0){
$_SESSION['lang'] = 'english';
Print_r ($_SESSION);
}else if($entry == 1){
$_SESSION['lang'] = 'japanese';
Print_r ($_SESSION);
}
Nothing is being printed. Does anyone know what is wrong?
You didn't actually have anyway to check the response (unless you omitted some part of your javascript).
Check MDN's XMLHttpRequest's documentation.
var request = new XMLHttpRequest();
request.onload = function() {
alert(this.responseText);
}
request.onerror = function(e) {
alert('Error : ' + e.target.status);
}
request.open('GET', 'setlang.php?entry=0', false);
request.send();
Also make sure you call session_start(); in your php file.
Add this on the top of setlang.php:
session_start();
Related
Ive tried on load atribute in body tag without success
<body onload=\"updateGroup()\">
nor function calling inside echo:
echo "<script> updateGroup(); </script>";
I'm open to critics!
function updateGroup(){
var http = new XMLHttpRequest();
var url = \"../requests/updateGroup.php\";
http.open(\"POST\", url, true);
//Send the proper header information along with the request
http.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
}
}
http.send();
}
I believe what your looking for is an iife. This should run even before document.ready
(updateGroup() {
....
})();
I have a browserside javascript file that's supposed to be asking the serverside php file for a string with an ajax request. The php file seems to have the correct string, but for some reason the ajax request is returning the string 'false'.
This is the php file, named test.php:
<?php
$dir = "site/uploads";
$a = scandir($dir);
$b = json_encode($a);
echo $b;
?>
This is the js file:
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.responseType = "text";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('test' + xmlhttp.responseText);
console.log('test' + JSON.parse(xmlhttp.responseText));
}
};
xmlhttp.open("GET", "test.php", 'false');
xmlhttp.send();
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.responseType = "text";
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
console.log('test2' + xmlhttp2.responseText);
console.log('test2' + JSON.parse(xmlhttp2.responseText));
}
};
xmlhttp2.open("GET", "test2.php", 'false');
xmlhttp2.send();
}
when i open the website in my browser and run load(), the console reads:
testfalse
testfalse
test2false
test2false
and has no errors. What am I doing wrong here? Thanks!
scandir() in the php-file is probably returning false, because of an error.
https://www.php.net/manual/de/function.scandir.php (Check the return values)
There are multiple possiblities for this to happen:
The folder doesn't exist
The path is incorrect (Try using absolute paths)
The folder isn't accessible, because of missing permissions
In my JS code, I take in 3 inputs on a html page and save them to local storage. I then want to send these variables to php in order to save them to my database. No matter how hard I try no tutorial using ajax, jquery etc allows me to successfully post and echo variables from javascript in my php code. I see no reason why my code below doesn't echo the variables, but it doesn't.
Full code: https://codeshare.io/ayvK9e
Exact PHP elements (just trying to send normal variables right now as it still won't work"
PHP:
foreach($_POST as $post_var){
echo($post_var);
}
JS:
const xhr = new XMLHttpRequest();
xhr.onload = function(){
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText
};
xhr.open("POST", "eDBase.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=dominic&message=bumbaclaat");
If $post not work try using input php
$data = json_decode(file_get_contents('php://input'), true);
When calling my function with the inputs onclick=showFunction; I was passing nothing to the function. In order for my values to be echoed in php I had to pass a parameter to the function onclick=function('text or variable'); IDK how I missed that.
Try using the FormData()
let form = new FormData();
form.append('name', 'dominic');
form.append('message', 'bumbaclaat');
const xhr = new XMLHttpRequest();
xhr.open("POST", "eDBase.php");
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText;
}
else console.log('error')
};
xhr.send(form);
Comment out the setRequestHeader to test it.
And at PHP
if(isset($_POST['name'])){
echo $_POST['name'];
echo $_POST['message'];
}
else{
echo 'There was a problem';
}
I am calling a php file that queries my database and returns a result. I have verified that the php file accurately returns the data as needed, but my calling page is not updated from the JavaScript.
What do I need to alter in my syntax below so that the returned value is returned on page?
<script type="text/javascript">
function boostion()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("data").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
EDIT
I have also opened Developer Options in Chrome and checked the Console and there are no errors or issues displayed, everything is a success!
Edit 2
I tried to use the JQuery approach below and used this syntax - but I get the error
Uncaught TypeError: $(...).load is not a function
Syntax:
<script src="https://code.jquery.com/jquery-3.1.1.slim.js"
integrity="sha256-5i/mQ300M779N2OVDrl16lbohwXNUdzL/R2aVUXyXWA="
crossorigin="anonymous" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
document.getElementById("data").innerHTML = data;
});
});
</script>
Edit 3
This is my php syntax that runs the sql syntax and echo result that I want to have returned from the javascript
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'host';
$option['user'] = 'user';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance( $option );
$result = $db->getQuery(true);
$result->select($db->quoteName(array('trackandfieldresults')));
$result->from($db->quoteName('[TrackData]'));
$db->setQuery($result);
$row = $db->loadRowList();
echo $row['0']
?>
Use xhr.send();
If it is a GET request, you have to apply the query string in in xhr.open and you dont have to set Content-type:application/x-www-form-urlencoded
first, the scripts should be inside the HTML before the ending body tag. then you open another file and write your code in it. JQUERY does not have script tag. Sp you are creating an external javascript file for the script. No script tag needed. Now use this format.
$(window).on('load', function(e){
e.preventDefault();
var dat = //the content you are trying to load
$.get('middleware.php', dat, function(data){
$('#selector').html(data)
});
})
I have a faster approach using JQuery.
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
//Do whatever you want here
});
});
This should do the Job. Your approach is old and kind of complicated to debug
Try this
function boostion(){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.send();
xhr.onreadystatechange = function(){
console.log(xhr);
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("data").innerHTML = xhr.responseText;
}
}
}
<div id="data"></div>
<button onclick="boostion();">Load</button>
I'm trying to send the value of a variable number via ajax to a PHP script. But the PHP script is not printing the desired output on opening on a browser. Tried but couldn't find whats wrong here.
Any pointers ?
index.html
<button type="submit" class="btn btn-success" id = 'first' onclick='process();'>Submit</button>
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.open("POST", "index.php", true);
xhr.send(data);
}
</script>
index.php
<?php
session_start();
$number = $_POST['num'];
$_SESSION['numb'] = $number;
echo $_SESSION['numb'] ;
?>
Editing my long winded lame answer since you fixed the close curly bracket... but bloodyKnuckles is right you also need something in your 'process' function to take the response from your PHP page and output it... or whatever you want to do. You can basically use the method 'onreadystatechange' in the XMLHttpRequest object and then look for a 'readyState' property value of 4 which means everything is done. Here is a simple example of that just outputting the results to the console (which you can view using developer tools in your browser of choice).
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status==200){
console.log('xhr.readyState=',xhr.readyState);
console.log('xhr.status=',xhr.status);
console.log('response=',xhr.responseText);
}
else if (xhr.readyState == 1 ){
xhr.send(data)
}
};
xhr.open("POST", "ajax-test.php", true);
}
</script>
As you go further you may want to update your PHP page to only update the session when the POST value is there.
<?php
//ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
if(isset($_POST['num'])){
session_start();
$_SESSION['numb'] = $_POST['num'];
echo $_SESSION['numb'];
}
?>
You can uncomment those ini_set and error_reporting lines to try to figure out what is going on with your PHP script.
This is because you are not sending header information with request...
Append this code
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
after
xhr.open("POST", "index.php", true);