I have this javascript file that is calling a php file to return a JSON string. Chrome dev tools is throwing the error at line 10 in the javascript code. I know the error relates to a missing bracket but for the life of my and 3 other people who have looked at it the syntax is correct.
var request = new XMLHttpRequest();
var listings = [];
var json;
var url = "getListing.php";
request.open("GET", url, true);
request.send();
request.onreadystatechange = function(e)
{
if(request.readyState == 4){
json = JSON.parse(request.responseText);
for(var x = 0; x < json.length; x++){
var list = new listingInfo();
list.category = json[x].category;
list.date = json[x].dateListed;
list.description = json[x].description;
list.id = json[x].listingID;
list.title = json[x].title;
list.userID = json[x].userID;
listings.push(list);
}
}
console.log(listings);
}
here is the php file
<?php
session_start();
$con = mysql_connect("localhost", "listAdmin", "hermes");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("GregsList", $con)
or die("Unable to select database:" . mysql_error());
$result = mysql_query("SELECT * FROM Listings WHERE userID = '$_SESSION[userID]' ORDER BY dateListed DESC");
#converts to json
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
#If you want to see if correct json is printing use ---> print json_encode($rows);
return json_encode($rows);
?>
request.readyState == 4 is not enough you should add request.status== 200
In your php script replace return json_encode($rows); with print json_encode($rows);
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'm unable to retrieve the q parameter sent from the PHP.
When I run my code, null values get inserted in my database.
Here are the concerning parts of my code:
My JavaScript function:
function load_now(str){
//alert(str);
var id = str.split("+")[0];
var r = confirm("Start load process for scooter " + str + "?");
if (r == true) {
var xmlhttp = new XMLHttpRequest();
//console.log(str);
xmlhttp.open("GET", "load_scooter_action.php?q=" + str, true);
xmlhttp.send();
}
}
and my load_scooter_action.php file:
<?php
require "checkUserModel.php";
require "databaseController.php";
$databaseController = new DatabaseController();
$databaseController->startConnexionToDatabase();
$conn = $databaseController->getConn();
$dateObject = new DateTime();
$startTime = $dateObject->format('Y-m-d H:i:s');
$user = $_SESSION['user-id'];
// get the q parameter from URL
$q = $_REQUEST["q"];
//forme:(scooter, lat, lng, chg);
$val = explode("+",$q);
$scooter = val[0];
$lat = val[1];
$lng = val[2];
$chg = val[3];
echo "<script type='text/javascript'> console.log(".$q.")</script>";
$sql = "UPDATE `scooters` SET `disponible` = '0' WHERE `scooters`.`numero` = '$scooter';";
if ($conn->query($sql) === TRUE) {
$add = "\nScooter Taken";
} else {
$add = "Error Taking scooter" . $conn->error;
}
$sql = "
INSERT
INTO Reloads(scooter, user, initialLoad, finalLoad, sourceX, sourceY,destinationX, destinationY, startTime,endTime)
VALUES ('$scooter','$user','$chg',null,'$lat','$lng',null ,null, '$startTime', null)";
if ($conn->query($sql) === TRUE) {
//echo "\nNew record created successfully";
//echo '<script>window.location.href = "../php/scooterMapIndex.php";</script>';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Could you help me have a clear understanding of my mistake?
Thanks in advance.
EDIT
str is has the following form 599+50.8037+4.32782+4
Two mistakes:
The first one is a quick fix. Replace val with $val
The second one is that, although str is of the form 599+50.8037+4.32782+4 in the .js file, $q gets retrieved without the + characters in the .php file. Therefore it has to be split appropriately.
Can you show me that what is passed in str or which value is passed in str load_now function. Do you get value when you alert(str)?
If yes then try below function
$.ajax({
type: 'GET',
url: 'follow_user.php?user_id='.urlencode($user_id),
success: function(data) {
alert('done');
}
});
Thanks
I am using AJAX in order to access data from a php file.
I have problem with the format of retrieved data from database, please help.
So, this is my ajax function splice. It retrieves data from find_account.php
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
form_prof.prof_id.value = req.responseText;
form_prof.prof_name.value = req.responseText;
form_prof.prof_username.value = req.responseText;
form_prof.prof_password.value = req.responseText;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
find_account.php
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
echo 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$id = $arr['profs_number'];
$name = $arr['profs_name'];
$username = $arr['profs_username'];
$password = $arr['profs_password'];
}
header("Content-type: text/plain");
echo $id;
echo $name;
echo $username;
echo $password;
?>
and I have 4 input boxes in my HTML from where the req.responseText puts the value
and everytime I search the name in the input field for example:
Search: [ Dorothy Perkins ]
The output goes like [id,name,username,password]:
[20111Dorothy Perkinsdperkins#mail.com123456] [same with 1st field] [same] [same]
Wherein I want it to be like...
[20111] [Dorothy Pekins] [dperkins#mail.com] [123456]
Where [ ] are input fields.
Please help me arrange my format, I am so confused. I am new to this.
You can encode return values in json before sending back.
In PHP
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
$returnValues = 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$returnValues = json_encode($arr);
}
echo $returnValues;
?>
In Javascript
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
req = JSON.parse(reg);
form_prof.prof_id.value = req.id;
form_prof.prof_name.value = req.name;
form_prof.prof_username.value = req.username;
form_prof.prof_password.value = req.password;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
You have to write the data in some format from your PHP code (XML, json, or simply separate the values with a comma), and parse it from your javascript.
For example, in PHP:
echo $id . "," . $name . "," . $username . "," . $password;
And then in the javascript:
values = req.responseText.split(",");
form_prof.prof_id.value = values[0]
form_prof.prof_name.value = values[1];
form_prof.prof_username.value = values[2];
form_prof.prof_password.value = values[3];
Of course you may have to do something more complicated if the values may contain a comma.
You can try this
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query, MYSQLI_STORE_RESULT);
while($arr = $result->fetch_array(MYSQLI_ASSOC)) {
$returnValues = json_encode($arr);
break;
}
echo $returnValues;
Note that column names are used as associative index for $arr
Hope it works.
For my bookshop, I started to built a cashdesk script. This is a very simple form, with an ajax dynamic search. This is a script for a local PC, so the script will not be publish on the web.
When I scan the EAN code, I've my form fill with title, author, editor and price. The book is ready to add in the basket.
Now I'm trying to introduce Json in this script : but I don't understand how to get the values of the mysql query in the script, and put them in the correct fields of my cashdesk form.
I've tested the Mysql query and the Json.
The query
<?php
header('Content-Type: text/html; charset=ISO-8859-1');
include('connexion.php');
$connect_db = connect();
$i = 0;
$tmp = array();
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$tmp[$i] = $row;
}
echo json_encode($tmp);
close();
?>
A json exemple :
[{"product_id":"7097","product_name":"Paix pour tous - Livre audio","product_author":"Wayne W. Dyer","product_editor":"Ada","product_price":"20.28"}]
The ajax script
var xhr = null;
function getXhr()
{
if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
else if(window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
alert("Not Working");
xhr = false;
}
}
function ajaxEAN()
{
getXhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var data = '{"product_id": "product_id", "product_name":"product_name", "product_author":"product_author", "product_editor":"product_editor", "product_price":"product_price"}';
oData = JSON.parse( data);
for( var i in oData){
document.getElementById( i).value = oData[i];
}
}
}
xhr.open("POST",'ajaxrecupaddr.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
EAN = document.getElementById("EAN").value;
xhr.send("EAN="+EAN);
}
Thanks for any help !
As far as understand, you simply can't take a JSON from response. If so, than you simply should do:
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200) {
oData = JSON.parse(xhr.responseText);
for(var i = 0; i < oData.length; i++) {
for( var key in oData[i]){
document.getElementById(key).value = oData[i][key];
}
}
}
There, xhr.responseText will return a string with JSON received from server.
Also, few notes:
Instead of
header('Content-Type: text/html; charset=ISO-8859-1');
you should better use:
header('Content-Type: application/json;');
Also, in line below you are opened to SQL Injections:
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
instead of simply doing WHERE product_EAN = '$_POST[EAN]' you should do, at least, WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "':
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "'");
See more about mysql_real_escape_string. It will correctly escape all potentially dangerous symbols and will save you from errors when you have ' symbol in EAN. Also, read warning shown on a page linked above. You should better change your database extension as MySQL extension is deprecated.