why i am getting empty response text in ajax? - javascript

below is my code fo ajax which sends a string data via post method, the request is successful but I get an empty response. I had checked the readystate and status both are proper and the php file is in the same directory.
function getData(str)
{
if (str == "")
{
} else
{
if (window.XMLHttpRequest)
{
var dat = new XMLHttpRequest();
} else
{
dat = new ActiveXObject("Microsoft.XMLHTTP");
}
dat.open("POST","userdat.php",true);
dat.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
dat.onreadystatechange = function ()
{
if (dat.readyState == 4 && dat.status == 200)
{
alert(dat.responseText);
$('#dataReT').text(dat.responseText);
}
}
dat.send("userid=" + str);
}
}
content of my php file:
<?php
$id=$_REQUEST['userid'];
echo $id;
?>

there is no userid in $_REQUEST. Try to add this to your php file:
if(array_key_exists('userid',$_REQUEST)) {
echo $_REQUEST['userid'];
} else {
echo 'no userid.';
}
You may send userid value from your javascript file

Related

XMLHttpRequest POST _self using localStorage with PHP

I'm using PHP 7.3 with MySQL v5.6.
Browsing a catalog page, I stored some items ids to localStorage.wishlistStorage.data, and now on the wishlist page I want to retrieve this list of ids for display. I'm using PHP because later I will be sending and retrieving items from a database. Also, it's easy to build HTML on the fly using PHP and a POST array. Unfortunately, I'm struggling with the AJAX XMLHttpRequest.
I am loading a Javascript file at the bottom of the page that retrieves the localStorage data:
var wishlistStorage = {};
window.addEventListener("load", function() {
wishlistStorage.get();
loadWishlist();
});
wishlistStorage = {
data : null, // empty storage
get : function() {
wishlistStorage.data = localStorage.getItem("wishlistStorage");
if(wishlistStorage.data === null) {
wishlistStorage.data = { items: [], item_notes: [], comments: '' };
wishlistStorage.save();
}
else {
wishlistStorage.data = JSON.parse(wishlistStorage.data);
}
}
};
// get wishlist contents
function loadWishlist() {
var items = wishlistStorage.data.items.join("%20");
var wishlistRequest;
if(window.XMLHttpRequest) {
wishlistRequest = new XMLHttpRequest();
} else {
wishlistRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
wishlistRequest.onreadystatechange = function() {
if(wishlistRequest.readyState == 4 && wishlistRequest.status == 200) {
console.log("Got them.");
} else {
console.log("I see nothing.");
}
wishlistRequest.open("POST", "_self", true);
wishlistRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
wishlistRequest.send("wishlist_items=" + encodeURIComponent(items));
}
}
In the body of wishlist.php
<?php
if (array_key_exists('wishlist', $_POST)) {
$temporary_wishlist = $_POST['wishlist'];
echo "Yes, it works! $temporary_wishlist";
} else {
echo 'Invalid parameters!';
}
?>
All I get is the "Invalid Parameters" message. None of the console.log messages appear. Where am I going wrong?
source

PHP write file works, but says false

I don't have much experience with PHP, but what I'm trying to do is to write content to a file. For some reason the content is written to the file, but still returns 'failed to write to file!' with the 400 status code. But the contents are successfully written to the file. How?
php code (update.php):
<?php
//get root and page of request
$content_root = $_SERVER['DOCUMENT_ROOT'] . '/Animagie/content';
$page = $_POST['page'];
//open the correct contentfile
$content_file = fopen($content_root . '/' . $page, 'w');
if (isset($_POST[$page . '-content'])) {
if (fwrite($content_file, $_POST[$page . '-content']) === FALSE ) {
echo 'failed to write to file!';
fclose($content_file);
http_response_code(400);
} else {
fclose($content_file);
http_response_code(200);
}
} else {
echo 'something went wrong!';
fclose($content_file);
http_response_code(400);
}
?>
I call update.php with following code:
editor.addEventListener('saved', function(e) {
var name, payload, regions, xhr;
//check if something changed
regions = e.detail().regions;
if (Object.keys(regions).length === 0) {
return;
}
//set editor busy while saving
this.busy(true);
// Collect the contents of each region into a FormData instance
payload = new FormData();
payload.append('page', getCurrentPage());
for (name in regions) {
if (regions.hasOwnProperty(name)) {
payload.append(name, regions[name]);
}
}
// Send the updated content to the server to be saved
function onStateChange(e) {
//check if request is finished
if (e.target.readyState === 4) {
editor.busy(false);
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
}
}
xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '../api/update.php');
xhr.send(payload);
});
As you probably can tell it's quiet important to get the correct statuscode since I check for it and return if it's succesfull or not to the user. Anyone able to help me?
Thanks in advance!
Apperently the problem lays in the javascript check:
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
should be
if (e.target.status == 200) {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
Also after I switched the if-statement (like told by #Jon Stirling), postman wasn't refreshed yet. So it was partially a wrong if-statement on the server side & wrong if-statement on the client side.

Session Management HTML Client and PHP on Server

Serverside: PHP
Clientside: HTML and Javascript
I am trying to create a session manager in HTML (Phonegap). The HTML should maintain the session based on the authentication of PHP on server side.
I am able to start the session in PHP (its in the below code), what i need is, This session code of PHP should start within HTML.
I want the session of PHP in HTML because the phonegap does not understand PHP files. So i need to manage everything with HTML and javascripts.
HTML:
<input type="text" name="txt" id="txt" placeholder="Enter Your ID" class="inputText" />
<input type="submit" OnClick="JavaScript:doCallAjax();" class="inputSubmit" value="Login">
Javascript:
Script :
var HttPRequest = false;
function doCallAjax() {
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'http://localhost:9999/working-DONOT-TOUCH/login.php';
var pmeters = "tPassword=" + encodeURI( document.getElementById("txt").value );
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "Now is Loading...";
}
if(HttPRequest.readyState == 4) // Return Request
{
if(HttPRequest.responseText == 'Y')
{
window.location = 'mainmenu.html';
}
else
{
alert('Wrong User ID ');
}
}
}
}
</script>
PHP:
session_start();
$password = trim($_POST["tPassword"]);
if(trim($password) == "")
{
echo "<font color=red>**</font> Plase enter [ID]";
exit();
}
$mysqli=mysqli_connect('localhost','root','root','db');
$query = "SELECT * FROM pg_master_students_details WHERE Stu_Register_No='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if($row)
{
echo "Y";
$_SESSION["password"] = $password;
session_write_close();
}
else
{
echo "<font color=red>**</font> ID is wrong";
}
mysqli_close($mysqli);
?>
You should manage all html content based on a json requested to your server via javascript.
When you do a login to the server, the server responds by returning a cookie (PHPSESSID).
If you keep using the same cookie on your requests, your session will be the same once logged in. I'm not sure if jquery (for example), maintain the same cookie in each ajax request, but just to keep in mind.

