How can I iterate XMLHttpRequest? - javascript

I have two files: one file contains php code (and it works properly) and the other one contains javacript.
The problem is in javascript page:
function calcDist() {
var citta = $("#txtpartenza").val();
$.ajax({
type: "POST",
url: 'mostraPartenze.php',
dataType: "json",
success: function (data) {
$.each(data, function (index) {
var partenza = data[index];
trovaGeo(citta, partenza);
});
}
});
}
function trovaGeo(partenza, destinazione) {
var latPartenza;
var lonPartenza;
var latDestinazione;
var lonDestinazione;
console.log(partenza); // for test
console.log(destinazione); // for test
var xmlhttpPart = new XMLHttpRequest();
var xmlhttpDest = new XMLHttpRequest();
xmlhttpPart.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext="+partenza+"&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpPart.send();
xmlhttpDest.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext="+destinazione+"&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpDest.send();
xmlhttpPart.onreadystatechange = function () {
if (xmlhttpPart.readyState == 4 && xmlhttpPart.status == 200) {
xmlhttpDest.onreadystatechange = function () {
if (xmlhttpDest.readyState == 4 && xmlhttpDest.status == 200) {
var resPart = JSON.parse(xmlhttpPart.responseText);
latPartenza = resPart.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
lonPartenza = resPart.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
var resDest = JSON.parse(xmlhttpDest.responseText);
latDestinazione = resDest.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
lonDestinazione = resDest.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
lonDestinazione = resDest.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
console.log(latPartenza);
}
};
}
};
}
Ajax works correctly; I can call trovaGeo(citta, partenza) without problems but in trovaGeo(partenza, destinazione) function, XMLHttpRequest "part" doesn't work properly: in console the variable latPartenza is never printed and obviously all codes in xmlhttpPart.onreadystatechange = [...] it's never executed.
For completeness this is the heart of php file:
$i = 0;
$citta = array();
while ($rows = $result->fetch_assoc()) {
$citta[$i] = $rows['partenza'];
$i=$i+1;
}
echo json_encode($citta);

I find the problem.
I have to use preventDefault in the first line of the event of on('submit'...
This is the solution:
$('form').on('submit', function (e) {
e.preventDefault();
[...]

The problem might be with nested onreadystatechagestatements , there might be a delay in responses. But I can see that second request is dependent on first request response.try the below change
xmlhttpPart.onreadystatechange = function() {
if (xmlhttpPart.readyState == 4 && xmlhttpPart.status == 200) {
xmlhttpDest.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext=" + destinazione + "&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpDest.send();
xmlhttpDest.onreadystatechange = function() {
// your code
console.log(latPartenza);
}
};
}
};

Related

Javascript GET request after POST request

I have a page that uses a function for getting some data, with a GET xhttp request, from a database (get_worktime_list()).
On the same page, I can add some data to the database with a form using a POST xhttp request and after a success (saved in the response) I will get the content included the new line from the database with the same function get_worktime_list().
The problem is that when getworktime is called after the POST request, get_worktime_list() makes another POST request instead of a GET. why???
function http_request(post_data, end_point, type)
{
console.log("HTTP");
var res = 0;
//var data = "data=0&username="+stored_token.username+"&token="+stored_token.token;
var data = "data=0&"+post_data;
console.log(data);
// Check if is valid token/username from database
const url = "http://192.168.1.188:5000/services/"+end_point;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(xhttp.responseText);
}
};
if (type == "GET")
{
console.log(url+"?"+post_data);
xhttp.open("GET", url+"?"+post_data, false);
}
else
{
console.log("Data: "+data);
xhttp.open("POST", url, false);
}
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(data);
xhttp.abort();
return res;
}
This add data to DB
function addworktime(username,token)
{
console.log("Aggiungo ore");
var date = document.getElementById("data").value;
var type = document.getElementById("turno").value;
var pay = document.getElementById("paga").value;
var emp = document.getElementById("dipendente").value;
var ore = document.getElementById("num_ore").value;
var data = "username="+username+"&token="+token+"&day="+date+"&turn_type="+type+"&pay="+pay+"&emp="+emp+"&ore="+ore;
var res = http_request(data,"admin/dipendenti/addtime.php","");
//console.log(res);
if (res.insert_ok == 1)
{
display_time_table(0,0,null);
} else {
console.log(res);
}
}
This function makes a GET request when a page load and a POST request when called by addworktime()
function display_time_table(from,to,cf)
{
let time_list_table = document.getElementById("list-container");
var time_list = get_worktime_list(saved_data.username,saved_data.token,from,to,cf);
let time_table = generate_time_list_table(time_list);
time_list_table.innerHTML = time_table;
}
function get_worktime_list(username,token,date_from,date_to,cf)
{
var data = "username="+username+"&token="+token;
if (cf != "" || cf != null)
{
data = data+ "&dipendente="+cf;
}
if (date_from != 0)
{
data = data +"&date_from="+date_from;
}
if (date_to != 0)
{
data = data + "&date_end="+date_to;
}
var time_list = http_request(data,"admin/dipendenti/getworktime.php", "GET");
return time_list;
}
The server can only accept GET requests for that API and obviously, I get a parse error parsing the JSON response.
Thanks for help

