Roku remote in javascript - javascript

I am get errors in the web console for my roku remote control script. The javascript is as shown here:
<script>
function rokuSend(RokuAccess) {
xhr = new XMLHttpRequest();
xhr.onload=function() { alert(xhr.responseText); }
xhr.open("POST", RokuAccess);
xhr.send();
}
function rokuKeySend(keyVal) {
rokuSend("http://" + document.getElementById('RokuIP').value + ":8060/keypress/" + keyVal);
}
I supply the IP address for the Roku using:
<form id="Roku"><input type="text" id="RokuIP"></form>
When ever I press a key on my web based remote it send a command, to simplify things I will be using the SAME function to send key presses as well as other commands. So one of the functions called "rokuKeySend()" simply constructs the proper string that is needed to send a command issued by a key press. The second function "rokuSend()"sends the command to the Roku. Later additional commands will be sent to collect data from the Roku so I will create more functions that use "rokuSend()". For now I use the following buttons (these will later be replaced with images), for now they work fine as proof of concept:
<button type="button" onclick="rokuKeySend('Back')">Back</button>
<button type="button" onclick="rokuKeySend('Home')">Home</button>
<button type="button" onclick="rokuKeySend('Up')">Up</button>
<button type="button" onclick="rokuKeySend('Left')">Left</button>
<button type="button" onclick="rokuKeySend('Select')">Select</button></td>
<button type="button" onclick="rokuKeySend('Right')">Right</button>
<button type="button" onclick="rokuKeySend('Down')">Down</button>
<button type="button" onclick="rokuKeySend('InstantReplay')">InstantReplay</button>
<button type="button" onclick="rokuKeySend('Info')">Info</button>
<button type="button" onclick="rokuKeySend('Rev')">Rev</button>
<button type="button" onclick="rokuKeySend('Play')">Play</button>
<button type="button" onclick="rokuKeySend('Fwd')">Fwd</button>
<button type="button" onclick="rokuKeySend('Backspace')">Backspace</button>
<button type="button" onclick="rokuKeySend('Search')">Search</button>
<button type="button" onclick="rokuKeySend('Enter')">Enter</button>
After placing the IP into the input of the form, I can press ANY of the buttons and they do work. However they 'visually' depress when clicked by a mouse, but do not return from the depressed state. Upon checking the web console of the browser I found an error. This error is likely the reason I do not get return from the depressed state. How do I fix this? The error is listed below:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://xxx.xxx.xxx.xxx/keypress/KEY. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
In the above error 'xxx' represents the IP and 'key' represents the key that was pressed.

Its mentioned in the error, CORS Header is missing. Cross Object Resource Sharing(CORS) requires to add header "Access-Control-Allow-Origin" in the request. You can try to add this header in the request-
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
If its not working, you have to create something proxy kind of solution. You can find more details here and here regarding CORS and fixing the error.

Related

AJAX always fails after some time

