Cannot get data as JSON from a PHP file on the server - javascript

I have a database on the server, containing a table customers, and column names in that. I want to make a request to the server where I ask for the first 2 records in the customers table. Once I run the program, the browsers cannot display the records, it shows undefined. Look the image below.
.php:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("127.0.0.1", "abc", "def", "mydatabase");
$result = $conn->query("SELECT names FROM " . $obj->table . " LIMIT " . $obj->limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
.html:
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":2 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
for (x in myObj) {
txt += myObj[x].name + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("GET", "demo_file.php?x=" + dbParam, true);
xmlhttp.send();
</script>

You must be use names instead of name of object in loop in js because in your select query you have names columns and results have names property.
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":"customers", "limit":2 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
console.log(myObj)
for (x in myObj) {
txt += myObj[x].names + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("GET", "demo_file.php?x=" + dbParam, true);
xmlhttp.send();
</script>

Related

Function output empty by succesfull AJAX response

There's an issue with my function in the AJAX.
I create an AJAX call to a PHP file that returns JSON.
For loop this JSON I created a fucntion that I run if the AJAX is successfull.
But in practice the data is empty.
<script>
document.getElementById("getproducts").addEventListener("submit", sendAjax);
function sendAjax(event) {
var q = document.getElementById('search').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
display(this.responseText);
}
}
xhttp.open("POST", "results.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('search='+q);
event.preventDefault();
}
function display( jsdata ){
for ( var key in jsdata ){
var htmltabel = '';
var datanode = document.createElement("div");
htmltabel += '<div class="id">' + jsdata[key]['id'] + '</div>';
content = htmltabel;
datanode.innerHTML = content;
document.getElementById("resultt").appendChild(datanode);
}
}
</script>
If I code the JSON hardcode in the function like this than everything is okay.
var hardcoded = {"1736":{"id":"1736","post_title":"Test explode","_sku":"12345","_stock":null,"_price":"9.50"}}
//PART OF THE CODE
if (this.readyState == 4 && this.status == 200) {
display(hardcoded);
}
How can I fix this that the function use the responded JSON?
here is a corrected script, You should just convert the responseData from string to Json Object!
document.getElementById("getproducts").addEventListener("submit", sendAjax);
function sendAjax(event) {
var q = document.getElementById('search').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
display( JSON.parse(this.responseText) ); // You should convert the response from string to a valid JSON
}
}
xhttp.open("POST", "results.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('search='+q);
event.preventDefault();
}
function display( jsdata ){
for ( var key in jsdata ){
var htmltabel = '';
var datanode = document.createElement("div");
htmltabel += '<div class="id">' + jsdata[key]['id'] + '</div>';
content = htmltabel;
datanode.innerHTML = content;
document.getElementById("resultt").appendChild(datanode);
}
}

How do I send a value from Javascript to PHP that will not be changed?

I have function that is running multiple times and executing a PHP file. I do, however, want to make sure the functions does not interfere with each other.
for(int i = 0; i<5; i++){
functionName(i)
}
function functionName(number){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
var PageToSendTo = "phpFile.php?";
var MyVariable = number;
var VariablePlaceholder = "name=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xhttp.open("GET", UrlToSend, true);
xhttp.send();
}
This is how my code looks so far, how do I change it so that the next iteration of the function does not effect the previous one?
phpFile.php
<?php
require '../notWebsite/dbh.php';
session_start();
$variable = $_GET['name'];
$sqlInsertClass = "INSERT INTO class (className) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sqlInsertClass)) {
header("Location: ../Website.php?error=InsertError");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $variable);
mysqli_stmt_execute($stmt);
exit();
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>

Passing elements of array from javascript to php

