php file not running when called from xmlhttprequest - php

I am having trouble with my php file (login.php) running when called by javascript using XMLHttpRequest. The php file works fine when I run it from the url, but does not seem to be called by the XMLHttpRequest. I'm new to this and am struggling to get this working.
The javascript file just gets the username and password and sends them as parameters to the php file in the url. The Php file logs check with the database for a correct combination.
My Javascript file:
function logIn(){
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
var usename = document.getElementById("userName").value;
var password = document.getElementById("password").value;
var url = "login.php?q=" + usename + "&x=" + password;
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlenclosed');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4){
alert("GOOD");
}}
xmlhttp.send(url);
alert(url + xmlhttp.status);
}
function logInClick(){
logIn();
}
window.onload = function() {
document.getElementById("AboutMe").onclick=aboutMessage;
document.getElementById("ContactMe").onclick=contactMessage;
document.getElementById("submitButton").onclick=logInClick;
}
My Php file:
<?php
$host="localhost";
$username="root";
$password="";
$db_name="website";
$tbl_name="users";
mysql_connect("$host","$username","$password")or die("Cannot Connect");
mysql_select_db("$db_name")or die("Cannot Select DB");
$inputUserID=$_POST['q'];
$inputPassword=$_POST['x'];
//$encrpytedPassword=md5($inputPassword);
$inputUserID = stripslashes($inputUserID);
$inputPassword = stripslashes($inputPassword);
$inputUserID = mysql_real_escape_string($inputUserID);
$inputPassword = mysql_real_escape_string($inputPassword);
$sql = "SELECT * FROM $tbl_name WHERE userID='$inputUserID' and Password='$inputPassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if ($count==1){
session_start();
$_SESSION['userID']=$inputUserID;
//change this at some point
header("location:regularUserLoggedIn.html");
} else {
header("location:www.yahoo.com");
}
?>
Any help would be great. Thanks.

The first line of your PHP Script is header. The execution of the script is stopped after header. Try removing that line and just echo what you get at the server first..

The first line of your php code redirects to another page. The result of the javascript returns will be the redirected page content rather than the outputted content of your code.
P.S. Your javascript code has security issues that others can steal the passwords easily.

Related

forgot password page in php

I wanted to create a forgot password page. To avoid mailing the user with his details, I decided to display his details in an alert box, although I know that it is much less secure!
So, here's my code in the php file "forgotdetails.php".
//Here are my database details, which I can't show.
$conn= mysql_connect($dbhost, $dbuser, $dbpass);
// Check connection
if(!$conn){
die('Could not connect'.mysql_error() );
}
$db_selected = mysql_select_db('users');
if(!$db_selected){
die('wrong'.mysql_error() );
}
$post_username = $_POST['email']; // the ajax post username
$query = "SELECT * FROM users WHERE id='". $post_username. "'";
$results= mysql_query($query);
$row=mysql_fetch_assoc($results);
$username=$row['id'];
$password=$row['pass'];
if(mysql_num_rows($results)==0)
{
echo "pass= " . $password;
echo "You haven't registered yet! Go to the Home-Page to Register!";
/*$query = "SELECT * FROM users WHERE id='$post_username' AND pass='$post_password'";*/
}
else
{
echo $password;
echo "Your Login details are-:"."\nUser ID- ". $username . "\nPassword- ". $password . "\nLogin to your account, to change your password. ";
}
And here's my ajax function (inside the html file) which is getting called as the forgot password button is clicked-:
<script lang="javascript" type="text/javascript">
function ajaxFunction1() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function ()
{ if (ajaxRequest.readyState == 4)
{ var ajaxDisplay = document.getElementById('results');
alert (ajaxRequest.responseText);
ajaxDisplay.innerHTML = "<br/><br/><h2><font color='#18E618'>"+ajaxRequest.responseText+"</font></h2>"; } }
// Now get the value from user and pass it to
// server script.
var email = document.getElementById('email').value;
//var bitsmailid = document.getElementById('bitsmailid').value;
if ( email== "" || email== null || email== '') {
alert("BITS ID Not Filled");
exit();
}
/*if ( bitsmailid== "" || bitsmailid== null || bitsmailid== '') {
alert("BITS Mail ID Not Filled");
exit();
}*/
var queryString = "?email=" + email;
ajaxRequest.open("POST", "forgotdetails.php" +queryString, true);
ajaxRequest.send(null);
}
</script>
My query is that, the I need to check whether the query returned through SQL in the PHP File ($results) is empty or not and then I need to perform the functions as i have mentioned in my code. I have used mysql_num_rows($results)==0 condition (which I got to know after reading similar posts on Stack Overflow). Although it doesn't seems to evaluate correctly. It evaluates true always, even though there are entries in the database.
I have read all the posts concerning this type of questions on Stack Overflow, and after 12+ hours of testing the code with many different possibilities, still I am still unable to solve my query. I have provided all the details necessary for my query, however If anyone needs anything, I will provide them with you.
I am a newbie into Web Development, so please help me to solve my query. Thank You in advance for your Help!
I am sorry if you feel that this question has already been answered earlier, however I posted this again because those posts sadly couldn't help me. I have read all of them. Sorry!
It should be
$sql = "SELECT * FROM users WHERE id='". $post_username. "'";
$result = mysql_query($sql, $conn);
if ($result && (mysql_num_rows($result) > 0)) {
// user exists
// here you get row
$row = mysql_fetch_assoc($result);
}
I know it is without pdo and it is insecure.

