xmlhttprequest in chrome extension - xmlhttprequest

I am developing a chrome extension and I have an iframe which I use in my extension. This is what I do with my iframe
"When I drag and drop a image to my iframe I handle the drop event in one of the content scripts and pass that function call my extension code. There I create a xmlhttprequest object and then send the URL of the image to a php file in my server."
This is what is happening. I get a readyState of "4" but there is no POST request going out of my browser. I checked with the "NETWORK" tab in the browser but there is no POST request going out of the browser (I have listed my site in the permissions section of the manifest file).
This is my code --.>
JScript.js(One of the content scripts )
drop: function(event, ui) {
var imgurl=$(ui.draggable).attr('src');
imgurl="IMGURL="+imgurl;
_post("www.somedomain.come/testing.php",imgurl,function(result){ alert("success")});
}
This is my proxy in the same content script-->
_post = function(url, data, callback)
{
console.log("sending post");
chrome.extension.sendRequest({
msgType:'post',
data: data,
url:url
}, function(response){
alert(response);
});
}
This my OnRequest function handler in background.html -->
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
if (request.msgType === 'post') {
alert("Now in OnRequest function");
// console.log("Now in Onrequest Function");
alert("Url: "+request.url + "\n Data : "+ request.data);
ajaxcallingfunction(request);
alert("completed the ajax call");
sendResponse("success");
}
});
var ajaxcallingfunction = function(request){
var xhr = new XMLHttpRequest();
xhr.open("POST",request.url, false);
xhr.onreadystatechange = function(){
alert(xhr.readyState);
if (xhr.readyState == 4) {
alert(xhr.readyState);
}
}
xhr.send(request.data);
alert("after xhr call");
};

You have http:// in front of your url, right?
xhr.readyState doesn't tell much, it just means that it is done. Check out what's inside xhr.status, it would contain error code. If everything is ok it should be 200:
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
alert(xhr.status);
}
}

Related

Shutdown Kodi with api (blackberry qml)

Hello I trying shutdown Kodi (raspberry pi) with mobile app (blackberry qml).
But I do not how.
I used this code: (in browser)
"http://[myip]:[myport]/jsonrpc?request={"jsonrpc":"2.0","method":"System.Suspend","id":1}"
I used this code: (in the app)
function sendRequest() {
var xhr = new XMLHttpRequest();
var url = "http://[myip]:[myport]/jsonrpc?request={\"jsonrpc\":\"2.0\",\"method\": \"System.Suspend\",\"id\":1}"
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseText);
textArea.text = xhr.responseText;
}
}
};
xhr.open("GET", url, true); // with "POST" I got the same problem.
xhr.send();
}
I got:
{"error":{"code":-32700,"message":"Parse error."},"id":null,"jsonrpc":"2.0"}
Remote from web browser works fine (http://[myip]:[myport])
Thank you for your answers.
********** Update: 21.10.2020 **********
I'm in progress. But I don't know what to do next.
I found some information why I have an error.
I don't know how to implement in my code.
Can you help me?
Thank you so much.
https://github.com/xbmc/xbmc/pull/12281
https://forum.kodi.tv/showthread.php?tid=324598&highlight=json
Here's how to do it.But I can't understand it.
https://retifrav.github.io/blog/2018/09/01/kodi-remote-control-app/
This is my function (on Kodi 17.6 it is working but on Kodi 18 is not working )
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
text.text = xhr.responseText
}
}
};
var url = 'http://<IP:PORT>/jsonrpc?request={"jsonrpc": "2.0", "id": 1, "method": "System.Shutdown"}'
xhr.open("GET", url, true) // when I write "POST" - nothing happens
xhr.send()
}
You should URL encode the json in your url before it's used in the open method. Use encodeURIComponent() to do that. Your browser is changing:
{"jsonrpc":"2.0","method": "System.Suspend","id":1}"
To:
%7B%22jsonrpc%22%3A%222.0%22%2C%22method%22%3A%20%22System.Suspend%22%2C%22id%22%3A1%7D%22
But your code is not.

angularjs post file to web api

