i am a beginner that is doing an app for my school work.
Currently, i am using XAMPP to host my app and phpmyadmin for my database.
The problem i am facing is that the xmlhttp.status is returning 0 instead of 200. I do not have this problem with my previous project where i am using microsoft azure instead of XAMPP.
Here is the code of my script in index.html
var userid;
var password;
function serverURL(){
return "http://localhost/webP/FYP/workshop/platforms/android/assets/www/";
}
function login(){
userid = $("#userid").val();
password = $("#password").val();
if (validate()){
alert("validate pass");
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/login.php";
url += "?userid=" + userid + "&password=" + password;
alert(url);
xmlhttp.onreadystatechange=function() {
alert("xmlhttponready running");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.status);
alert(xmlhttp.readyState);
}
getLoginResult(xmlhttp.responseText);
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
Here is my login.php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
try{
$conn = new mysqli("127.0.0.1", "root", "root", "bencoolen");
$userid = $_GET["userid"];
$password = $_GET['password'];
$query = "SELECT count(*) as found from profiles where userid ='" .
$userid . "' and password = '" . $password . "'";
$result = $conn->query($query);
$count = $result->fetch_array(MYSQLI_NUM);
$json_out = "[" . json_encode(array("result"=>$count[0])) . "]";
echo $json_out;
$conn->close();
}
catch(Exception $e) {
$json_out = "[".json_encode(array("result"=>0))."]";
echo $json_out;
}
The PHP returns result='0'
I personally feel that the problem could lies in
function serverURL(){
return "http://localhost/webP/FYP/workshop/platforms/android/assets/www/";
}
Please advise :(
Some liitle mistakes:
Your saveUrl function returns "http://localhost/webP/FYP/workshop/platforms/android/assets/www/"
Now when you are trying to concat
var url = serverURL() + "/login.php";
The url becomes
"http://localhost/webP/FYP/workshop/platforms/android/assets/www//login.php"
I excpect you want json response. Then why you are adding? "[".json_encode()."]"
json_encode(array("result"=>0))
Outputs:
{"result":0}
and
getLoginResult(xmlhttp.responseText);
You are keeping out of the if block. This is the main reason you are getting 0 response. For this let me explain little bit about xmlhttp
When a ajax request is triggered, it is completed with 4 states
state value = 0 :=> (state = UNSET): the xmlhttp instance is initiated
state value = 1 :=> (state = OPENED): The browser sends the data to the server
state value = 2 :=> (state = HEADERS_RECEIVED): request reached at server
state value = 3 :=> (state = LOADING): server processing the request
state value = 4 :=> (state = DONE): response reached from server to browser
Now comming to the coding part:
// When ever there is a state chgange in
// the xmlhttp object
xmlhttp.onreadystatechange=function() {
alert(xmlhttp.readyState);
// when the response from server is reached (state = 4)
// and the response header http code is 200 (xmlhttp.status == 200)
// do the following
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.status);
alert(xmlhttp.readyState);
getLoginResult(xmlhttp.responseText);
}
}
But as you have kept getLoginResult(xmlhttp.responseText); out of if block, so it get executed when state is zero (means when the request was not sent to server)
Try this js code:
var userid;
var password;
function serverURL() {
return "http://localhost/webP/FYP/workshop/platforms/android/assets/www/";
}
function login(){
userid = $("#userid").val();
password = $("#password").val();
if (validate()){
alert("validate pass");
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "login.php";
url += "?userid=" + userid + "&password=" + password;
alert(url);
xmlhttp.onreadystatechange=function() {
alert("xmlhttponready running");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.status);
alert(xmlhttp.readyState);
getLoginResult(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
And your php code:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
try{
$conn = new mysqli("127.0.0.1", "root", "root", "bencoolen");
$userid = $_GET["userid"];
$password = $_GET['password'];
$query = "SELECT count(*) as found from profiles where userid ='" .
$userid . "' and password = '" . $password . "'";
$result = $conn->query($query);
$count = $result->fetch_array(MYSQLI_NUM);
$json_out = json_encode(array("result"=>$count[0]));
echo $json_out;
$conn->close();
}
catch(Exception $e) {
$json_out = json_encode(array("result"=>0));
echo $json_out;
}
?>
Suggestions
As you are using jquery, try to use, jquery.ajax() instaed of XMLHttpRequest (if you are doing it for learning purpose, then its fine). This will fix your browser compatibility issue.
To avoid sql injection, try to use mysqli::prepare. http://php.net/manual/en/mysqli.prepare.php
For more about the XMLHTTPRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
Related
I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.
I have a js function that calls in an xml request to fetch data from a separate php file. I can get a returned data through echoing it from the separate php file.
Here's my current code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if(this.readyState == 4 && this.status == 200)
{
//On Data Receive
countryHeader.innerHTML = this.responseText;
}
};
xhttp.open("GET", "country.php?c=" + countryName, true);
xhttp.send();
And on my php:
include("conn.php");
$c = htmlentities($_GET["c"]);
$sec_country = mysqli_real_escape_string($con, $c);
//Searches the db
$sql = "SELECT * FROM countries WHERE country_code = '$sec_country' LIMIT 1";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
if($count == 1)
{
//Get Data
$row = mysqli_fetch_assoc($result);
$countryName = $row['country_name'];
$countryPrice = $row['country_price'];
echo $countryName." is worth $".$countryPrice;
}
else
{
//Invalid Code/No Data
echo "No Country Found";
}
If I send in a country code for example like rus, it would return Russia is worth $1B mainly from the echo $countryName." is worth $".$countryPrice;
But what if I want to separately send $countryName and $countryPrice?
For example responseText.a and responseText.b
You can send JSON response from PHP. Here is a reference -> https://www.w3schools.com/js/js_json_php.asp
I am trying to pass data back to the server and then use the reply to update the browser page.
My code for a SELECT input is as follows;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
The script code is as follows;
<script>
function findTeleNo(that){
alert("I am an alert box!" + that);
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TeleNo").value = this.responseText;
}
}
};
xhttp.open("GET", "findTeleNo.php?q=" + that, true);
xhttp.send();
</script>
The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.
And the PHP file is as follows;
<?php
$MatchCaptain = $_REQUEST["q"];
$teleNo = "";
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$teleNo = $db_field['TeleNo'];
break;
}
}
}
echo $teleNo;
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
$ufullName = $first_name." ".$last_name;
return $ufullName;
}
?>
The php file requests the q variable from the url and makes it $MatchCaptain.
This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script.
The field id I am trying to update is;
<p><b>Telephone Number: </b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>
The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that.
Any help as to how I get this working would be grateful.
I have changed my script to
<script>
function findTeleNo(that){
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
// OK
alert('response:'+xhttp.responseText);
document.getElementById("TeleNo").innerHTML = this.responseText;
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
};
</script>
The response shown by alert('response:'+xhttp.responseText); is correct and the line of code
document.getElementById("TeleNo").innerHTML = this.responseText;
does print the response to the web page.
I am trying to update my list of tweets via AJAX. I have ran the script on the page and know that script works, and I have a console.log line in my ajax call so I know that is getting hit as well.
setInterval(function () {sendRequest()}, 5000);
function sendRequest(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log("yay");
}
}
xmlhttp.open("GET","getTweets.php",true);
xmlhttp.send();
}
My AJAX should run every 5 seconds, and the hit the PHP script to return new results that have been stored in the database. My PHP looks like:
$conn = mysqli_connect("localhost", "*", "*", "*");
if (!$conn) {
echo("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM tweets;";
$results = mysqli_query($conn, $query);
while($list = mysqli_fetch_assoc($results)){
echo '<div class="tweet-containter">';
echo '<img class="user-img" alt="user-img" src="images/gb.png">';
echo '<h3 class="tweet-username">#'.$list['username'].'</h3>';
echo '<p class="tweet-body">'.$list['tweetBody'].'</p>';
echo '<p class="tweet-body">Tweeted: '.$list['datePosted'].'Retweet: <i class="fa fa-retweet" id="retweet4" onclick="retweetAJAX()"></i> Like: <i class="fa fa-thumbs-up" id="likes4" onclick="likeAJAX()"></i> Dislike: <i class="fa fa-thumbs-down" id="dislikes4" onclick="dislikeAJAX()"></i></p>';
echo '</div>';
}
This goes for those that do not understand ReadyState codes. You should know the following codes for ReadyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
And Status Code
200: "OK"
404: Page not found
with that said, try doing this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
} else if(xmlhttp.status == 400) {
alert('There was an error 400')
} else {
alert('something else other than 200')
}
}
}
ryandonohue,
PHP is a Hyper-Text Processor. PHP runs on your server & the results are generated before the page is loaded. You should not be using PHP to output results like HTML elements, it is much more appreciated if you use JavaScript to manipulate the Document Object Model (DOM).
Though, for your intermediate purposes you might not notice an immediate difference.
For PHP5 you should look into the usage of PHP-PDO http://php.net/manual/en/class.pdo.php to prevent SQL injection.
Modification:
function getall($table, $values, $conditions = null, $limit = null, $ascdesc = null){
$values_str = "";
foreach($values as $key => $value){
$values_str .= $value . ", ";
}
$cond_str = "";
$hascond = false;
if($conditions != null){
$hascond = true;
foreach($conditions as $key => $value){
$cond_str .= $key . "='" . $value . "' AND ";
}
$cond_str = rtrim($cond_str, " AND ");
}
$values_str = rtrim($values_str, ", ");
$cond_str = " WHERE (" . $cond_str . ")";
$orderby = "";
$hasorder = false;
if($ascdesc != null){
$hasorder = true;
foreach($ascdesc as $key => $value){
$orderby = " ORDER BY " . $value . " " . $key;
break;
}
}
$sql = "SELECT " . $values_str . " FROM " . $table . " " . (($hascond)? $cond_str: "") . (($hasorder)? $orderby: "") . (($limit)? " LIMIT " . $limit: "");
//echo $sql;
$sql_prep = (new PDO('mysql:host=localhost;dbname=' . 'database', 'username', 'Password'))->prepare($sql);
$sql_prep->execute();
return $result = $sql_prep->fetchAll(PDO::FETCH_ASSOC);
}
initialization: ( returns an array so you need to json encode)
getall('table',
Array(
'*'
),
null, 5, null);
AJAX:
function ajax(file,type, params, func){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//xmlhttp.responseText
func(xmlhttp.responseText);
}
}
if(type.toLowerCase() != "post"){
xmlhttp.open(
type, file + "?" + params_to_get(params),
true
);
xmlhttp.send();
}else{
xmlhttp.open(
type, file,
true
);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params_to_get(params));
Since you have an error code of readystate of 4 with a status of 500 i would say the issue is more with the compatibility of MYSQLi or the way your table is set up with your database.
check out this POST for more information about headers:
Ajax call to PHP is returning nothing
This is my JavaScript code:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
for(i = 0; i < 5; i++)
{
var prikey = (i+1);
//document.getElementById("demo").innerHTML = prikey;
myFunction(xmlhttp.responseText);
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response)
{
//some code here
}
Now, I want to transfer prikey from this JavaScript file to the server-side PHP file.
The PHP code is
$conn = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($conn,"$db_name")or die("cannot select DB");
$sql="SELECT countries FROM $tbl_name";
$result=mysqli_query($conn,$sql);
I want to integrate the transferred prikey variable such that I will be able to query the database in the following way:
$sql="SELECT countries FROM $tbl_name where id=$prikey";
where $prikey is where I store the value gotten from the JavaScript file.
How do I accomplish this?
You need to add the prikey as a parameter to the GET url.
Javascript:
// The request is inside of a function so that each
// xmlhttp is a different object
function sendRequest(prikey) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState === 4)
{
if (xmlhttp.status === 200 || xmlhttp.status === 304)
{
myFunction(xmlhttp.responseText);
}
}
};
xmlhttp.open("GET", url + '?prikey=' + prikey, true);
xmlhttp.send();
}
// Send the requests
for(i = 0; i < 5; i++)
{
// Pass it the prikey
sendRequest(i + 1);
}
function myFunction(response)
{
// Do stuff
}
And in your PHP code, get it through the $_GET array:
// Get the variable sent through the Ajax request
$prikey = $_GET['prikey'];
$conn = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($conn,"$db_name")or die("cannot select DB");
$sql = "SELECT countries FROM $tbl_name WHERE id = $prikey";
$result = mysqli_query($conn,$sql);
// echo the result so that your JavaScript code gets the response
// Again, ignore if you've already done this
echo $result;