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.
Related
I am creating a website where a user logs in, enters information that is submitted to a database, and then can call information from the database that will be inserted into an html text element. I have separate html files for each website page, and multiple php files. They are all contained and linked properly on the same server, under the same FTP account. EDIT: THIS WAS MY PROBLEM. I HAD SEPARATE PHP AND HTML FILES. ONCE I COMBINED THEM, I NO LONGER NEEDED THE JAVASCRIPT AND EVERYTHING WORKED FINE. My code has been checked by multiple sources, and I can have the user correctly input information into the database. When it comes to retrieving the information to be displayed on client-side, however, the php will not change the html via javascript.
I am currently using 000webhost.com, but I tried plugging the files into dreamweaver and the files still aren't communicating properly. I'm wondering whether this is a software limitation (aka something is going wrong with 000webhost.com) or if there is a key piece of info I am missing, such as a command that will link the files together.
Here is the example php and html for one of the retrieve information functions:
$servername = "localhost";
$username = "-";
$password = "-";
$database = "-";
$link = mysqli_connect($servername, $username, $password, $database);
if (!$link) {
die(mysqli_error());
}
$sql = "SELECT UserClassName FROM UserInfo1 WHERE UserEmail = '". mysqli_real_escape_string($link, $_SESSION['useremail']) . "'";
if (!$sql) {
die(mysqli_error());
}
$result = mysqli_query($link, $sql);
if (!$result) {
die(mysqli_error());
}
?>
<script>
function getclassname() {
return document.getElementById("UserClassName").innerHTML = "<?php echo
$result ?>";
}
</script>
<html>
<body onload="getclassname(); getcurrentlevel();">
<h1 class="text-center" id="UserClassName" name="UserClassName"><b>Welcome Enviroquest Research Team!</b></h1>
</body>
</html>
I think the only problem is that you put the javascript code outside the html. It should be placed before the closing body tag.
This is what your html should look like :
<?php // your php code here ?>
<html>
<body onload="getclassname(); getcurrentlevel();">
<h1 class="text-center" id="UserClassName" name="UserClassName"><b>Welcome Enviroquest Research Team!</b></h1>
<script>
function getclassname() {
document.getElementById("UserClassName").innerHTML = "<?php echo $result; ?>";
}
function getcurrentlevel() {
// this function should be remove if not used
}
</script>
</body>
</html>
Although i have followed the sample code from http://api.jquery.com/jQuery.post/ and of course Stackoverflow i couldnt find a solution to my problem.
I have a toggle image in html which everytime a user clicks on it,changes the image and update the column in the DB.Here is the code:
HTML
<input type="image" src="smileys/heart.gif" class="play" onclick="toggle(this,'<?php echo $ida;?>')"/>
AJAX
function toggle(el,al){
if(el.className=="play")
{
el.src='smileys/lol.gif';
el.className="pause";
$.post("update.php", { "hr": 1, "ida": al } );
}
else if(el.className=="pause")
{
el.src='smileys/heart.gif';
el.className="play";
$.post("update.php", { "hr": 0, "ida": al } );
}
console.log(al);
return false;
}
update.php
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$database = "db";
$heart=$_GET["hr"];
$ida=$_GET["ida"];
$con = mysql_connect($host,$user,$pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
mysql_query("UPDATE tablename SET heart='$heart' WHERE id='$ida'");
?>
The toggle function works well but the DB is not updated when a user clicks and the image.
I believe it has to do with the $.post function,not sending correctly the data to the php.
BTW if i do
http://domain.com/update.php?hr=1&ida=127
it works.
NOTE: I am using mysql and not PDO only for this example.
...and yes my code is messy and ugly,still learning.
Any help?
Thanks
Well, it's a _POST request and not an _GET, so, to capture its values you need to use $_POST instead $_GET.
Also, as i noticed, there's and _GET link, so you need to change your $.post with $.get.
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 to: Query Database through Javascript / PHP
This question is related to my above question. I fixed the PHP script to the one as mentioned in one of my answers; I attempted to use $.getJSON to no avail. So I stuck with my original method of getting a response from the server:
function getDatabaseRows()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "myDomain.com/subDirectory/getRowCounts.php", true);
xmlHttp.send(null);
}
When the alert runs, it acts as if it is a text file, and gets the entire contents of my PHP script. It doesn't run the script, it merely grabs a text-copy of it off of the server. My script (which is linked in the earlier question) is:
$rowCounts = array();
$dbhost = 'host';
$dbuser = 'host';
$dbpass = 'host';
$dbase = 'host';
$fields = array(
'MaxTID' => array('tab' => 'TransData', 'col' => 'TID'),
'MaxSID' => array('tab' => 'FullData', 'col' => 'SID'),
'MaxFID' => array('tab' => 'SalamanderData', 'col' => 'FID'),
'MaxOID' => array('tab' => 'OthersData', 'col' => 'OID')
);
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db($dbase, $con) or die(mysql_error());
foreach ($fields as $id => $info) {
$sql = "SELECT MAX({$info['col']}) FROM {$info['tab']}";
$result = mysql_query($sql, $con);
if (!$result) die('Could not query:' . mysql_error());
$rowCounts[$id] = mysql_result($result, 0);
}
echo json_encode($rowCounts);
mysql_close($con);
Any clue as to why my AJAX script returns a text-copy of the PHP script on the server; and not the JSON results I am looking for?
EDIT:
Pointing my browser to the PHP script returns:
{"MaxTID":"1","MaxFID":null,"MaxSID":"3","MaxOID":"1"}
$.getJSON is jQuery, so you would need to include it in your page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$.getJSON('http://myDomain.com/subDirectory/getRowCounts.php', function(response) {
console.log(response);
});
</script>
Javascript is going to pull down whatever the http server gives it. So if the http server is not configured correctly to process your server-side script I.E. php, then you're going to get the contents of the file instead of the processed html output from running the php script. Contact your server admin to get it fixed, and verify that you are using a .php extension on your file and not .txt.
Found the solution.
The problem arrises from the fact that I was working on a network share drive ....which also happened to be living on the web server.
So whenever I went to test the script, it would fetch my file like so:
file:////mySubDomain.myDomain.com/getRowCounts.php ... Which obviously can't work, considering it isn't being served by the server.
Fixed by changing file://// to http://
Basically I have a php script located on a sever that generates a JSON file listing places from a mysql database. Using jQuery Mobile I am developing an application to display these places. My code works in Chrome & Safari, however when I port it over to Phonegap it doesn't work. I have searched all over the internet but can't find an answer :(.
The php file for generating JSON (json.php):
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "xxx";
$password = "xxx";
$database = "xxx";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM places ORDER BY name ASC";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
My Javascript file located within my app (Loads JSON and displays it):
$('#places').bind('pageinit', function(event) {
getPlaces();
});
function getPlaces() {
var output = $('#placeList');
$.ajax({
url: 'http://www.mysite.com/json.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<li><a href="">'+item.name+'<span class="ui-li-count">'
+ item.checkins+'</span></a></li>';
output.append(place);
});
$('#placeList').listview('refresh');
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
The HTML looks like this:
<div data-role="content">
<h3>Places</h3>
<ul data-role="listview" id="placeList" data-inset="true">
</ul>
</div><!-- /content -->
This code works in Chrome & Safari, however when run in the xCode simulator with Phonegap it doesn't load the JSON.
Any help would be much appreciated :)
I don't think the problem has anything to do with the server code (PHP), unless you are producing invalid JSON. The question should be tagged with JavaScript rather than PHP. Anyway, there is an excellent article describing a very similar type of application. It even includes sample code. Have a look:
Sample Application using jQuery Mobile and PhoneGap
Dude,
That's server side script it won't run unless its hosted on a server with those languages implemented. I'm running into a similar problemn One suggestion was to implmented the AJAX to fetch the data from a php site an return the data. I'm look'n to just forward the whole page over too a Safari webview window (which you have to set in phonegap permissions). Problem there is I get all the Safari chrome on the top and bottom trying to figure out how to trim that so I don't have to recode with AJAX to pull PHP data server side.