Value not found in php - javascript

For login i'm passing mail id and password from javascript file and i've checked through console.log that the values are printed. But when i echo both values in php only password is showed not the mail. But i can't find any error.Here i'm pasting the php file.
<?php
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$datamail = $_GET["mailID"];
$datapass = $_GET["psw"];
//$datamail = isset($_GET["mailID"]) ? $_GET["mailID"] : '';
echo $datamail;
echo $datapass;
$login_query = "SELECT * FROM student_table where mail_id = '$datamail' AND password='$datapass'";
//echo $login_query;
$login_res = $db->query($login_query);
if( $login_res->num_rows == 1 ){
//if( $login_res == true ){
echo "success";
}
else {
//echo $login_res;
echo mysqli_error($db);
exit;
}
$db->close();
?>
Javascrit file Here
function globalLogin() {
checkLogInMail();
//pageEntry();
}
function checkLogInMail() {
var mailET = document.getElementById("mailID");
var mailIdError = document.getElementById("mailIdErr");
mailID = mailET.value;
var regex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (!regex.test(mailID)) {
mailIdError.innerHTML = "Enter a valid Email id";
//loginFlag = 1;
}
else{
checkmailPass();
}
}
function checkmailPass() {
var passET = document.getElementById("psw");
var passError = document.getElementById("pswErr");
psw = passET.value;
console.log(mailID);
console.log(psw);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
alert(response);
if(!response.localeCompare( "success" )){
document.getElementById("loginErr").innerHTML = "Mail or Password is correct";
//alert("Successfully logged in :)");
//window.location.href = "index.html";
}
else{
document.getElementById("loginErr").innerHTML = response;
}
}
}
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID"+mailID, true);
xhttp.send();
}

you miss = in your get request in mailID
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID="+mailID, true);

You missed an equal sign '=' in your javascript at your mailid parameter.

Related

Json decode from Javascript to php to Javascript

I am trying to get the value from json.stringfy sent to PHP file, for some reason php file is not receiving the key. If I manually add the key it is working fine. What could be wrong here:
My php file:
$request = json_decode(file_get_contents('php://input'), true);
$getID = $request['docid'];
$query = mysqli_query($con, "SELECT * FROM user_details WHERE id = $getID'");
if(mysqli_num_rows($query) > 0)
{
$response["details"] = array();
while ($row = mysqli_fetch_array ($query))
{
// temp user array
$detail = array();
$detail["docname"] = $row["docname"];
$detail["textresults"] = $row["textresults"];
array_push($response["details"], $detail);
}
echo json_encode($response);
$response["success"] = 1;
}
else
{
$response["success"] = 0;
echo json_encode($response);
}
This is my javascript file:
function loadData() {
var docid = window.localStorage.getItem('myKey');
console.log("Docid " + docid);
var xhr = new XMLHttpRequest();
var url = "./api/getData.php";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
}
};
var data = JSON.stringify({'docid': docid});
xhr.send(data);
}

AJAX function gives void, fread (php) output to html div

This is a PHP function that reads first the title then the content of a txt file that has been uploaded,
<?php
$q = $_REQUEST["q"];
$output = "";
if ($q !== "") {
$bestand = fopen("Blogs.txt", "r");
if (!$bestand) {
echo "Kon geen bestand openen";
}
while (!feof($bestand)) {
$blog = fgets($bestand);
$blog = explode(",", $blog);
$i = 0;
foreach ($blog as $key) {
$i++;
if ($i % 2 == 0) {
$output = $key;
}
elseif (!$i % 2 == 0) {
$Blogname = fopen("Blogs/$key", "r");
$Blogtext = fread($Blogname, filesize("Blogs/$key"));
$output = $Blogtext;
}
}
}
fclose($bestand);
}
?>
but then i wanted to have it show up in html instead of php so i search solution and found AJAX but have been struggling for hours on why it doesn't work
function Getblog() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "Blogreader.php?q=" + str, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var para = document.createElement("div");
var t = document.createElement(this.responseText);
para.appendChild(t);
document.getElementById("BlogDiv").appendChild(para);
}
};
}
This is the Javascript code that gives a void function.
What i want it to do is make a DIV of the output of a the php function
<a> <input type="button" onclick="Getblog()"></a>
<div id="BlogDiv"></div>
And this is the refresh button and the div where they are going to be showed

Run Javascript script from ajax response

I want to call a JS Script in Ajax response. What it does is pass the document.getElementById script to the Ajax responseText.
The current code returns me this error: Uncaught TypeError: Cannot set property 'innerHTML' of null
This is done with Visual Studio Cordova..
Ajax:
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
PHP:
if($count == 1){
echo "document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
";
}else{
echo "document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block';
";
}
You can solve it by a small change, you just have to write JS code in the AJAX success that you wrote in your PHP page. In the PHP page, there is no alertBox element, that's why the error occurred.
Your JS code will be like this:
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText=="success"){
document.getElementById('alertBox').innerHTML = 'Login Success!';
document.getElementById('alertBox').className = 'alert alert-success';
document.getElementById('alertBox').style.display = 'block';
setTimeout(function () {
window.location.href = '../html/dashboard.html';
}, 1000);
}elseif(this.responseText=="error"){
document.getElementById('alertBox').innerHTML = 'Invalid login details';
document.getElementById('alertBox').className = 'alert alert-danger';
document.getElementById('alertBox').style.display = 'block'
}
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
And PHP code like:
if($count == 1){
echo "success";
}else{
echo "error";
}
Basically you get that error because the thing you're trying to change is not on the page when you look for it.
What you need to do is, do not write javascript with PHP. You return something like an int from php and then use that to decide what the javascript does.
You have the html on the page and just change the content inside it.
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var str = this.responseText; //you may need to trim whitespace
var alert = document.getElementById('alertBox');
if (str.trim() == 1) {
alert.innerHTML = 'Login Success!';
alert.className = 'alert alert-success';
alert.style.display = 'block';
setTimeout(function() {
window.location.href = '../html/dashboard.html';
}, 1000);
}
else {
alert.innerHTML = 'Invalid login details';
alert.className = 'alert alert-danger';
alert.style.display = 'block';
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});
<div id="alertbox"></div>
PHP Code:
if($count == 1){
echo 1;
}
else{
echo 0;
}
Use eval like below
$("#loginBtn").click(function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var fun = eval(this.responseText);
}
}
xmlhttp.open("POST", "http://www.sampleee.esy.es/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);
});