Web server exited unexpectedly, restarting new instance

I do not have any other option, but to ask here again... and problem is killing me for the past 5 hours. I got button that call javascript function, and then javascript opens another php page and does insert in MySQL database.
HTML code:
<ul>
<li id="ConfirmButton" name="Insert" onclick="GetAllIDs()"><a>Potvrdi</a></li>
</ul>
Javascript code:
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
http.open('get', 'insert.php?MatchID='+MatchID+'&TipID='+TipID+'&UserID=' + 1,true);
http.send(null);
PHP code:
include('config.php');
$matchID = $_GET['MatchID'];
$tipID = $_GET['TipID'];
$userID = $_GET['UserID'];
// Escape User Input to help prevent SQL Injection
$MatchID = mysql_real_escape_string($matchID);
$TipID = mysql_real_escape_string($tipID);
$UserID = mysql_real_escape_string($userID);
$insertTicket_sql = "INSERT INTO
betslips(DateTime,MatchID,TipID,UserID)
VALUES(".$MatchID.",".$TipID.",'".date("Y-m-d H:i:s")."',".$UserID.")";
$insertTick= mysql_query($insertTicket_sql) or die(mysql_error());
So after I run this code and I use break point I see in my php code all parameters I sent over forms normally and it's all there, but when I reach code $insertTick I get error
web server exited unexpectedly, restarting new instance.
Has anyone seen this problem before, and how can I deal with it?
Thanks
did anyone seen this problem before?
Not me, I dont use the mysql_* functions.
Your INSERT query parameter and values dont match.
So ive ported your example code to PDO perhaps its some interest:
<?php
//PDO Connect
try{
$con = new PDO('mysql:host=127.0.0.1;dbname=yourDB','root','password');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}catch (Exception $e){
die('Cannot connect to database. Details:'.$e->getMessage());
}
//Check that the variables are set
if(isset($_GET['MatchID']) && isset($_GET['TipID']) && isset($_GET['UserID'])){
//Prepare your query
$query = $con->prepare("INSERT INTO betslips (DateTime,MatchID,TipID,UserID)
VALUES ('".date("Y-m-d H:i:s")."', :matchID, :tipID, :userID)");
//Bind your values with the placeholders
$query->bindParam(":matchID", $_GET['MatchID']);
$query->bindParam(":tipID", $_GET['TipID']);
$query->bindParam(":userID", $_GET['UserID']);
//Execute
$query->execute();
die('Success!');
}else{
die('Error: Parameter not set.');
}
?>

jQuery Mobile Login script

I made a basic HTML/PHP login page, and jQuery mobile login page. I want to make them both submit to the same file called checklogin.php, intended to redirect them to their respective main pages if a login is successful. It works successfully for the basic page, but not the jQuery Mobile page. Trying to submit via the mobile page takes me to a page with the phrase "undefined" on it.
So instead, I tried to write some PHP and jQuery script so that if a mobile post is detected, instead of immediately going to the main page, it would return that it was successful, and the login page itself would redirect the user to the main page. Although clicking submit yields a successful "form is sent" alert for testing purposes, a correct login does not make the page change. What should I add?
This is my PHP login checker.
<?php
$host=// Host name
$username=// Mysql username
$password=// Mysql password
$db_name=// Database name
$tbl_name=// Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To prevent MySQL injection (a form of internet hacking)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
// Register $myusername, $mypassword and redirect to the main page"
session_register("myusername");
session_register("mypassword");
//Send them back to the page they were at/
if(!$_POST['mobile'])
{
header("location:main.php");
}
else
{
header('HTTP/1.0 401 Unauthorized', true, 401);
}
}
else
{
echo "Wrong Username or Password";
}
?>
And this is my script back on the login page for redirecting the user.
<script language="javascript">
// Global declarations - assignments made in $(document).ready() below
var hdrMainvar = null;
var contentMainVar = null;
var ftrMainVar = null;
var contentTransitionVar = null;
var stateLabelVar = null;
var whatLabelVar = null;
var stateVar = null;
var whatVar = null;
var form1var = null;
var confirmationVar = null;
var contentDialogVar = null;
var hdrConfirmationVar = null;
var contentConfirmationVar = null;
var ftrConfirmationVar = null;
var inputMapVar = null;
// Constants
var MISSING = "missing";
var EMPTY = "";
var NO_STATE = "ZZ";
function getFormValues() {
data = {};
data['username'] = $("#username").val();
data['password'] = $("#password").val();
return data;
}
function transmitPost() {
$.ajax({
url: 'checklogin.php',
type:"post",
data: getFormValues(),
statusCode: {
401: function() {
alert("Wrong Password");
},
200: function() {
window.location = "m/main.php";
alert('Submitted');}
}
error: function(value) {
alert("error");
}
});
}
$('#submitButton').bind('click', function() {
alert('User clicked on "foo."');
});
</script>
I haven't reviewed all the code yet but when you submit a form to a page not jqm you should add data-ajax="false" to the <form> tag. Saying jqm it should load the page normally and not interpret it as content for the jqm page. That resolved the 'undefined' thing for me...

