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();
}
Related
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);
?>
Dears
I called a javascript function on onload body
<body onload="loadLeads()">
This function loads a leads information from database and display it in a table.
The problem is when the user press on delete button to delete a lead from the table. the function runs correctly and delete the lead from the database. BUT although the deletelead function relaoad the page which calls loadLeads() on load the page which should display the new leads without the deleted one. BUT the deleted one display again! although it deleted from the database!!
how can I run it correctly??
I should delete the cache of the browser each time to force the code runs correctly!!
how can I do it please?
this is the javascript code for delete
function deleteLead(id)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
location.reload();
}
}
xmlhttp.open("GET", "deletelead.php?id="+id, true);
xmlhttp.send();
}
This is the script calling in the HTML
<script src="https://example.net/js/loadLeads.js?version=' + Math.floor(Math.random() * 100) + '"\><\/script>'"></script>
This is the loadleads function javascript
function loadLeads()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
LeadsInfo = JSON.parse(this.responseText);
LeadsInfoCount = LeadsInfo.length;
DrawLeadsTable();
}
}
xmlhttp.open("GET", "LoadLeads.php", true);
xmlhttp.send();
}
This is the LoadLeads.php
<?php
require "conn.php";
$SelectSQL = "SELECT * FROM leads";
$result = $conn->query($SelectSQL);
$ECount = $result->num_rows;
if ($ECount != 0 )
{
$FinalArr = array();
$count =0;
while($row1 = $result->fetch_assoc())
{
$id = $row1["id"];
$name = $row1["name"];
$email = $row1["email"];
$mob = $row1["mob"];
$country = $row1["country"];
$comefrom = $row1["comefrom"];
$time = $row1["time"];
$qulified = $row1["qulified"];
$landingpage = $row1["landingpage"];
$myArr = array($id,$name,$email, $mob,$country,$comefrom,$time,$qulified,$landingpage);
$FinalArr[$count] = array();
$FinalArr[$count] = $myArr;
$count++;
$UserData = json_encode($FinalArr,JSON_UNESCAPED_UNICODE);
}
}
mysqli_close($conn);
echo $UserData;
?>
Add this before the xmlhttp.send();
xmlhttp.setRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");
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>
I am sending some information to a php file that runs a query but I want to also retrieve some information from that php file at the same time. The php file executes fine but I can't get the json_encoded object.
Javascript function that sends a string and a number to a php file:
function open_close(){
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status="+status+"&TicketNum="+ticketNum;
var http3 = createAjaxRequestObject();
if (http3.readyState == 4) {
if (http3.status == 200){
alert("Ticket Updated!"); //This never gets hit
getUpdatedTicket(JSON.parse(http3.responseText));
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
PHP File that takes the string and number and updates a table
<?php
include("config.php");
session_start();
$status = $_POST["Status"];
$num = $_POST["TicketNum"];
$newStatus = " ";
if(strcmp($status, "Open") == 0){
$newStatus = "Closed";
}
elseif(strcmp($status, "Closed") == 0){
$newStatus = "Open";
}
$sql = "UPDATE tickets SET Status = \"$newStatus\" where TicketNum = $num ";
$r = $conn ->query($sql) or trigger_error($conn->error."[$sql]");
$sql = "SELECT * FROM tickets where TicketNum = $num";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
?>
How can I retrieve the json_encoded object in the same javascript function?
You'd need a readyState listener to know when the request is done, and then get the data from the responseText
function open_close() {
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status=" + status + "&TicketNum=" + ticketNum;
var http3 = createAjaxRequestObject();
http3.onreadystatechange = function () {
if (http3.readyState == 4) {
if (http3.status == 200) {
console.log(http3.responseText); // <- it's there
}
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
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);
}
}