Why am I not able to fetch property of the object that I get from PHP?

I am trying to receive data from database based on the name entered by user, everything works fine I do see the value on screen and no error Here is the php code :
<?php
$dbhost = "localhost";
$username = "root";
$password = "";
mysql_connect($dbhost,$username,$password);
#mysql_select_db("trynew") or die(mysql_error());
$user ="mon";
$query = "SELECT * FROM trynewtable where name = '$user' ";
$all_result = array();
$result = mysql_query($query);
if($result==FALSE)
{
die(mysql_error());
}
while($row = mysql_fetch_assoc($result))
{
$all_result[] = $row;
}
header('Content-Type: application/json');
$jsondata = json_encode($all_result);echo $jsondata;
mysql_close();
?>
JavaScript code :
var loadingFunc=function()
{
var xhr;
if(window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else
{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var jsonData= "";
xhr.onreadystatechange =function()
{
if(xhr.readyState==4)
{
if(xhr.success =200)
{
jsonData = xhr.responseText;
document.getElementById("dvID").innerHTML = jsonData;
//var parsejson = JSON.parse(jsonData);
//document.getElementById("dvIDO").innerHTML = parsejson.age;
document.getElementById("dvIDO").innerHTML = jsonData[0].age;
}
else
{
document.getElementIdById("dvID").innerHTML = "it's not success ";
}
}
else
{
console.log("error is here");
console.log(xhr.readyState);
}
}
var element1 = document.getElementById("dvID") ;
xhr.open("POST","index.php");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var sendD = document.getElementById("data_found").value;
var data = "data_found=" + sendD;
var element = document.getElementById("btn") ;
if(element)
{
element.addEventListener('click',function(){
console.log("just clicked")
xhr.send(data);
})
}
};
window.onload = loadingFunc();
but the output that I see on the html div is :
[{"id":"1","Name":"mon","Age":"26","Gender":"F"}]
undefined
I am getting the whole object but whenever I am trying to fetch any property of the object like age here (parsejson.age or jsonData[0].age) it's showing undefined , Could anyone help me how do I fetch any property of the object?
Kindly let me know what am I doing wrong ?
First transform the cleartext response into a javascript object. You have the line already there but commented out it seems, after that:
alert(jsonData["Age"]); //Age
alert(jsonData.Age); //Age

Unable to pass value to php POST via javascript

I am trying to update the text from textbox to database using the onclick event and calling a javascript function.
This is the javascript code
function send_post()
{
var hr = new XMLHttpRequest();
var url ="send_post.php";
var fn = document.getElementById("post").value;
var vars = "post="+fn;
hr.open("POST",url,true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencode");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status ==200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = fn;
}
This is the php file code
<?php include 'inc/connect.inc.php';
$post =#$_POST['post'];
if ($post != "") {
$date_added = date("Y-m-d");
$added_by = "test123";
$user_posted_to = "test123";
$sqlCommand = "INSERT INTO posts VALUES('','$post','$date_added','$added_by','$user_posted_to')";
$query = mysql_query($sqlCommand) or die (mysql_error());
}
else{
echo "Write something to post.";
}
?>
But I get this error from the php :
Undefined index: post on line 3
The MIME type you are trying to use is application/x-www-form-urlencoded (with a d on the end).
PHP doesn't know how to parse data encoded as application/x-www-form-urlencode (without the d) so it doesn't populate $_POST for your code.
Javascript part:
<script>
function getXMLObject(){
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e2) {
xmlHttp = false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
var xmlhttp = new getXMLObject();
function send_post() {
if(xmlhttp) {
var post = document.getElementById("post").value;
xmlhttp.open("POST","send_post.php",true);
xmlhttp.onreadystatechange = resultPost;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("post=" + post);
}
}
function resultPost() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
}
</script>
PHP part:
<?php
include 'inc/connect.inc.php';
if(isset($_POST['post']) && trim($_POST['post']) != '') $post = mysql_real_escape_string(trim($_POST['post']));
else $post = '';
if ($post != '') {
$date_added = date("Y-m-d");
$added_by = "test123";
$user_posted_to = "test123";
$sqlCommand = "INSERT INTO posts VALUES('','$post','$date_added','$added_by','$user_posted_to')";
$query = mysql_query($sqlCommand);
if(mysql_affected_rows($link) == 1){
echo 'Operation successfully executed';
exit;
}
}
echo 'Write something to post.';
?>

Categories

Resources