Making a Javascript Loop request in rails view - javascript

I need to download a file from a link I am given. In order to do this I must make a get request to that link. It can have 3 states:
1. Code 200 and the download will begin once the request landed
2. Code 202 which means I must repeat the request because the file is being uploaded
3. Error code and I must create a dom element that shows that.
How it works:
I make a request to this rails action:
def by_month
export_form = Commissions::ByMonthForm.new(current_user)
if export_form.submit(params)
#export = export_form.export
else
show_errors export_form.errors
end
end
This in turn starts the file upload. Which I don't know when it's ready(depending on how big the file it is). Now I must create a javascript get request to a link that follows the indications I have given at the beginning of the post. And integrate it in the by_month.html.erb view from rails . The javascript I managed to write is:
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
httpGetAsync(theUrl);
}
else {
make_error_css();
}
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
However I don't think it works. Any ideas of how I can do this?(redirect_to_main and make_error_css are functions that I will implement myself later).

Update As per the comments below
Can you try this,
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
setTimeout(
makeRequest(theUrl),
3000);
}
else {
make_error_css();
}
}
}
//makeRequest(xmlHttp, theUrl);
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
function makeRequest(theUrl){
httpGetAsync(theUrl);
}
makeRequest() is where the request is made again if the status is 202.

Related

POST value from JavaScript to PHP via AJAX without jQuery

I'm trying to send a JavaScript variable to be processed server-side by PHP then echo back the result. My ajax request results in readyState == 4 and status == 200 yet PHP keeps echoing back an empty array/value.
I'm pretty sure this comes from my Ajax call sending an empty request but everything I tried didn't work, so maybe I'm going all wrong here.
JS (from index.html) :
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.send(valueToSend); //this line is probably not sending the value the way I expect it to
}
}
PHP (from test.php) :
echo $_POST['name']; //simple echo to check if PHP indeed receives valueToSend
My last try was to change request.send(valueToSend); with .send(encodeURI('name=' + valueToSend)); but it just made the ajax call redirect the page location to a non-existing one.
What am I doing wrong ?
There are few things wrong in your code, such as:
Even through you defined send_ajax() function, you didn't call it anywhere in the code.
With POST request you need to send an HTTP header setRequestHeader() along with the request, like this:
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
echo $_POST['name']; in test.php page won't work because name is undefined here. Your send() method call should be like this:
request.send("name="+valueToSend);
So the complete JavaScript code would be like this:
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("name="+valueToSend);
}
}
send_ajax();

Using AJAX to execute a PHP script through a JavaScript function

I have an anchor link with no destination, but it does have an onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
But clicking the link just changes the URL to http://localhost/.
I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Can you please provide your : del_post.php file?
Normally you can show a text or alert in a
<div id="yourname"></div>
by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("yourname").innerHTML = xmlhttp.responseText;
}
This response is coming from your PHP file for example :
function remove_record(ARG){
if ($condition==true)
echo "TRUE";
else
echo "FALSE";
}
You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:
<script>
function deletePost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Do something if Ajax request was successful
}
};
xhttp.open("GET", "del_post.php", true);
xhttp.send();
}
</script>
You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.
Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:
What file to call
What to do with the response from the file you called
What to do if an I/O error happens
So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) - and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
//textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}
function ohNo()
{
//stuff like URL not found, etc.
alert("I/O error");
}
And now that you're armed with that, this is how you compose the real call inside the function you called at the <a>:
function functionThatReallyCallsAjax()
{
//there are probably many scenarios but by having this extra function,
//you can perform any processing you might need before the call
doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}
One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the 'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)

My IP gets blocked for odd reasons by my server each time i do ajax continuous update

Everytme when i call ajax and i use timeout to repeat the ajax function, after a few minutes, i can't have access to my website, it;s like my IP address gets blocked from my server, by the way i am using 000webhost for hosting my server. The code is below .Can someone assist me and tell me what i can do solve this problem without telling me to use websockets/comets, i want to use AJAX for very frequent update maybe up to 10 seconds. Not a most but it will be great if someone can show solutions without the use use of JQuery Thank you.
function display_message(user,id){
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
/**********************************************************/
var data = "user="+user+"&id="+id;
xhr.open("POST", "message_read.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("message_box").innerHTML =xhr.responseText;
mymessage =setTimeout(display_message(user,id), 5000);
} else {
alert('There was a problem with the request.');
}
}
}
}

javascript : JSON obj not coming

What is the issue in below script.Here alert "33here" is coming but am not getting my json object.alert(jsontext) is coming blank.if i hit this URL in browser then i am getting JSON object.
xmlHttp = new XMLHttpRequest();
xmlHttp.overrideMimeType("application/json");
alert('11here');
xmlHttp.open( "GET", "http://<hostname>/appsuite/api/login", true );
alert('22here');
alert(xmlHttp);
xmlHttp.send();
alert('33here');
var jsontext= xmlHttp.responseText;
alert(jsontext);
Tried as per suggestions but not working.I am new in javascript / ajax.Any issue in this ?
xmlHttp = new XMLHttpRequest();
xmlHttp.overrideMimeType("application/json");
alert('Hi 11here');
xmlHttp.open( "GET", "http://<hostname>/appsuite/api/login", true );
alert('Hi 22here');
alert(xmlHttp);
xmlHttp.send();
alert('Hi 33here');
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
}
Ajax runs asynchronously. You can't depend on when the request from .open will complete or even if it will complete. Any code that depends on the value of an ajax request must be done in the request callback.
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
}
A good place to start is looking at the examples provided by MDN: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
function alertContents(httpRequest) {
try {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
catch( e ) {
alert('Caught Exception: ' + e.description);
}
}
After the request status reached 200 and the ready state is 4 the response is filled.

xmlHttpRequest.send(Params) not working in tomcat 7

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.

Categories