I am trying to send data to php file then echo the word "Hello!" when i call a function in javascript, however, no message appear, i guess there is en error in the calling, can you guide me please?
Here is my code:
Javascript:
function asyncpost_deviceprint() {
var xmlhttp = false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
else if (!xmlhttp) return false;
xmlhttp.open("POST", "http://localhost/Assignment/insert.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("userAgent" + userAgent()); /* fire and forget */
return true;
}
PHP:
<?php
echo "Hello!";
?>
echo "Hello!";
won't display any message because in Ajax request this function sends a respond to Javascript.
If you want to display sth on the screen with PHP instead of Ajax you should use:
window.location.href="path to your php site"
it will redirect you to php file and display Hello!
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
document.body.innerHTML += xmlhttp.responseText;
}
}
};
Add this before xmlhttp.send
It will literally just stick the php echo text after the last thing in the document.
Related
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
Im working on an ajax form to show errors without reloading the page. So if everything is good, the user we be redirected to home.php. At the moment the user will also be redirected when there is an error.
This is my code so far:
index.php:
<script>
function myFunction()
{
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
window.location.replace("/index.php");
}
}
xmlHttp.open("post", "login.php");
xmlHttp.send(formData);
}
</script>
login.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
echo 'not ok';
}
}
?>
Remove loop from the code and pass elements in FormData() because passing element will take all the fields inside the form
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
Throw a 401 error if it fails login, this will stop the redirect.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
header("HTTP/1.1 401 Unauthorized");
exit;
}
}
?>
do you know jquery ?
jquery w3 school search on google
avaible
$('#data-div-id').load('www.sdasd .php ? or whatevver');
function tmp_func_sil_ok(e){
$.ajax({type:"GET",url:"go.php",data:{'snf_sil':e},success: function(e){msg_("<h3>Başarılı</h3>");}});
}
I am creating an AJAX+PHP submit form, for example purposes. For this, I will need Ajax, PHP and index.html file to write into the inputs. The problem is that, when I submit I have no way of redirecting a page, so I created this hack. (since page redirect get permission from the PHP script first) otherwise show error.
AJAX
function submit_form(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success'){
location.href = '/success';
}
//
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
And this is my PHP.
<?php
echo "/success";
if($_GET){
}else{
echo "error, no value found";
}
as you can see, this allows me to redirect the page, as the javascript will read the "/success" and redirect the document, but one problem with this is that, I don't like using echo, because the page actually shows "success" before redirect. I don't want it to show anything to the page.
Change your echo statement to return json_encode(), then in your JS code, you can parse it using JSON.parse();
In your PHP removes the slash of this line: echo "/success";
And in your java script code, add a else sentence before print error:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success') {
location.href = '/success';
}
else {
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
}
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);
I need to use the xhr.send(VALUE) to send the data in AJAX. How do I get this data in a PHP file?
JS:
window.onload = function() {
var value = 'hello';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(value);
}
You are just sending a string to the PHP file. You are not sending it as a query string or with a content type, so PHP doesn't populate the $POST array.
You can try to read the raw post data:
$post = file_get_contents('php://input');
echo $post; // hello
Or, if you want PHP to populate $_POST, you need to do some extra steps in your JavaScript.
window.onload = function() {
var value = 'hello';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
// Tell the server you are sending form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Send it as a query string
xhr.send('value='+value);
}
Then in your PHP, you can access $_POST['value'].
echo $_POST['value']; // hello
If you want to see the $_POST variables on the PHP page you can use this code to display them all so you can visually see their keys and values
echo "<pre>";
print_r($_POST);
echo "</pre>";
From there you will know how to use the data in any file. You can do the same thing with $_GET
Try this, replace your xhr.send with
JS
xhr.send('value='+value);
PHP
echo($_POST['value']);