I see a lot of these questions comming by. But I seem to do something wrong. So forgive me for asking (I am a bit of a n00b). In my php I echo the the folowing echo json_encode(['msg'=>$NewTotal]);.
I use a HTML5 worker to post data to a php on my server and I need the echo to be posted back to the main script so I can repost it to set it as new value for the variable Totalaccounts for the loop.
Worker Script:
onmessage = function(dbs) {
console.log(dbs.data);
var Totalaccounts = dbs.data;
var DBScriptLoop = setInterval(
(function () {
DBStartWorking();
//postMessage(Totalaccounts);
}), 123000);
function DBStartWorking(){
for (var dw = 0; dw < Totalaccounts; dw++) {
setTimeout(function() {
httpRequest = new XMLHttpRequest()
var dataresponse = httpRequest.responseText;
var NewCount = dataresponse.msg;
httpRequest.open('POST', 'DostuffV1.php')
httpRequest.send(Totalaccounts)
postMessage(NewCount);
console.log(NewCount);
}, 1200 * dw);
}
} // End script loop
};
Main script:
var DBScriptWorker;
function startDBScriptWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(DBScriptWorker) == "undefined") {
DBScriptWorker = new Worker('DBScriptWorker.js');
var php_va = "<?php echo $AccToRank; ?>";
DBScriptWorker.postMessage(php_va);
}
DBScriptWorker.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
DBScriptWorker.postMessage(event.data);
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
}
}
function stopDBScriptWorker() {
DBScriptWorker.terminate();
DBScriptWorker = undefined;
}
In my network tab I see the response is this: {"msg":29}
My variable is not set, it commes up as undifined. What am I doing wrong? Searching and trying for hours now..
Related
The script makes an ajax call to a PHP file on input change, but the JSON isn't parsing and I don't know why
Here's the Javascript
input.addEventListener("input", (event) => {output.innerHTML = "Cerca " + document.getElementById("tophead-searchbar").value + " su Nevent";
var searchqueryajax = new XMLHttpRequest;
ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
searchqueryajax.addEventListener("load", innerhtmlqueries());
searchqueryajax.open("GET", ajaxquerylink);
searchqueryajax.send();
function innerhtmlqueries() {
queriesarray = JSON.parse(searchqueryajax.responseText);
}
});
The input is document.getElementById("tophead-searchbar") and the output is the Result1, it says the value of the input
Here is the PHP Script:
$query = $_REQUEST["query"];
$queryresults = mysqli_query($name, "SELECT * FROM search_queries WHERE MATCH(ID, QUERY) AGAINST('$query') LIMIT 7");
if ($queryresults->num_rows > 0) {
$autocompleteresults = array();
while($row = mysqli_fetch_array($queryresults)) {
$results["ID"] = $row["ID"];
$results["value"] = $row["QUERY"];
$results["type"] = $row["TIPO"];
array_push($autocompleteresults, $results);
}
}
echo json_encode($autocompleteresults);
There are no PHP errors on the log and i don't see the PHP File on Network Tab of the browser F12 editor
I tried to do some things on Javascript code but i still don't notice the request on Network Tab
Edit: I also have another ajax call like this in the same file and it works
var checkajaxiflogged = new XMLHttpRequest();
checkajaxiflogged.addEventListener("load", checkajaxiflogged_function);
checkajaxiflogged.open("GET", "topbarprofileinformation.php");
checkajaxiflogged.send();
function checkajaxiflogged_function() {
topheadjsonresponse = JSON.parse(checkajaxiflogged.responseText);
document.getElementById("tophead-account-img").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
if (topheadjsonresponse.isloggedin == "yes") {
document.getElementById("tophead-accedi-btn").style.display = "none";
document.getElementById("tophead-account-img").style.display = "block";
document.getElementById("Immagine-Profilo-Menu-Principale").style.backgroundImage = "url('../beta/immagini_profilo/" + topheadjsonresponse.profiloimg + "')";
document.getElementById("Nome-Profilo-Menu-Principale").innerHTML = topheadjsonresponse.displayname;
document.getElementById("Username-Profilo-Menu-Principale").innerHTML = "#" + topheadjsonresponse.username;
}
}
You can use jquery for simplified get request
input.addEventListener("input", (event) => {
output.innerHTML = "Cerca " + document.getElementById("tophead-
searchbar").value + " su Nevent";
getData(); //Call the get function
});
// Ajax function to get data using jquery
function getData() {
let ajaxquerylink = "suggerimenti_query.php?query=" + document.getElementById("tophead-searchbar").value;
$.ajax({
url : ajaxquerylink,
type : "GET",
success : function(data)
{
let response = JSON.parse(data);
console.log(response);
}
});
}
I solved by myself, in this row
searchqueryajax.addEventListener("load", innerhtmlqueries);
I removed the () in innerhtmlqueries() and now the call response works
Thanks anyway for the support!
I'm using PHP 7.3 with MySQL v5.6.
Browsing a catalog page, I stored some items ids to localStorage.wishlistStorage.data, and now on the wishlist page I want to retrieve this list of ids for display. I'm using PHP because later I will be sending and retrieving items from a database. Also, it's easy to build HTML on the fly using PHP and a POST array. Unfortunately, I'm struggling with the AJAX XMLHttpRequest.
I am loading a Javascript file at the bottom of the page that retrieves the localStorage data:
var wishlistStorage = {};
window.addEventListener("load", function() {
wishlistStorage.get();
loadWishlist();
});
wishlistStorage = {
data : null, // empty storage
get : function() {
wishlistStorage.data = localStorage.getItem("wishlistStorage");
if(wishlistStorage.data === null) {
wishlistStorage.data = { items: [], item_notes: [], comments: '' };
wishlistStorage.save();
}
else {
wishlistStorage.data = JSON.parse(wishlistStorage.data);
}
}
};
// get wishlist contents
function loadWishlist() {
var items = wishlistStorage.data.items.join("%20");
var wishlistRequest;
if(window.XMLHttpRequest) {
wishlistRequest = new XMLHttpRequest();
} else {
wishlistRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
wishlistRequest.onreadystatechange = function() {
if(wishlistRequest.readyState == 4 && wishlistRequest.status == 200) {
console.log("Got them.");
} else {
console.log("I see nothing.");
}
wishlistRequest.open("POST", "_self", true);
wishlistRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
wishlistRequest.send("wishlist_items=" + encodeURIComponent(items));
}
}
In the body of wishlist.php
<?php
if (array_key_exists('wishlist', $_POST)) {
$temporary_wishlist = $_POST['wishlist'];
echo "Yes, it works! $temporary_wishlist";
} else {
echo 'Invalid parameters!';
}
?>
All I get is the "Invalid Parameters" message. None of the console.log messages appear. Where am I going wrong?
source
I want to display a form with a script I adapted from this question. The script is in a file I wrote called queries.js, and its purpose is to print the content of a php form called "dbMinAlert.php" in a div like this <div id="recentExits" name="recentExits"></div> located in my project's index, I tried invoking getNewData(); in my index.php file using this tag <body onLoad="getNewData()"> but it doesn't seem to do anything at all.
var data_array = ''; // this is a global variable
function getNewData() {
$.ajax({
url: "dbMinAlert.php",
})
.done(function(res) {
data_array = res; // the global variable is updated here and accessible elsewhere
getNewDataSuccess();
})
.fail(function() {
// handle errors here
})
.always(function() {
// we've completed the call and updated the global variable, so set a timeout to make the call again
setTimeout(getNewData, 2000);
});
}
function getNewDataSuccess() {
//console.log(data_array);
document.getElementById("recentExits").innerHTML=data_array;
}
getNewData();`
---This php code works and it actually does what I expect it to do. The real problem is the javascript, for all I care the next php form could print a "Hello world" message, but I want it displayed inside the div I placed in my index, without having to post a thing to dbMinAlert.php.
define("HOST", "localhost");
define("DBUSER", "root");
define("PASS", "password");
define("DB", "mydb");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM outputs, products
WHERE products.idProduct=outputs.idProduct
ORDER BY Date DESC, Time DESC limit 5
");
echo '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
echo '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';
}
echo '</ul>';
You have to execute the function for the first time.
getNewData();
It could be the way you are returning the result from php. Instead of doing multiple echo, could you first assign your result in single php variable and finally do single echo.
$result = '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
$result = $result + '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';}
$result = $result + '</ul>';
echo $result;
I found a solution in this question and my code ended up Like this.
I just had to invoke the function in my index by typing <body onload="return getOutput();">
JavaScript
//Min-Max Alerts
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'dbMinAlert.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('recentExits');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('recentExits');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
I'm trying to complete a connection using Long Polling, where the browser sends a request to the server and to be awaiting a response. To prevent this door is infinitely open, I created a routine that every 10 seconds the server sends an empty response to the browser, stating that there was nothing yet.
It's all working perfectly, had no problems related to that.
My problem is that when the user clicks on a link on the page, the browser waits for the answer call for power upgrade, or can take up to 10-sec. This makes it appear that the tool is slow.
Does anyone have any idea how to solve this?
Image:
Image:
Follows the JavaScript function used to make the call:
function loadJSON() {
if(libera) {
var data_file = http + "bibliotecas/longpolling/notificacoes.php";
var data = {};
data.n = long_n;
data.u = userchat;
data.m = msgchat;
data.c = chatUsuario;
http_request.onreadystatechange = function() {
if(http_request.readyState == 4 && http_request.status == 200) {
try {
var jsonObj = JSON.parse(http_request.responseText);
var qtd = jsonObj.funcao.length;
if(qtd > 0) {
var funcao = "";
for(var key in jsonObj.funcao) {
funcao = jsonObj.funcao[key];
MontarFuncao(eval(funcao),jsonObj.metodo[key]);
}
}
}
catch (e) {
//alert('Erro - '+ http_request.responseText);
}
loadJSON();
}
}
var string = JSON.stringify(data);
http_request.open("POST", data_file, true);
http_request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
http_request.setRequestHeader("Content-length", string.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(string);
return;
}
}
Follows the PHP function responsible for staying open expecting some changes in the database:
ob_start();
$json = json_decode(file_get_contents(`php://input`));
while($x < 5) {
if(time() >= (15 + $_SERVER['REQUEST_TIME']) || connection_aborted()) {
echo str_pad(NULL,1);
die(json_encode(array()));
flush();
ob_flush();
break;
}
//Query DB
if(count($retorno) > 0) {
flush();
ob_flush();
echo json_encode($retorno);
exit;
}
else {
flush();
sleep(2);
$x++;
}
}
I'm not sure if this is related to an ajax call or not. I'm very new to Ajax, and so I suspect it is the cause.
I run the following javascript:
function GetXmlHttpObject() {
"use strict";
var objXMLHttp = null;
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
objXMLHttp = new window.ActiveXObject("Microsoft.XMLHTTP");
}
return objXMLHttp;
}
function delete_director(i) {
"use strict";
var r, url;
r = window.confirm("Are you sure you want to disable this director");
url = "ajax.php?task=director&event=delete&UserId=" + i;
if (r === true) {
mdata = new GetXmlHttpObject();
if (mdata === null) {
alert("Browser does not support HTTP Request");
return;
}
mdata.open("GET", url, true);
mdata.send(null);
}
}
And that calls into the following php function:
function deletedirector()
{
$UserId=mysql_real_escape_string($_GET['UserId']);
$query = "update tbl_users set IsDisabled='1' where UserId=".$UserId;
$result = mysql_query($query) OR die('Cannot perform query!');
if ($result) {
error_log("a");
?><script type="text/javascript">window.location='index.php?task=director&success=Director Successfully Deleted.'</script><?
} else {
error_log("b");
?><script type="text/javascript">window.location='index.php?task=director&error=Director Deletion Failed.'</script><?
}
}
The db shows that the director was deleted, and "a" prints in the error log, but the window.location never fires.
The user experience is that the browser prompts for confirmation, and after that - nothing. A javascript console shows now error.
Any ideas?
You already return new object (of XMLHttpRequest API) with function, so you don't need new here
...
if (r === true) {
mdata = GetXmlHttpObject();
...
and try to use onreadystatechange like this
mdata.onreadystatechange = function(){
if (mdata.readyState === 4) {
alert("some text");
} else {
alert(mdata.status);
}
};