I've a angular function for to upload file to web api
$scope.uploadFile = function () {
var file = $scope.file;
console.log("file: " + file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", uri);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);
$scope.progressVisible = true;
xhr.send(file);
}
function uploadProgress(evt) {
$scope.$apply(function () {
if (evt.lengthComputable) {
$scope.progress = Math.round(evt.loaded * 100 / evt.total);
}
})
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
$scope.$apply(function () {
$scope.progressVisible = false;
})
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
The code is available here http://jsfiddle.net/vishalvasani/4hqVu/
I need a web api controller to manage file post, how can I read it?
Is it possible to use PostValue instead of task async?
Server side I get the file, read content, query a database and return JSON response
Thanks

CORS doesn't work

i was trying to make asynchronous call to Yahoo's symbol suggest JSONP API, so there's cross domain problem, I have read this document and try to change it's url , the following are the codes i use
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
// var url = 'http://updates.html5rocks.com';
var url = 'http://autoc.finance.yahoo.com/autoc?query=google&callback=YAHOO.Finance.SymbolSuggest.ssCallback';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
console.log(text);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
but the problem still not solved:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
does anyone know why? Also, I compared the code in document with regular ajax code, they are almost the same, how does CORS work?
thanks
For CORS to work, the server needs to set the Access-Control-Allow-Origin header. If you do not control the server, and the server hasn't set that header, then I'm afraid you're out of luck.
CORS replaces JSONP as the way to load cross-domain json content, but with JSONP the server also needs to implement it.
If the owner of the content doesn't want you to use it, the browser will reject it.
Edit: of course you can avoid the cross-browser issue by having your server get the content from the original server, and having the browser get it from your own server. More work, but it's not cross-browser anymore.

PhantomJS: submit a form

I am filling out and submitting a form using PhantomJS and then outputting the resulting page. The thing is, I have no idea if this thing is being submitted at all.
I print the resulting page, but it's the same as the original page. I don't know if this is because it redirects back or I didn't submit it or I need to wait longer or or or. In a real browser it sends a GET and receives a cookie, which it uses to send more GETS before eventually receiving the final result - flight data.
I copied this example How to submit a form using PhantomJS, using a diferent url and page.evaluate functions.
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
//Load Login Page
page.open("http://www.klm.com/travel/dk_da/index.htm");
},
function() {
//Enter Credentials
page.evaluate(function() {
$("#ebt-origin-place").val("CPH");
$("#ebt-destination-place").val("CDG");
$("#ebt-departure-date").val("1/5/2013");
$("#ebt-return-date").val("10/5/2013");
});
},
function() {
//Login
page.evaluate(function() {
$('#ebt-flightsearch-submit').click() ;
# also tried:
# $('#ebt-flight-searchform').submit();
});
},
function() {
// Output content of page to stdout after form has been submitted
page.evaluate(function() {
console.log(document.querySelectorAll('html')[0].outerHTML);
});
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 50);
The site of interest is rather complicated to scrape. I logged the HTTP traffic from the US KLM site and got this:
GET /travel/us_en/apps/ebt/ebt_home.htm?name=on&ebt-origin-place=New+York+-+John+F.+Kennedy+International+%28JFK%29%2CNew+York&ebt-destination-place=Paris+-+Charles+De+Gaulle+Airport+%28CDG%29%2C+France&c%5B0%5D.os=JFK&c%5B0%5D.ost=airport&c%5B0%5D.ds=CDG&c%5B0%5D.dst=airport&c%5B1%5D.os=CDG&c%5B1%5D.ost=airport&c%5B1%5D.ds=JFK&inboundDestinationLocationType=airport&redirect=no&chdQty=0&infQty=0&c%5B0%5D.dd=2013-07-31&c%5B1%5D.dd=2013-08-14&c%5B1%5D.format=dd%2Fmm%2Fyyyy&flex=true&ebt-cabin-class=ECONOMY&adtQty=1&goToPage=&cffcc=ECONOMY&sc=false HTTP/1.1
Your injected values for the form elements are not what their server is looking for.
Inside page.evaluate(), you are sandboxed, but the sample code includes a hook to get sandboxed console activity onto the external console. For other debugging, you can also include object inspectors, etc., but they have to be injected into the page or part of the code passed into evaluate().

Get JavaScript Variable Value in a PHP Variable?

I have this JavaScript function which is getting a value from a select option in HTML:
<script type="text/javascript">
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var str=xmlhttp.responseText;
var splitstr=str.split('||');
document.getElementById("txtHint").innerHTML=splitstr[0];
document.getElementById("txtval").innerHTML=splitstr[1];
}
}
xmlhttp.open("GET","getdetails.php?q="+str,true);
xmlhttp.send();
}
</script>
Now, str is the JavaScript variable I want to take its value and put it into a PHP variable.
I am using this, but it is not working:
$grade = "<script language=javascript>document.write(str);</script>";
echo $grade;
What is the correct way to do this?
PHP runs on a web server, so it will only execute when the page loads. So the above statement will not work as it runs within the function which is called after page load.
To achieve what you want, you can send str to a php file via ajax call and store it in a session variable. & then whenever you need the variable call another ajax function which will retrieve the session value.
You can use jQuery to handle AJAX calls.
Make sure you include this line in your html page.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Use the javascript to make your call to PHP and sent your str data.
function uploaddata(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
var fd = new FormData();
fd.append('data1', str);
try {
$.ajax({
url: 'dosomething.php',
data:fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
var response = $.parseJSON(data);
if (response.code !== '0'){
alert(response.description);
}
else {
alert(response.description);
};
},
error: function(jqXHR, error, errorThrown) {
alert(jqXHR.responseText);}
});
}
catch (ex) {
}
}
At server side create the dosomething.php will make the process you need.
<?php
// get your data at server side
str = $_POST['data1'];
// do processing
// return answer to browser
$ans = ['code' => '0', 'description' => 'Everything are ok'];
echo json_encode($ans);
return;
?>
At your javascript the success portion will be activated and you can use the code and description to build your logic.