I'm trying to pass to php from javascript elements of an array, for processing, like this:
for(var i=0;i<points.length;++i){
var xmlhttp = new XMLHttpRequest();
var distancesObject = null;
lat = points[i][LAT];
lng = points[i][LNG];
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
if(xmlhttp.response!=null){
distancesObject = JSON.parse(xmlhttp.response);
}
}
};
xmlhttp.open("GET", "Distances.php?lat=" + lat + "&lng=" + lng, true);
xmlhttp.send();
}
It should iterate through every elements of the array and return the object, if it exists in the database, yet it returns null, even though i know for sure the first values are stored in the database.
It only works if I pass values like points[0], points[1].
The php code is:
<?php
$latitude = $_GET['lat']; //"47.158857";
$longitude = $_GET['lng']; // "27.601249"
$query = "SELECT pharmacyDistance, schoolDistance, restaurantDistance, busStationDistance FROM distances WHERE lat='$latitude' and lng='$longitude'";
$result = mysqli_query($dbc,$query);
$count = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$json_array = json_encode($row);
if($json_array!=null){
echo $json_array;
}
mysqli_close($dbc);
?>
Is there something I'm doing wrong?
Please don't do that way. Really. Add all array items into your url and perform just one request, where you will query for everything you need and return a list. Handle the list in the response. Something like(from top of my head):
var urlParams = [];
points.forEach(function(point) {
urlParams.push("lat[]=" + point.LAT + "&lng[]=" + point.LNG);
});
var xmlhttp = new XMLHttpRequest();
var distancesObject = null;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
if(xmlhttp.response!=null){
distancesObject = JSON.parse(xmlhttp.response);
}
}
};
xmlhttp.open("GET", "Distances.php?" + urlParams.join("&"), true);
xmlhttp.send();
In PHP:
$whereClause = "";
for ($i = 0; $i < count($_GET['lat']); $i++) {
$whereClause.= "(lat='" . $_GET['lat'][$i] . "' and lng='" . $_GET['lng'][$i]. "') and ";
}
$query = "SELECT pharmacyDistance, schoolDistance, restaurantDistance, busStationDistance FROM distances WHERE " . substr($whereClause, 0, (strlen($whereClause) - 4)); // Substr to remove last ' and' from where clause
$result = mysqli_query($dbc,$query);
$count = mysqli_num_rows($result);
$distances = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$distances[] = $row;
}
$json_array = json_encode($distances);
if($json_array!=null){
echo $json_array;
}
mysqli_close($dbc);
Then you'll have a list of your distances as json and just one hit in your database. Also, is not healthy for your app to call an ajax in a for loop, it will open various parallel async requests, a mess.
This is how the query will looks like approximately:
SELECT ... FROM ... WHERE (lat='1' and lng='1') and (lat='2' and lng='2') and ...
I didn't tested those codes and I don't play with PHP for a while, so I hope the code is ok, forgive any typos or syntax errors.
I believe your problem lies with these 2 lines:
lat = points[i][LAT];
lng = points[i][LNG];
Firstly, you have defined them into the global scope. They should be prefixed with the var keyword unless you've already defined these variables above.
Second, [LAT] is trying to use an (I assume unitiated) variable named LAT. The correct syntax for using a string key name is either points[i]['LAT'] or points[i].LAT.
So, updating your code to
var xmlhttp = new XMLHttpRequest();
var distancesObject = null;
var lat = points[i].LAT;
var lng = points[i].LNG;
Should hopefully solve your problem.
you're overwriting the object which is handling the connection in the for loop, probably faster than the response can return.
try:
var xmlhttp = [];
for(var i=0;i<points.length;++i){
xmlhttp[i] = new XMLHttpRequest();
var distancesObject = null;
lat = points[i][LAT];
lng = points[i][LNG];
xmlhttp[i].onreadystatechange = function() {
if (xmlhttp[i].readyState == 4 && xmlhttp[i].status == 200){
if(xmlhttp[i].response!=null){
distancesObject = JSON.parse(xmlhttp.response);
}
}
};
xmlhttp[i].open("GET", "Distances.php?lat=" + lat + "&lng=" + lng, true);
xmlhttp[i].send();
}

How to send String from text area to php via js

