i have a trouble with my project.
In my site i have a page html with a single button and at onclick() eventa js function call intro.js, trough a XmlHttpRequestObject have to do many calls at many php function, in detail:
in js i call scan() function
function scan() {
if (xmlHttp)
{
// try to connect to the server
try
{
// initiate reading the async.txt file from the server
xmlHttp.open("GET", "php/intro.php?P1=http://"+oStxt.value, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
// change cursor to "busy" hourglass icon
document.body.style.cursor = "wait";
}
// display the error in case of failure
catch (e)
{
alert("Can't connect to server:\n" + e.toString());
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
}
}
}
And in handleRequestStatuschange i have:
function handleRequestStateChange()
{
// obtain a reference to the <div> element on the page
// display the status of the request
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
{
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
// read response only if HTTP status is "OK"
if (xmlHttp.status == 200)
{
try
{
// read the message from the server
response = xmlHttp.responseText;
// display the message
document.body.appendChild(oRtag);
oPch = document.getElementById("divRtag");
oOch = document.createTextNode(response);
oPch.appendChild(oOch);
}
catch(e)
{
// display error message
alert("Error reading the response: " + e.toString());
}
}
else
{
// display status message
alert("There was a problem retrieving the data:\n" +
xmlHttp.statusText);
// revert "busy" hourglass icon to normal cursor
document.body.style.cursor = "default";
}
}
}
It works for just one php call, but i need to call different php page in scan function after intro.php (scan2.php, scan3.php, ecc ecc) and with json_decode write single data of the array that return in div tags on my html page.
Which is the best way to call different php pages and manage the results with a single js function in ajax?
Thanks in advance
Alessandro
Not sure how you built your php-functions. Cant you create a function, that calls other functions (scans)?
function doScan(){
$data = array();
//like this, or with a loop
$data['scan1'] = scan1();
....
$data['scanN'] = scanN();
echo json_encode($data);
}
Really, the simplest method that comes to mind is just to parameterise this function. This is as simple as
function doScan(url) { // Code here }
Then simply make the exact same ajax request with the url variable.
xmlHttp.open("GET", "php/" + url + "?P1=http://"+oStxt.value, true);
Next, simply call the doScan function with various parameters.
doScan("index.php");
doScan("otherPage.php");
doScan("somethingElse.php");
This will make ajax requests on the PHP file that you specify.
Related
Hello I managed to get my submit to send a post request via ajax, but I want to make this asynchronous in case my php-file takes longer to process.
I can't seem to wrap my head around the way to async the ajax part. Here is my function so far:
submitForm(e) {
console.log(e);
e.preventDefault();
/* to prevent double submitting the form after the first submit*/
/* submitBtn.disbabled = true; */
this.isDisabled=true;
this.submitStatus = 'Successfully send!';
/* append form-values to the formdata s i can push it to my .php file */
const formData = new FormData();
formData.append('user_name', this.user_name);
formData.append('user_email', this.user_email);
formData.append('user_message', this.user_message);
/* async function should probably start here..*/
/* object of my http request */
const ajax = new XMLHttpRequest();
/* opneing my connection */
ajax.open('POST', this.url);
ajax.onreadystatechange = function() {
/* if state is send and status is ok */
if(ajax.readyState === 4 && ajax.status === 200) {
if (ajax.responseText === "success") {
/* contactForm.innerHTML = `<h2>Thank you, ${contactName}, your message has been send.</h2>` */
}else {
this.submitStatus = ajax.responseText;
this.isDisbabled = false;
}
}
}
/* function-call of my promise function */
/* send the request with the appended form data.
executing the load event */
ajax.send(formData);
/* resetting the input-fields to blank after the submit is done. */
this.user_name="";
this.user_email="";
this.user_message="";
}
I appreciate the help!
You could always wrap the AJAX call in an async function like so:
async function ajaxRequest() {
//ajax call here (pass in anything you need)
return result;
}
and then in your main function just await the result:
let ajaxResult = await ajaxRequest();
so the rest of your code won't execute until the ajax call has finished and the result has been received :)
I have an ajax request executing through the XMLHttpRequest() object
My AJAX method is called in this format:
var xmlhttp = new XMLHttpRequest();
$(document).ready(function () { LoadData(); });
function LoadData()
{
var parameters = "DisplayData=true";
var url = "default.aspx";
Send(url, parameters, "DisplayData");
CheckForAbort();
}
function Send(url, parameters, QueryType)
{
...
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-lencoded");
xmlhttp.send(parameters);
xmlhttp.onreadystatechange = function (){...}
}
There is also a timer on the page which refreshes the data by making a new request through the Send(...) method in intervals of 15 seconds. Every .3 seconds and it calls an Elipsis() method that displays and "blinks" the "loading message" (if appropriate to be displayed) and checks for the abort.
var Color = "red";
function Elipsis() {
if (ResponseMessage != "")
{
if (Color == "darkred") { Color = 'red'; } else { Color = 'darkred'; }
$("#StatusResponse").css("display", "block");
$("#StatusResponse").css("color", Color);
CheckForAbort();
}
}
function CheckForAbort()
{
console.log("MenuActivted: " + MenuActivted);
if (MenuActivted)
{
xmlhttp.abort();
ResponseMessage = "Aborting Request";
MenuActivted = false;
}
}
But when the user clicks the menu bar which is an anchor tag with the HREF set to another page. The browser doesn't respond until the ajax request has completed it's fetch.
The HTML HREF is called the following way on an ASPX page:
<%#Eval("Text")%>
the Ajax Abort sets the flag that is checked in the CheckForAbort() method:
var MenuActivted = false;
function AbortAjax()
{
MenuActivted = true;
return false;
}
I am running IE 11 on Win 7. I have called an abort() method in another section of the code. which executes the xmlhttp.abort(). The response status and ready state respond (console output below) but the page still waits to respond to the HREF
Console output:
HTML1300: Navigation occurred.
File: ChangePassword.aspx
MenuActivted: true
ReadyState: 4
Status: 0
Does anyone have a solution to this problem?
[Updated **********]
I thought I had the solution but I didn't.
I commented out the set header but although it allowed my HREF to execute it was because the xhr was throwing an error and the fetch was terminating.
xmlhttp.open("POST", url, true);
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
Please read the entire post before responding.
I'm new to web-development. Created a signup page making some asynchronous calls to php. Ran debugging found the control skips the onreadystatechange function completely. Please help...
var ajax = ajaxObj("POST", "signup.php"); //defines the ajax object, definition is below
ajax.onreadystatechange = function () { //doesn't run after this line
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box
at <u>"+e+"</u> in a moment to complete the sign up process.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g); //control reaches here directly
}
}// control exits here
The ajax object is created externally here..
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
This is because it's an event callback function and it will be called when server responds to your ajax request. If you're using firefox press F12, switch to network tab and check html and xhr to see it's status.
Because it is asynchronous so the function won't be called as you step through the code in a linear fashion.
It gets called by native code when the ready state changes.
Stick a breakpoint inside the function if you want to debug it.
i'm trying to login into the site with the following javascript. But, i'm loading only the complete page. I'm developing windows 8 app
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/home/home.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
// TODO: Initialize the page here.
document.getElementById("bt_login").addEventListener("click", login, false);
}
});
})();
function login() {
var xhrDiv = document.getElementById("xhrReport");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = dataLoaded;
xhr.open("POST", "http://www.160by2.com", true, <username>, <password>);
xhr.send();
function dataLoaded() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// OK
xhrDiv.innerHTML = window.toStaticHTML("response:" + xhr.responseText);
} else {
// not OK
xhrDiv.innerText = "failure";
}
}
};}
I want to dsiplay in xhrdiv.innerHTML as "LOGIN SUCCESS" or "LOGIN ERROR"
EDIT:
I tried the following code:
iframe = document.getElementById("ifra_op");
iframe.setAttribute("src", "http://www.160by2.com/index");
document.getElementById("op").appendChild(iframe);
iframe.contentWindow.document.getElementById("MobileNoLogin") = "<mobno>";
iframe.contentWindow.document.getElementById("LoginPassword") = "<pass>;
iframe.contentWindow.document.getElementsByName("LoginForm").click();
But, there is an error. It says "Javascript run time error:math is undefined"
"math" comes from the website. I don't know how to handle this. Also, the permission is denied. Why is that so?
You need to make sure you have a service (something like a web service) in the remote server to process the request.
In here what you can do is.
Create an iframe and set the src to 160by2;
Access the webpage using iframe.contentwindow, inject your code to fill up the forms and trigger the submit button.
Parse the received html to verify your login.
Use jquery , makes life easier.
var iframe = $("#ifra_op");
$(iframe).attr("src", "http://www.160by2.com/index");
$(iframe).attr("onload","submitForm();");
function submitForm(){
$(iframe.contentWindow.document).find("#MobileNoLogin").val("9999");
$(iframe.contentWindow.document).find("#LoginPassword").val("pass");
$('#button').click();
}
Below is my javascript code snippet. Its not running as expected, please help me with this.
<script type="text/javascript">
function getCurrentLocation() {
console.log("inside location");
navigator.geolocation.getCurrentPosition(function(position) {
insert_coord(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
});
}
function insert_coord(loc) {
var request = new XMLHttpRequest();
request.open("POST","start.php",true);
request.onreadystatechange = function() {
callback(request);
};
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send("lat=" + encodeURIComponent(loc.lat()) + "&lng=" + encodeURIComponent(loc.lng()));
return request;
}
function callback(req) {
console.log("inside callback");
if(req.readyState == 4)
if(req.status == 200) {
document.getElementById("scratch").innerHTML = "callback success";
//window.setTimeout("getCurrentLocation()",5000);
setTimeout(getCurrentLocation,5000);
}
}
getCurrentLocation(); //called on body load
</script>
What i'm trying to achieve is to send my current location to the php page every 5 seconds or so. i can see few of the coordinates in my database but after sometime it gets weird. Firebug show very weird logs like simultaneous POST's at irregular intervals.
Here's the firebug screenshot:
IS there a leak in the program. please help.
EDIT: The expected outcome in the firebug console should be like this :-
inside location
POST ....
inside callback
/* 5 secs later */
inside location
POST ...
inside callback
/* keep repeating */
Probably not the problem, but I can suggest two refactorings:
Merge your two conditions in callback():
if ((req.readyState == 4) && (req.status == 200)) {
And you can shorten your setTimeout line to:
setTimeout(getCurrentLocation, 5000);
And in an effort to fix the problem, can I get you to remove the setTimeout() from callback(), and replace the call to getCurrentLocation() with it? So you're only writing "callback success" when the callback is run, nothing else.
setTimeout(getCurrentLocation, 5000); //called on body load