when we open the code in console browser all the mobile number should be display i did not want this? how to hide this from console?

After View console all the mobile no showing how can I resolved it?
var jArray = <?php echo json_encode($allmobone); ?>;
var mob = document.getElementById("user_mobile_number").value;
var precode = "91";
mobcode = precode + mob;
for (var r = 0; r < jArray.length; r++) {
if (jArray[r] == mobcode) {
document.getElementById("spn_user_mobile_number_2").style.display = "block";
return false;
}
}
If you need to hide the $allmobone value completely from a browser developer tools, don't send it to clients. Instead send an AJAX request to the server when you need to check a mobile number, and make a decision depending on the request response.
Here is an HTML code of the page with the user interface:
function ajaxGet(url, onload, onerror) {
var request = new XMLHttpRequest();
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
onload(request.responseText);
} else {
onerror();
}
};
request.onerror = onerror;
request.open('GET', url, true);
request.send();
}
var mob = document.getElementById("user_mobile_number").value;
var precode = "91";
mobcode = precode + mob;
ajaxGet('/checkMobileCode.php?mobcode=' + encodeURIComponent(mobcode), function (response) {
if (response === 'ok') {
document.getElementById("spn_user_mobile_number_2").style.display = "block";
}
});
And here is a PHP code of the script which checks a mobile code (/checkMobileCode.php):
if (in_array($_GET['mobcode'] ?? '', $allmobone)) {
echo 'ok';
} else {
echo 'fail';
}
Option 1:
Use Ajax to load your resources dynamically, then viewing source (ctrl+u) will not show any values:
$.ajax({
url: 'getJson.php',
dataType: 'json',
success: function (jArray) {
var mob = document.getElementById("user_mobile_number").value;
var precode = "91";
mobcode = precode + mob;
for (var r = 0; r < jArray.length; r++) {
if (jArray[r] == mobcode) {
document.getElementById("spn_user_mobile_number_2").style.display = "block";
break;
}
}
}
});
But there still be visible response in console network tab
Option 2:
If you have only static data, then loop your data and apply inline css:
<?php
foreach ($allmobone as $el) {
if ($el === $_POST['mobcode']) {
echo "<div id='spn_user_mobile_number_2'>...</div>";
}
}
Only that you have to submit form when user enters "mobcode" to reload page.

update function on ajaxObject

