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
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'm newbie in php and JavaScript, and I want to print all rows in my table
I use this code, it works but no output have come from it, and no errors occurs
function show(){//function get data and send it to Ajax, and I can make 1 function get 3 parameters
// var formData = new FormData();
// formData.append('result', $(("#a").val()));//php elem , html element
// formData.append('contactUsEmail', $("#contactUsEmail").val());
// formData.append('contactUsMessage', $("#contactUsMessage").val());
if(false){
swal("Attention !", "Please fill in all fields", "error");
}else {
//Ajax
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var text =this.responseText; // 0 unvalid , 1 true
// document.getElementById("a").innerHTML = this.responseText;
}
}
ajax.open("GET", "one.php", true);
ajax.send(formData);
}
}
php code here :
<?php
function OpenCon()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "chat";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
return $conn;
}
function show(){
$sql = "SELECT id FROM masseges";
$result = OpenCon()->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: ". $row["id"]."bb";
}
} else {
echo "0 results";
}
OpenCon()->close();
}
No errors in page, but a blank page. How can I fix it ?
You are not actually returning any html tags back to your website.
You should be able to see the result from the php echo in the network tab of your development console.
If you want to fill a table, I suggest you create the table structure on your website and add the data from php as a new table row.
HTML:
<table>
<tr>
<th>id</th>
</tr>
</table>
PHP:
echo "<tr><td>id: ". $row['id']."bb</td></tr>";
Another word of advide:
Have a look at jquery! Gonna save you a a lot of time!
I have been where you are half a year ago :-)
I've had a fit for the past few days trying to figure out how to communicate across domains with ajax requests.
I have this file...
<?php
header('Access-Control-Allow-Origin: *');
?>
<script>
function send(user){
var hr = new XMLHttpRequest();
var url = "http://forumchest.com/kb_exchange.php";
var data = "user="+user;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onload = function(){
if(hr.readyState == 4 && hr.status == 200){
var text = hr.responseText;
alert(text);
} else {
alert(hr.readyState + " " + hr.status);
}
}
hr.send(data);
}
</script>
<?php
include_once("conn.php");
$fetch_sites = mysqli_query($conn, "SELECT * FROM sites");
while($row = mysqli_fetch_array($fetch_sites)){
$site_id = $row['id'];
$site_address = $row['address'];
$fetch_subs = mysqli_query($conn, "SELECT * FROM subscriptions WHERE site='$site_id'");
while($row1 = mysqli_fetch_array($fetch_subs)){
$sub_user = $row1['user'];
$sub_username = $row1['username'];
echo "<script>send('$sub_username');</script>";
}
}
mysqli_close($conn);
?>
It is attempting to send an ajax request to the following file hosted on a different server with a different domain name.
<?php
header("Content-Control-Allow-Origin: *");
?>
<script>
function respond(user, posts){
var data = "user="+user+"&posts="+posts;
var hr = new XMLHttpRequest();
hr.open("POST", "http://xenforotest.esy.es/responder.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(data);
}
</script>
<?php
$conn = mysqli_connect("host", "user", "password", "db");
if(!$conn){
echo "this1";
} else {
echo "this2";
}
$user = $_POST['user'];
$fetch_user = "SELECT message_count FROM xf_user WHERE username='$user'";
$query_user = mysqli_query($conn, $fetch_user);
$row = mysqli_fetch_array($query_user);
$message_count = $row['message_count'];
echo "<script>respond('$user', '$message_count');</script>";
mysqli_close($conn);
?>
I am getting two responses from the first file saying "2 200" and "3 200". So I'm getting a readyState of 2 and a status of 200.
Why isn't this working?
It should be
header("Access-Control-Allow-Origin: *");
and not
header("Content-Control-Allow-Origin: *");
Cross domain is not relevant there. Your problem is that you send data as a url string.. POST data should be in formdata object of javascript
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.
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);