I am trying to get the string value from a textarea in js and send it to my php file. but when i check the value of the variable that receives the string it returns "". however every other value is received.
js file
$(document).ready(function () {
$("#newTestApprove").on("click", function(e) {
$testimonial = escape(document.getElementById("testimonialArea").value);
$client = document.getElementById("client").value;
$event = document.getElementById("event").value;
$status = "submitted";
if ($testimonial.length === 0)
{
alert("Testimonial Field is left empty");
}else
if ($client.length === 0)
{
alert("Client Field is left empty");
}
else if ($event.length === 0)
{
alert("Event Field is left empty");
} else{
obj = {"status":$status, "client":$client, "event":$event, "testimonial":$testimonial};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
validity = this.responseText;
if (validity === "Successful"){
$('#newTestimonialModal .modal-body').html("Your Testimonial has been Submitted");
$("#newTestApprove").remove();
}
}
};
}
xmlhttp.open("POST", "../php/postTestimonial.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xmlhttp.send("x=" + dbParam);
});
});
php file
<?php
$obj = json_decode($_POST["x"], false);
$testimonial = $obj->testimonial;
echo $testimonial;
?>
When i echo $testimonial it returns ""
please assign variable in javascript as
var testimonial=document.getElementById("testimonialArea").value;
instead of
`$testimonial=escape(document.getElementById("testimonialArea").value);
please try below `eg:
<html>
<body>
Address:<br>
<textarea id="myTextarea"></textarea>
<p>Click the button to alert the contents of the text area.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var testimonial = document.getElementById("myTextarea").value;
document.getElementById("demo").innerHTML = testimonial;
var obj = {"testimonial":testimonial};
var dbParam = JSON.stringify(obj);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "ajax_info.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname="+dbParam);
}
</script>
</body>
</html>
Php file ->ajax_info.php
<?php
$obj = json_decode($_POST["fname"], false);
$testimonial = $obj->testimonial;
echo $testimonial;
?>

How to i get a specific value from a json encoded array?

Here is my JavaScript and my PHP for a dynamic ajax search. I am trying to get data from the database and display it in my DOM as a string.
javascript
var searchBox = document.getElementById("searchBox");
var searchButton = document.getElementById("searchButton");
var search = getXmlHttpRequestObject();
searchBox.addEventListener("keyup", ajaxSearch);
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support our dynamic search");
}
}
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
function displaySuggestions(){
var ss = document.getElementById("searchSuggestion");
ss.innerHTML = '';
string = search.responseText;
ss.innerHTML = string;
}
function delay(functionName){
setTimeout(functionName, 100);
}
function setSearch(x){
document.getElementById("searchBox").value = x;
document.getElementById("searchSuggestion").innerHTML = "";
}
searchBox.addEventListener('click', ajaxSearch);
window.addEventListener('click', function(){
document.getElementById('searchSuggestion').innerHTML = '';
});
php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Products";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$searchValue = $_GET['search'];
if(isset($searchValue) && $searchValue != ''){
$search = addslashes($searchValue);
$statement = $conn->prepare("SELECT Name FROM Product WHERE Name LIKE('%" . $search . "%') ORDER BY
CASE WHEN Name like '" . $search . " %' THEN 0
WHEN Name like '" . $search . "%' THEN 1
WHEN Name like '% " . $search . "%' THEN 2
ELSE 3
END, Name");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($result);
echo $json;
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
What i want to know i how to get specific values from my response.
[{"Name":"iMac"},{"Name":"iPad 2"},{"Name":"iPhone 5"},{"Name":"iPhone 6"},{"Name":"iPod Touch"},{"Name":"iWatch"}]
For my search to work effectively i need it to display just the string of the product name and not the whole object.
Using a delay rather than the ajax callback is just shockingly prone to failure. Suppose your ajax call takes more than 100ms? It can totally happen. Similarly, why wait 100ms if your server is nice and fast and it finishes in 25?
Ditch the global search object, and change this:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
to
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject();
if (search) {
search.onreadystatechange = function() {
if (search.readyState == 4 && search.status == 200) {
displaySuggestions(JSON.parse(search.responseText));
}
};
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}
Then displaySuggestions receives an array:
function displaySuggestions(results) {
// Use standard array techniques on `results`, e.g., `results[0]` is the first,
// maybe loop while `index < results.length`, maybe use `results.forEach(...)`...
}
Or taking it further, let's add a level of convenience there:
var failed = false;
function getXmlHttpRequestObject(done, failed){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
if (!failed) {
alert("Your browser does not support our dynamic search");
failed = true;
}
return null;
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 {
if (done) {
done(xhr);
}
} else {
if (failed) {
failed(xhr);
}
}
}
};
return xhr;
}
Then:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject(function(xhr) {
displaySuggestions(JSON.parse(xhr.responseText));
});
if (search) {
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}

Categories