I'm creating a Chrome extension that injects an HTML form on a page through inject.js and when a query is entered and the button is pressed an API call is made through background.js. The contents are then brought back to the inject.js script and processed.
When I first try to make a call through inject.js I get the following error:
Error in event handler for 'undefined': fetchResult is not defined ReferenceError: searchResult is not defined
Oddly enough when I wait a little and press again the query is fetched.
I'm suspecting fetchresult is undefined the first time because it takes a couple of moments to fetch the query but I don't know how to fix this.
inject.js:
function fetch() {
var fetchResult;
var fetchquery = document.getElementById('field').value;
chrome.extension.sendMessage({greeting: fetchquery}, function(response) {
fetchResults = response.farewell
constructHTML(fetchResultsResults)
});
};
background.js:
function loadXMLDoc(query)
{
if (query){
// new cross origin XML request
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
fetchResult = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET","http://XXXXXXXXXXXXXXX&q="+query, true);
xmlhttp.send();
return fetchResult;
} else {
return "noquery";
}
};
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (loadXMLDoc(request.greeting) != "noquery"){
sendResponse({farewell: loadXMLDoc(request.greeting)})
}
});
Any help will be greatly appreciated!
XMLHttpRequest is asynchronous, so instead of return fetchResult, you should invoke a callback to pass the result. Here's an example:
function loadXMLDoc(query, callback)
{
if (query){
// new cross origin XML request
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
if(xmlhttp.status==200)
{
fetchResult = JSON.parse(xmlhttp.responseText);
callback(fetchResult);
} else {
callback("noquery");
}
}
}
xmlhttp.open("GET","http://XXXXXXXXXXXXXXX&q="+query, true);
xmlhttp.send();
} else {
callback("noquery");
}
};
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
loadXMLDoc(request.greeting, function(fetchResult) {
if (fetchResult != "noquery")
sendResponse({farewell: fetchResult})
else
sendResponse({});
});
return true; // See the description of https://developer.chrome.com/extensions/extension.html#property-onMessage-sendResponse.
});
Related
function getXmlHttpRequestObject()
{
var xmlHttp = false;
if (window.XMLHttpRequest)
{
return new XMLHttpRequest(); //To support the browsers IE7+, Firefox, Chrome, Opera, Safari
}
else if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP"); // For the browsers IE6, IE5
}
else
{
alert("Error due to old verion of browser upgrade your browser");
}
}
var xmlhttp = new getXmlHttpRequestObject(); //xmlhttp holds the ajax object
function servletPost()
{
if(xmlhttp)
{
var comp_to = document.getElementById("comp_to").value;
var comp_subject = document.getElementById("comp_subject").value;
var comp_letter = document.getElementById("comp_letter").value;
var date_time = document.getElementById("date_time").value;
if(comp_to==""||comp_subject==""||comp_letter==""||date_time=="")
{
document.getElementById("redSignal").style.display='block';
document.getElementById("redSignal").innerHTML="All Fields are necessary";
}
else
{
xmlhttp.open("POST","complaintHandler",true);
xmlhttp.onreadystatechange = handleServletPost;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data_string="to="+comp_to+"&subject="+comp_subject+"&complaint="+comp_letter+"&date_time="+date_time;
xmlhttp.send(data_string);
}
}
}
function handleServletPost()
{
if (xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
document.getElementById("greenSignal").style.display='block';
document.getElementById("greenSignal").innerHTML=xmlhttp.responseText;
}
else
{
document.getElementById("redSignal").style.display='block';
document.getElementById("redSignal").innerHTML="Error Code ="+xmlhttp.status;
}
}
}
I am getting the problem of error code 404
What could be the problem in this code? Please help me.
Error 404 itself says that your URL is wrong .
xmlhttp.open("POST","complaintHandler-wrong",true);
check this URL 1st .
ERROR 404 Says. The requested Http request is not present or wrong.
Please check your "complaintHandler" It might be complaintHandler.jsp , kind of...
Please go through this tutorial for your future use.
Here is the scenario:
I have a text box where I can enter a text for "Status". Beside it is a label that should contain the latest "Status". After entering a new status, a button of type button is invoked and calls 2 things(a pop-up cor credentials and a function for XMLHttpRequest).
function a(url){
try {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != null) {
req.open("GET", url, true);
req.onreadystatechange = getData;
req.send();
} else {
alert("fail");
}
} catch (e) {
alert("Error");
}
}
function getData(){
if(req.readyState == 4){
...some code
}
}
After entering credentiols and click on ok, the latest status should be updated. This is working fine in firefox and chrome. Also the only time the status updates on IE is when the browser was closed then opened.
I need to send a mail with jsp, but the page itself mustn't reload. The whole implementation is working fine when reloading on the POST-event, but adjusting the code to work with ajax breaks it. It seems that the jsp-Code within the index.jsp is not executed, when the ajax event is triggerd.
I am gonna show some snippets:
index.jsp
<%
String result = "=(";
String to = request.getParameter("rec_mail");
if(to != null) {
String from = request.getParameter("sendermail");
String host = "mailserver";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session mailSession = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Feedback");
message.setText(request.getParameter("feedbackinput"));
Transport.send(message);
result = "Sucess!";
}catch (MessagingException e) {
e.printStackTrace();
result = "failed!";
}
}
out.println(request.getParameter("sendermail"));
out.println(result);
%>
<input id="bsend" class="fbutton" type="submit" name="send" value="Send" onclick="loadContent()" style="float:right; width:18%; height:35%;" >
ajax.js
var xmlhttp
function loadContent() {
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support Ajax!");
return;
}
var url="./index.jsp";
xmlhttp.open("post",url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange=getOutput;
}
function getOutput()
{
if (xmlhttp.readyState==4)
{
alert("Message sent!");
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
(just showing the relevant parts, everywhere)
I get the alert-message, but no mail is sent ... I hope it is clear, what I am trying to do..
Thank you!
Best regards
Don't you also need to set a header for a HTTP Post
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
also, not sure if it will make a difference but I would make "post" to "POST".
I am trying to send some parameters through xmlHttpRequest.send(params) written in a JS file to my servlet where I try to get the parameters by req.getParameter("some_Parameter"); it returns null on the servlet. though if i send the parameters by appending them in url it works fine. but when the url will be large it will break the code. so please someone help me out.
Thanks in advance.
function doHttpPost(theFormName, completeActivity)
{
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
var xmlMessage = buildPOST(theFormName, completeActivity);
var responseTxt;
try {
xmlhttp.Open(document.forms[theFormName].method, document.forms[theFormName].action+'?'+xmlMessage, false);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
responseTxt = xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
enableDisableLinks(true);
setPointer();
xmlhttp.Send();
if(xmlhttp.Status != 200) {
alert("Post to server failed");
}
} catch (e) {
responseTxt = "Exception while posting form data: Error No: " + e.number + ", Message: " + e.description;
}
resetPointer();
enableDisableLinks(false);
var expectedTxt = "Form Data had been successfully posted to the database."
if(responseTxt.toString() == expectedTxt.toString()) {
// MNP: New requirement from Jeanne, should not refresh CM page, commenting it off for now
//if(completeActivity) {
// if (typeof (ViewCaseDetailBtn) != 'undefined') {
// ViewCaseDetailBtn.click();
// }
//}
return true;
} else {
alert (responseTxt);
}
return false;
}
BUGS
//IE only - shooting yourself in the
// Not all IE versions use ActiveX!
var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); foot.
//JavaScript case sensitive, open !== Open
xmlhttp.Open(document.fo...
//JavaScript case sensitive, send !== Send
xmlhttp.Send();
//JavaScript case sensitive, status !== Status
xmlhttp.Status
AND if you are using synchronous, it does not call the onreadystatechange.
If you are using POST, the value needs to be in send("valuestosendup") not on the querystring.
This code shows why you should really use a framework to make Ajax calls and to not roll your own.
I am trying to get the source code of HTML by using an XMLHttpRequest with a URL. How can I do that?
I am new to programming and I am not too sure how can I do it without jQuery.
Use jQuery:
$.ajax({ url: 'your-url', success: function(data) { alert(data); } });
This data is your HTML.
Without jQuery (just JavaScript):
function makeHttpObject() {
try {return new XMLHttpRequest();}
catch (error) {}
try {return new ActiveXObject("Msxml2.XMLHTTP");}
catch (error) {}
try {return new ActiveXObject("Microsoft.XMLHTTP");}
catch (error) {}
throw new Error("Could not create HTTP request object.");
}
var request = makeHttpObject();
request.open("GET", "your_url", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4)
alert(request.responseText);
};
You can use fetch to do that:
fetch('some_url')
.then(function (response) {
switch (response.status) {
// status "OK"
case 200:
return response.text();
// status "Not Found"
case 404:
throw response;
}
})
.then(function (template) {
console.log(template);
})
.catch(function (response) {
// "Not Found"
console.log(response.statusText);
});
Asynchronous with arrow function version:
(async () => {
var response = await fetch('some_url');
switch (response.status) {
// status "OK"
case 200:
var template = await response.text();
console.log(template);
break;
// status "Not Found"
case 404:
console.log('Not Found');
break;
}
})();
There is a tutorial on how to use Ajax here: https://www.w3schools.com/xml/ajax_intro.asp
This is an example code taken from that tutorial:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// Code for Internet Explorer 6 and Internet Explorer 5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
I had problems with the fetch api and it seams that it always returns promise even when it returns text "return await response.text();" and to handle that promise with the text, it needs to be handled in async method by using .then.
<script>
// Getting the HTML
async function FetchHtml()
{
let response = await fetch('https://address.com');
return await response.text(); // Returns it as Promise
}
// Usaing the HTML
async function Do()
{
let html = await FetchHtml().then(text => {return text}); // Get html from the promise
alert(html);
}
// Exe
Do();
</script>
For an external (cross-site) solution, you can use: Get contents of a link tag with JavaScript - not CSS
It uses $.ajax() function, so it includes jquery.
First, you must know that you will never be able to get the source code of a page that is not on the same domain as your page in javascript. (See http://en.wikipedia.org/wiki/Same_origin_policy).
In PHP, this is how you do it:
file_get_contents($theUrl);
In javascript, there is three ways :
Firstly, by XMLHttpRequest : http://jsfiddle.net/635YY/1/
var url="../635YY",xmlhttp;//Remember, same domain
if("XMLHttpRequest" in window)xmlhttp=new XMLHttpRequest();
if("ActiveXObject" in window)xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open('GET',url,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)alert(xmlhttp.responseText);
};
xmlhttp.send(null);
Secondly, by iFrames : http://jsfiddle.net/XYjuX/1/
var url="../XYjuX";//Remember, same domain
var iframe=document.createElement("iframe");
iframe.onload=function()
{
alert(iframe.contentWindow.document.body.innerHTML);
}
iframe.src=url;
iframe.style.display="none";
document.body.appendChild(iframe);
Thirdly, by jQuery : [http://jsfiddle.net/edggD/2/
$.get('../edggD',function(data)//Remember, same domain
{
alert(data);
});
]4
Edit: doesnt work yet...
Add this to your JS:
var src = fetch('https://page.com')
It saves the source of page.com to variable 'src'