Return value from php to javascript

I writing a registration/login form, I am sending user info via POST to a PHP that is looking in a DB. I would like that the PHP returns an ok or wrong value to the js and I don't now how to do it.
Here my js:
ui.onClick_regsubmit=function()
{
var fname=document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var affiliation=document.getElementById('affiliation').value;
var data = new FormData();
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
data.append("fname",fname);
data.append("lname",lname);
data.append("password",password);
data.append("mail",mail);
data.append("affiliation",affiliation);
xhr.open( 'post', 'PHP/registration.php', false );
xhr.send(data);
window.alert(affiliation);
}
And the php:
<?php
mysql_connect('localhost','root','') or die('Cannot connect mysql server');
mysql_select_db('ChemAlive_login') or die('cannot connect database');
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$password=$_POST['password'];
$mail=$_POST['mail'];
$affiliation=$_POST['affiliation'];
$q=mysql_query("select * from login where mail='".$mail."' ") or die(mysql_error());
$n=mysql_fetch_row($q);
if($n>0)
{
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password) echo "ok";
else echo "wrong";
}
else
{ $insert=mysql_query("insert into login values('".$fname."','".$lname."','".$mail."','".$password."','".$affiliation."')") or die(mysql_error());}
?>
I would like to return to js this ok or wrong value. How to do it?
xhr.onload=function()
{
if (xhr.status==200)
{
alert(xhr.response);
}else
{
alert("unknown server error");
}
}
it will be better if the server sends a response code, and javascript will transfer this code to the text. For example:
onload=function()
{
switch(xhr.response)
{
case "0":{alert("unknown error")};break;
case "1":{alert("email is already used")};break;
...
}
}
I think thought it is clear
I do not have the rep to comment or I'd ask for details, but if you can consider using ajax, it could look something like this:
php:
$doit = //your query;
if($doit){
$youdid = 'ok';
}
else{
exit('1');
}
js:
$(document).ready(function () {
var foo = $("#formfield")val();
$.ajax({
"foo":foo;
type: 'POST',
url: 'some.php',
success: function(responseText) {
if(responseText == "1") {
alert("Leave instantly");
};
}
else {
alert("One of us");
}
If you want to return either ok or wrong to the JavaScript to handle you could do something like this in your registration.php page:
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password){
header('Content-Type: application/json');
echo json_encode(array('password' => 'ok'));
}else{
header('Content-Type: application/json');
echo json_encode(array('password' => 'wrong'));
}
I have not fully testing this, but the idea is to set the header to return json and then send it a JSON string.
Does that make sense?
Like I said in my comment below I have only used jQuery for AJAX. But here is a little something of what I know about XMLHttpRequest and my undertsanding of how you would test what you get back.
You can set up a listener for when you get a response back onreadystatechange and then put the response in a variable var pass = xhr.response and then just output the text to an alert box like alert(pass.password).
if (xhr.onreadystatechange === 4 && xhr.status === 200){
var pass = xhr.response;
//should output either ok or wrong
alert(pass.password);
}
Read more about XMLHttpRequest here
Let me know if that works.

my php can't receive the 'post' variabe I am sending via ajax

Here is my javascript:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
hanapin.send(reqdata);
hanapin.onreadystatechange = function() {
if (hanapin.readyState == 4 && hanapin.Status == 200) {
document.getElementById('province').innerHTML=hanapin.ResponseText
}
}
window.alert(targeturl);
window.alert(reqdata);
}
I know the function is receiving the data because I used the alert.
but on php:
<?php
$findwat = $_POST['condo'];
echo $findwat;
?>
even when I open the php file using a separate link it won't echo the variable
An example using jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
function fetchprov(proptype) {
$.post("testajax.php", {condo:proptype}, function(data){
// data is the result received from php
alert(data);
});
}
A mandatory header field for http post request is Content-length. change your code to:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hanapin.setRequestHeader("Content-length", reqdata.length);
hanapin.setRequestHeader("Connection", "close");
hanapin.send(reqdata);
hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText} }
window.alert(targeturl);
window.alert(reqdata);
}
also a better solution is to use jquery to handle ajax

Categories