javascript, php, cookies

the application returns a value "1" in the database instead of the mac address...
I'm able to document.write the output of the mac address, but not able to have it store in the database.
Is the program using the previous cookie? (but Ive deleted all the cookies from the pc)
but if i change the variable mac to string data, it keep refresh my webpage. Why is that so... (var mac="test data";)
Please help!
create_users.php
<script language="JavaScript">
function getMacAddress(){
document.macaddressapplet.setSep( "-" );
return (document.macaddressapplet.getMacAddress());
}
function setCookie(c_name,value) {
document.cookie = c_name + "=" +escape(value);
}
//var mac="test data";
var mac = getMacAddress();
setCookie('cookie_name',mac);
window.location = "checkAvailability.php";
</script>
<script type="text/javascript">
document.write(getMacAddress());
</script>
checkAvailiability.php
$dbhost = 'localhost';
$dbuser = 'root';
$dbname = 'registration';
mysql_connect($dbhost, $dbuser) or die("Could not connect database");
mysql_select_db($dbname);
$javascript_cookie_value = isset($_COOKIE["cookie_name"]) ? $_COOKIE["cookie_name"] : 1;
mysql_query("INSERT INTO test (mac) VALUES ('$javascript_cookie_value')");
Why not:
window.location = "checkAvailability.php?mac=" + mac;
and eliminate cookie problems?
I presume you've checked that the applet is behaving as you expect?
C.
Assuming that code appears in checkAvailability.php, then it keeps refreshing because you have window.location = "checkAvailability.php"; with no logic to stop it running — so every time it loads the page, it gets redirected to that URI.

AJAX live email validation (PHP)

When a user creates an account on my website, I want the input username to be checked against all the current usernames in my database(MySQL) and confirmed if it is available.
Does anyone know any good libraries I could use, or a plug-in for jQuery perhaps?
Exactly what you want is given in example form here. it uses jQuery as the JavaScript library
And this is untested code that is the server-side
<?php
// check_username_available.php?name=(name they supplied)
// this stuff is normally in config.inc.php
$username = "..."; // Mysql username
$password = "..."; // Mysql password
$db_name = "..."; // Database name
// get name supplied from querystring
$name = $_GET('name');
// Connect to server and select database.
//
mysql_connect("localhost", $username, $password) or die("cannot connect to db");
mysql_select_db($db_name) or die("cannot select $db_name DB");
$query = "SELECT COUNT(*) FROM 'users' WHERE user_name = '$name'";
$result = mysql_query($query) or die("cannot count rows: " . mysql_error());
header("Content-Type: text/plain");
echo ( 0 < mysql_result($result, 0) ? "false" : "true" );
Create a PHP file that takes the username as an argument. Then pass it through a $.get method in jquery. This then returns a variable (in my case called data) That variable will contain anything the PHP file printed.
$.get("ajax_available.php?u="+username, function(data){
if(data == "true")
{
// username avaiable
$("#usernameAlert").html("<img src='images/icons/accept.png'
title='Laust' /> Username available");
}
else
{
// username not avaiable
}
});
In this example my php file returns the string "true" but thats just a quick example.

Categories