When a button is clicked on the webpage a table of data is displayed. I want to scrape that data but I can't find where it comes from in the website source code.
This is the tag for the button:
<button type="submit" onclick="divChangeStateOn('load-raw-0062294377Amazon.com'); getRaw('0062294377', 'Amazon.com', 'lr-0062294377Amazon.com',this);"style="margin-bottom: 4px; width: 120px; text-align: left;" name="load-raw"><img src='images/workstation.png'/> raw data</button>
I believe that the getRaw function is where the data comes from (I'm not positive about this) so I looked at the javascript code for the getRaw function
function getRaw(asin, store, res, caller)
{ document.getElementById(res).innerHTML = '<p align="center" valign="top"><img align="center" src="phpmy_loading.gif"></p>';
var poststr = "raw=" + encodeURI(asin) +
"&site=" + encodeURI(store);
var updateResults = new ajaxObject(res, 'extra.php', caller);
updateResults.update(poststr);
}
I have been having a hard time finding any documentation about ajaxObject and can't find any information about the update function. What is ajaxObject.update doing and is it possible for me to access the data that appears when the button is clicked?
function divChangeStateOn(divID)
{ var divElem = document.getElementById(divID);
divElem.style.display = 'block';
}
EDIT: The link to the source code view-source:http://www.ranktracer.com/account_workstation.php it might be password protected but I was just using the demo version
EDIT 2:
I am basically trying to write a script that replicates the Ajax http request. This where I am at, it doesn't work and I am especially concerned about where data = uri
x = time.time()
print x
timestamp = datetime.fromtimestamp(x/1000.0)
print timestamp
uri = "raw=0062294377&site=Amazon.com&timestamp="+str(timestamp);
url = "lr-0062294377Amazon.com"
length = str(len(uri))
headers = {'X-Requested-With': 'XMLHttpRequest',
"Content-type": "application/x-www-form-urlencoded",
"Content-length": length,
"Connection" : "close"}
s = Session()
r = s.post(url= url, data= uri, headers= headers)
The entire code for ajaxObject is present in the link you provided. Please let us know what help you are expecting here?
function ajaxObject(layer, url, caller) {
if (caller) {
disableButton(caller, 'disable');
}
var that = this;
var updating = false;
this.callback = function() {}
var LayerID = document.getElementById(layer);
this.update = function(passData) {
if (updating == true) {
return false;
}
updating = true;
var AJAX = null;
if (window.XMLHttpRequest) {
AJAX = new XMLHttpRequest();
} else {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX == null) {
alert("Your browser doesn't support AJAX.");
return false
} else {
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4 || AJAX.readyState == "complete") {
if (caller) {
disableButton(caller, 'enable');
}
LayerID.innerHTML = AJAX.responseText;
delete AJAX;
updating = false;
that.callback();
}
}
var timestamp = new Date();
var uri = passData + '&timestamp=' + (timestamp * 1);
AJAX.open("POST", url, true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", uri.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.send(uri);
return true;
}
}
}

AJAX Requests to php script

So the problem is: a user uplaods a file. I use ะต.PreventDefault(); to prevent the page from refreshing after the upload. Under the file upload form i've made a list of all the user's file names. Obviously the newly uploaded file name isn't in the list. After refreshing the page it gets in the list, but the business logic is that the file's name should go in the list withouth refreshing the page.
function showNewFileProperies() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("results").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "../../app/Models/UserFiles.php" , true);
xhttp.send();
}
This is the request with which I thought my problem would be solved.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserFiles extends Model{
protected $table = 'files';
public function getUserFiles(){
$getFiles = Filecontent::where('userid', Auth::id())->get();
foreach($getFiles as $getFile) {
$result = $getFile->filename;
return $result;
}
}
}
I'm using Laravel and Dropzone.js. The js code i put in the success event of dropzone.js
Sorry for the delay in response. Here is what I used to achieve what you are describing. Sorry for the bad indenting but this editor is really bad.
Dropzone.options.documentDropzone = {
paramName: "file",
dictDefaultMessage: "Drag your document over this box to upload or click here",
maxFilesize: 100, // MB
maxFiles: 10,
addRemoveLinks: true,
dictRemoveFile: 'Remove Attachment',
accept: function(file, done) {
done();
},
init: function() {
this.on("addedfile", function(file) {
busy_uploading = true;
});
this.on('removedfile', function(file){
remove_file(file.previewElement, file.fileID);
if(this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
busy_uploading = false;
}
});
this.on("complete", function (file) {
if(this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
busy_uploading = false;
}
});
},
success: function(file, response) {
response = JSON && JSON.parse(response) || $.parseJSON(response);
if(response.error) {
var node, _i, _len, _ref, _results;
var message = response.error;
file.previewElement.classList.add("dz-error");
_ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
_results.push(node.textContent = message);
}
return _results;
} else {
for(var i = 0; i < response.file_id.length; i++) {
file.fileID = response.file_id[i];
file.fileEXT = response.file_ext[i];
add_file_id(response.file_id[i]);
//You can add the uploaded item in your list here
}
return file.previewElement.classList.add("dz-success");
}
}
};
So this is roughly what I used. You can simply add the item on your list in the success function since that is where you will get the response from the server.
I did not include the php because it is just your basic upload script. This will work with as many files as you wish.
If you need more help just add a comment and I will try to assist you as best I can.
Actually I came up with this:
public function getCurrentFile(){
$userid = Auth::id();
$getFiles = File::where('userid', $userid)->orderBy('created_at', 'desc')->take(1)->get();
foreach($getFiles as $getFile) {
$result = $getFile;
$json = json_encode($result); //make it as json
return $json;
//echo $result;
}
}
Then I routed this model and in the js I've added:
success: function(file) {
$(function ()
{
$.ajax({
async: true,
url: "../public/currentfile",
dataType: 'json',
method:'get',
complete: function(data)
{
console.log(data.responseJSON);
var created_at = data.responseJSON['created_at'];
var filesize = data.responseJSON['filesize'];
var filename = data.responseJSON['filename'];
var fileid = data.responseJSON['fileid'];
$( "#results .tableheaders" ).after("<tr><td>" + fileid + "</td><td>" + filename + "</td><td>" + filesize + "</td><td>" + created_at + "</td></tr>");
}
});
});
if (file.previewElement) {
return file.previewElement.classList.add("dz-success");
}
}
And it seems to work...for now :D I'm not a JS guy and I don't even know how I managed to do this :D