I tried everything and searched everywhere but i can't wrap my head around this...
I have a button in a form that triggers on click a javascript function, which in turn makes an AJAX request to my server.
The problem is no matter what i do the request is made but the .fail method always executes after a few seconds and i get no error. I am sure my server sends no response (it's a server on an ESP32 which relies on the ESPAsyncWebServer, code below) and to add to this, the network inspector on both Firefox and Safari shows no communication.
I tried all sorts of things, from adding timeout:0 and cache:false to the AJAX call, to changing to GET instead of POST as the AJAX method, as well as preventing the default event on the button by returning false or using .preventDefault() in the javascript function but nothing works. What am I missing?
Here's the HTML:
<form>
<div class="form-row align-items-center mt-4">
<div class="form-group col-md-8">
<label for="newCode">Codice</label>
<div class="input-group">
<input type="text" class="form-control" id="newCode" placeholder="12345678">
<div class="input-group-append">
<button type="button" class="btn btn-secondary" id="learnCodeButton" onclick="learnNewCode(); return false;">Rileva</button>
</div>
</div>
</div>
<div class="form-group col-md-4">
<label for="newAlarmTriggerDelay">Delay Allarme (s)</label>
<input type="text" class="form-control" id="newAlarmTriggerDelay" placeholder="60">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="newDescription">Descrizione</label>
<input type="text" class="form-control" id="newDescription" placeholder="Studio Interno">
</div>
</div>
<div class="d-flex justify-content-center">
<button type="submit" id="saveSensor" onclick="saveSensor()" class="btn btn-lg btn-primary mt-4 pl-5 pr-5">Salva</button>
</div>
<div class="d-flex justify-content-center">
<button type="button" id="removeSensor" onclick="removeSensor()" class="btn btn-lg btn-link mt-2 text-danger">Rimuovi</button>
</div>
</form>
the javascript function:
function learnNewCode() {
document.getElementById("learnCodeButton").className = "btn btn-warning";
$.ajax({
method: "POST",
url: "/learnCode",
dataType: "json",
})
.done(function(returnedData) {
//substituteInField("newCode", returnedData["newCode"]);
})
.fail(function(jqXHR, textStatus, errorThrown) {
//substituteInField("newCode", "Learn code failed - Retry");
console.log("jqXHR response: " + jqXHR.responseText);
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
}).always(function() {
document.getElementById("learnCodeButton").className = "btn btn-secondary";
});
}
the code on the ESP32:
server.on("/learnCode", HTTP_POST, [](AsyncWebServerRequest * request) {
Serial.println("POST /learnCode");
});
and finally the console log (Firefox):
XHR POST http://192.168.1.105/learnCode
jqXHR response: undefined
Status: error
Error:
Thank you for your help.
You are not sending a response from your ESP32 Server.
The client is probably timing out.
Try adding a response (Note the response type here is text/plain adjust accordingly).
server.on("/post", HTTP_POST, [](AsyncWebServerRequest *request){
request->send(200, "text/plain", "Post route");
});
So i actually solved this with some help... the fact is that the timeout option in the AJAX request refers to the receipt of the request by the server and not to the time that the server takes to send a response.
To explain this better, when the AJAX request is sent to the server, the server acknowledges the receipt of the request to the client. The time between the request being made and the server acknowledging its receipt is what can be regulated by the timeout option.
After acknowledging the receipt, if the server doesn't serve a response in less than a few seconds, the AJAX call fails.
In my case, the ESPAsyncWebServer probably acknowledges the receipt before calling the server.on() method so if I send no response or the response takes too much time to deliver the AJAX call fails. In fact, if i load the website, power off the ESP, and after that try to make the call it won't fail but wait endlessly, as the timeout is by default infinite.
The solution will probably be send a call to activate the methods i need on the ESP and then poll the server periodically until i get an answer.

The quote isnt appearing on the webpage

What I'm trying to do is when the button is click the quote appears on the webpage but its not working. I am using a api
$(".btn").on("click",function(){
$.ajaxSetup({cache:false})
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&callback=",function(data){
$(".quote").html(data[0].content + "-" + data[0].title);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class = "container-fluid">
<div class = "row"></div>
<div class = "text-center quote-box">
<h1 >Random Quote Generator</h1>
<p class = "quote"> Click the button to get a random quote</p>
</div>
<div class = col-md-4 id = quote-button>
<button class="btn btn-primary" type="submit" id = quote-button>New Quote</button>
<button class="btn btn-primary" type="submit" id = quote-button><i class = "fa fa-twitter">Twitter</i></button>
</div>
</div>
</div>
Change http to https. Issue might be due to "Mixed Content", http and https which will be blocked by your browser.
$(".btn").on("click",function(){
$.ajaxSetup({cache:false})
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&callback=",function(data){
$(".quote").html(data[0].content + "-" + data[0].title);
});
});
Check this plunk
Mixed content occurs when initial HTML is loaded over a secure HTTPS
connection, but other resources (such as images, videos, stylesheets,
scripts) are loaded over an insecure HTTP connection. This is called
mixed content because both HTTP and HTTPS content are being loaded to
display the same page, and the initial request was secure over HTTPS.
Modern browsers display warnings about this type of content to
indicate to the user that this page contains insecure resources.
The request is working but the browser is blocking it because it is a cross origin request. Either get the server administrator has to enable cors or check if a JSONP request is supported.

Getting around CORS with embedded google forms

I'm trying to send form data to google via an embedded form.
I found this post that seems to answer my question but I'm getting CORS errors. Is there a way to solve this?
Other posts seem to say that CORS isn't an issue but I'm getting the errors.
Here is my code:
-JS-
function ajax_post() {
var field1 = $('#email').val();
$.ajax({
url: "https://docs.google.com/forms/d/e/xxxxxxxxxxxxxxxxxxxxxx/formResponse",
data: {"entry.xxxxxxxxxx": field1},
type: "POST",
dataType: "xml",
statusCode: {
0: function() {
//Success message
},
200: function() {
//Success Message
}
}
});
}
-HTML-
<form id="emailForm" target="_self" onsubmit="" action="javascript: ajax_post()">
<input id="email" type="text" autocomplete="off" tabindex="0" name="entry.xxxxxxxxxx" required>
<button id="send" type="submit">Submit</button>
</form>
The “No 'Access-Control-Allow-Origin' header is present on the requested resource” message indicates that responses from https://docs.google.com/forms/d/e/xxxx/formResponse URLs currently don’t include the Access-Control-Allow-Origin response header, so browsers won’t allow your frontend JavaScript code to access the response.
Given that, from your frontend code there’s no way you can tell if the POST request succeeds or not. But barring any other problems, it seems like the request will always succeed. If the request doesn’t reach the server at all (due to some network error) then you’ll hit a different failure condition that is observable from your frontend code so you can actually catch it.
So the way you know the request has successfully reached the server is just that you don’t get any other failure that’s observable from your frontend code.
I've found that it's actually easier to just POST the form with a hidden iframe as its target, and capture that iframe reload when the response is submitted.
For example, if this is your form:
<form id="my-form" target="my-response-iframe" action="https://docs.google.com/forms/u/1/d/e/<YOUR-ID>/formResponse" method="post">
<input type="text" name="entry.12345678" value="" required>
<input type="submit">
</form>
Then include an iframe on the same page, with the same id AND name you put as target in the form:
<iframe id="my-response-iframe" name="my-response-iframe"></iframe>
When the form is submitted, it should reload that iframe with the "Your response has been recorded." page from Google. We can catch that reload with JavaScript, so include this after your form and iframe:
<script type="text/javascript">
// set the target on the form to point to a hidden iframe
// some browsers need the target set via JavaScript, no idea why...
document.getElementById('my-form').target = 'my-response-iframe';
// detect when the iframe reloads
var iframe = document.getElementById('my-response-iframe');
if (iframe) {
iframe.onload = function () {
// now you can do stuff, such as displaying a message or redirecting to a new page.
}
}
</script>
You can't check whether the response was submitted correctly because you can't inspect the contents of a cross-origin iframe (that'd be a huge security risk), so just assume that if this iframe reloads, the response was ok.
You can hide the iframe with the following CSS:
visibility: hidden
height: 1px;
Much cleaner if you ask me, with no console errors or failed requests.

How to listen the 400 (Bad Request) with Angular *ngIf?

I won't paste any code, since this is a general question. I need to figure out how to listen if nothing returns. I can't get any objects, since nothing exists. I only receive on my GET request a message "400 (Bad Request)".(console).
How can I disable a button if there is a "400 (Bad Request)" (nothing exists)?
Is there a way to listen this on frontend?
Thanks
In Angular2 you would need to capture the error from the response.
badRequest: boolean = false;
this.appService.myHttpCall.subscribe(
data => // do something with success,
error => {
if(error.status == 400){
this.badRequest = true;
}
});
And use the result in your template. If you really want to go the *ngIf route you would do this:
<button *ngIf="badRequest" type="button" disabled>My Button</button>
<button *ngIf="!badRequest" type="button">My Button</button>
You would essentially have to code two buttons, both with *ngIf statements to get the result you want.
If you want to use the [disabled] attribute you would do this:
<button [disabled]="badRequest" type="button">My Button</button>
However, I would not disabled a button if a BadRequest happens, because then how would the user resubmit the form after correctly filling it out? For example, if the user leaves a required field blank, the server returns a BadRequest and disables the button. Then the user cannot correct the missing field and re-submit the form.
What I would do instead is to toggle the button's disabled attribute based on the validity of the form like this:
<form (ngSubmit)="onSubmit()" #myForm="ngForm">
...inputs....
<button type="submit" class="btn btn-success" [disabled]="!myForm.valid">SUBMIT</button>
</form>
Hope this helps.

How to pass user id in javascript or in ajax to fetch record from database if using laravel framework?

I have fetched task title from database. Now I want if I click on task title it should show description of that particular task on the same page using toggle.
I have tried AJAX and JavaScript but found no result. Can anyone help by providing a small example related to this topic?
<button type="button" id="button" value="submit" class="btn btn-warning" onclick="javascript:fload($usermm->id);">{{ $usermm->TaskTitle }}</button>
This should work:
<button type="button" id="button" value="submit" class="btn btn-warning" onclick="javascript:fload({{{ $usermm->id }}});">{{{ $usermm->TaskTitle }}}</button>
Use {{{ $usermm->TaskTitle }}} (3 curly brackets instead of 2) to make sure you escape the data in the view.
UPDATE
I'm not going to write all code for you but I can give you a clue:
function fload(id)
{
[...]
var url='mytaskurl?id=' +id;
[...]
}
UPDATE #2
Here is an example of using Ajax with Laravel:
http://blog.igeek.info/2013/using-ajax-in-laravel/

Categories