Calling data from JSON file using AJAX

I am trying to load some data from my JSON file using AJAX. The file is called external-file.json. Here is the code, it includes other parts that haven't got to do with the data loading.The part I'm not sure of begins in the getViaAjax funtion. I can't seem to find my error.
function flip(){
if(vlib_front.style.transform){
el.children[1].style.transform = "";
el.children[0].style.transform = "";
} else {
el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
}
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');
el.addEventListener('click', flip);
var word = null; var explanation = null;
var i=0;
function updateDiv(id, content) {
document.getElementById(id).innerHTML = content;
document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
function counter (index, step){
if (word[index+step] !== undefined) {
index+=step;
i=index;
updateDiv('the-h',word[index]);
updateDiv('the-p',explanation[index]);
}
}
var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
r.onload = function() {
if(this.status < 400 && this.status > 199) {
if(typeof callback === "function")
callback(JSON.parse(this.response));
} else {
console.log("err");// server reached but gave shitty status code}
};
}
r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}
r.send();
}
function yourLoadingFunction(jsonData) {
word = jsonData.words;
explanation = jsonData.explanation;
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
// then call whatever it is to trigger the update within the page
}
getViaAjax("external-file.json", yourLoadingFunction)
As #light said, this:
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
Should be:
function getViaAjax(url, callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", url, true);
I built up a quick sample that I can share that might help you isolate your issue. Stand this up in a local http-server of your choice and you should see JSON.parse(xhr.response) return a javascript array containing two objects.
There are two files
data.json
index.html
data.json
[{
"id":1,
"value":"foo"
},
{
"id":2,
"value":"bar"
}]
index.html
<html>
<head>
</head>
<body onload="so.getJsonStuffs()">
<h1>so.json-with-ajax</h1>
<script type="application/javascript">
var so = (function(){
function loadData(data){
var list = document.createElement("ul");
list.id = "data-list";
data.forEach(function(element){
var item = document.createElement("li");
var content = document.createTextNode(JSON.stringify(element));
item.appendChild(content);
list.appendChild(item);
});
document.body.appendChild(list);
}
var load = function()
{
console.log("Initializing xhr");
var xhr = new XMLHttpRequest();
xhr.onload = function(e){
console.log("response has returned");
if(xhr.status > 200
&& xhr.status < 400) {
var payload = JSON.parse(xhr.response);
console.log(payload);
loadData(payload);
}
}
var uri = "data.json";
console.log("opening resource request");
xhr.open("GET", uri, true);
xhr.send();
}
return {
getJsonStuffs : load
}
})();
</script>
</body>
</html>
Running will log two Javascript objects to the Dev Tools console as well as add a ul to the DOM containing a list item for every object inside the data.json array

Categories