AJAX wait until file exist on another server - javascript

I'm developing a website based in to servers. One is a free host and another is a Raspberry Pi. When you access a webpage in the free host, you get a form where you enter a link. The link is send to the Raspberry Pi which is permanently running a script that downloads some content of the link recieved and saves a big txt file. The script takes a bit to load (30 secs aprox) so I want to create a Javascript script in the primary page (free host one, with the form) wich shows a load icon and checks in the raspberry downloads folder until the file exists.
I think AJAX will be the best for this. The workflow is:
user access form.php and enters a link
the form is send directly to the RPi
the RPi begins to download things and returns the user to the refferrer page with the get parameter id=
here the ajax code begins to work checks into an url if .txt exists if it exists, it shows the download link else, it waits checking until it gets a 200 status code (This is what i need)
I know the problem with javascript and different servers so i've created a php script named check.php in the same server and folder of form.php which gets id as parameter and return 200 or 404 so the ajax code just needs to get that answer and act in consecuence
How can I do it? I'm new to AJAX, I know just a bit of Javascript. Could you help me withe the AJAX code?
My form.php?id= page:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>downloader</title>
</head>
<body>
<div id="content">
<?
if (!$_GET){
?>
<form action="<<rpi server>>" method="post">
URL: <input type="text" name="link">
<input type="submit" value="Download">
</form>
<?
}else{
?>
<script>
$.ajax({
type: 'POST',
url: '/check.php',
data: {'id':'<? echo $_GET['id']; ?>'},
//check if response is 200 or 404, if it's 404 keep checking every second, else show mesage
}
});
</script>
<?
}
?>
</div>
</body>
</html>

Use this
function checkFile()
{
$.ajax({
type: 'POST',
url: '/check.php',
data: {'id':'999'},
error : function(){
setTimeout(function(){ checkFile(); }, 3000);
},
success : function(data) {
//do whatever you want
}
});
}
$(function() {
checkFile();
});

Related

PHP/HTML, AJAX is not calling/executing PHP file

Before I opened this question, I searched the entire internet on a solution. Maybe it is me or my solution. Sorry for that.
The situation is, I have a web app which is build with PHP and interacting with the database through functions. Every page is a php in which html code is executed.
The problem is, when I want to implement Ajax to update data without refreshing a page, the PHP file is not being executed when the button is clicked.
The javascript has two functions:
Alert serialized data of the button (works)
Run php script with Ajax (doesn't work)
Html Header
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
Im using bootstrap-table, one of the column is a button which has the following content:
<form id="form" class="favourite-form" method="post"><input style="display:none" type="hidden" id=5 name="subject_id" value=5 ><input type="submit" name="submit" value="Button"></form><div id="response"></div>
When clicked on the button the following alert is popping up:
The script file is included in the php file:
include("favorite_ajax.html");
The script file has the following content:
$(document).on('submit', '.favourite-form', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var data = $(this).serialize(); //"this" represents the form element in this context
alert(data); // this alert works
$.ajax({
method: "POST",
url: "process.php", // calling this php file doens't work
data: data,
success: function(data) {
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown) //gracefully handle any errors in the UI
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
Finally the php file has one single simple function which inserts (dummy) data. The php file is tested and does not contain any errors.
<?php
insertDummyData(1, 123);
?>
In another topic I also read checking the logs. When I press the button, there is also no record being added in the logs.
Im cursious, what am I doing wrong? Spend like days to fix this, until now no results :(
put an error log in "process.php" to make sure that it's actually being called, if it's not being called, as others suggest, you may have path, permissions or script errors.
what does insertDummyData/process.php actually do? It must echo something as if it were writing to the page for the AJAX call to get a non-empty result. For example, in process.php
<?php
$new_data = my_function_which_does_stuff_to_posted_data($_POST['data']);
echo json_encode($new_data);
exit();

GET in HTML and Not PHP

I want to process a GET extension in a HTML page and not a PHP page.
I have looked through the internet and not found anything.
URL = examplesite.com?id=1234
I assume this would go to the index page on the domain. As the index page is a HTML page, is there a way to get the details of the extension transferred to another link I have in the html script that emails me when someone looks at the site.
<script src="trigger.php">
</script>
This way I can customise the extension to know where the person found me. id=1234 is from twitter, id=2345 from FB etc.
Then i could place the extension onto the script to send me the email.
<script src="trigger.php?id=1234">
</script>
Is there a way to get the HTML page to process extension and pass it on in a variable of some sort.
Thanks in advance
Robert
You can do it in Javascript in the HTML. window.location.search contains the query string from the URL.
You can then use an AJAX request to send the query string to your server script.
<script>
$(document).ready(function() {
var script = 'trigger.php' + window.location.search;
$.get(script);
});
</script>
This is not possible with plain HTML. By definition, HTML is not dynamic. It can't process anything you want. However, there are three options.
Firstly, you can use JavaScript and AJAX calls to make another HTTP request to examplesite.com/processID.php (or another PHP page) which will process the request.
Another way to use JavaScript would be to use a client side API such as MailChimp to send the email directly from the users computer.
Or you could just redirect your root page for your domain examplesite.com to lead to index.php. I'm sure that's very easy to configure in mainstream servers such as Apache or Nginx. Otherwise please ask another question on Server Fault about how to set this up using your server.
If you are using a PHP hosting provider, they should also be able to help redirect the root page. If you don't have any access to PHP on your hosting provider, you're out of luck. You must only use the second option.
Do it with ajax
<form id="form1">
<input type="text" />
<button type="submit" id="sendforms">send</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#sendforms").click(function() {
var combinedFormData = $("#form1").serialize();
$.get(
"trigger.php",
combinedFormData
).done(function(data) {
//alert("Successfully submitted!");
$("#result").html(data);
}).fail(function () {
//alert("Error submitting forms!");
})
});
});
</script>

Jquery Variable with ajax

I am working on a project and I am trying to use jquery to send a variable to php. This a file called test2.php that I have been using to test out the code, can anyone tell me what I am doing wrong because it should be printing out the variable when you click on the button but nothing is happening.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var something="hello";
$("button").click(function(){
$.ajax({ url: 'test2.php',type: "GET", data: { q : something }});
});
});
</script>
</head>
<body>
<button>Get External Content</button>
</body>
</html>
<?php
if(isset($_GET['q']))
{
$q = $_GET["q"];
echo $q;
}
?>
Your code looks generally correct but you have to remember that an AJAX call sends the data "Asynchronously", which means when you click on the button this data is being sent to a separate instance of "test2.php" for processing. It is not reloading the current page with this new data.
The "test2.php" code you are viewing in browser is only run on the server side once when you first start up the page, and there is no 'q' in the '$_GET' variable at that time. The AJAX request is sending data to a separate instance of the same "test2.php" file and it is receiving some data back, but it is not using that information to load anything into your browser.
Depending on what you are trying to achieve there are many different solutions. You could use what you receive from your AJAX request to update information on the page like so:
$.ajax({
url: "test2.php",
type: "GET",
data: { q: something},
success: function (response) {
// do something with 'response' here
}
});
Or you could have the button instead be a simple <a> tag that reloads the current page in browser with information stored in '$_GET' like so:
Button
Then when your PHP code looks for 'q' it would actually find it in the $_GET variable because you reloaded the page.

Automate Log In on Website (Autofill and Submit)

I am trying to visit a website and log in automatically.
After this, I want to return whether or not this was a success or failure, but I can't get it to work. The page loads blank and nothing happens.
Note: I have deliberately greyed out the URL.
Below is my attempt,
<HTML>
<HEAD>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>
<TITLE>Login</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
<script type="text/javascript">
$(document).ready(function () {
runLogin();
});
function runLogin(){
alert("start");
if (window.location.indexOf("url") > -1) {
jQuery("#j_username").val("username");
jQuery("#j_password").val("password");
jQuery("#loginForm").submit();
}
}
</script>
If you want to test your login form, use Protractor or other e2e test framework, but this way does not seem very safe.
http://angular.github.io/protractor/
It's loading a blank page because your back-end script isn't redirecting back to the page you started on. One option is to send the current webpage URL as an extra field to the login form so that it can redirect back after it has logged in. This will require you to refactor your back-end code so that it can handle this extra information (not really possible if you're using j_security_check). Another option is to make an AJAX request to your login page so that it doesn't actually redirect the page, it just submits the form quietly and then JS handles the response.
If you want to add the URL of the current page to the login request, do this:
function runLogin() {
if (window.location.indexOf("url") > -1) {
jQuery("#j_username").val("username");
jQuery("#j_password").val("password");
jQuery("#loginForm").append(
'<input type="hidden" name="url" value="'+window.location.href+'"/>'
);
jQuery("#loginForm").submit();
}
}
If you want to use AJAX to send a login request:
function runLogin() {
var $form = $("#loginForm");
$.post($form.attr("action"), $form.serialize(), function(data) {
// login successful/unsuccessful message displays
// depending on what "data" contains
});
}

Cannot get ajax calls to work with phonegap

I am converting my webapp from PHP / HTML to JS/HTML so that it can work with phonegap. I am keeping the php server side files separate and on the server. I am having issues with executing AJAX calls from my local HTML file. When i check the console on chrome, it doesn't show any errors, but the ajax call doesn't return any value either. Ive simplified the issue so that people can easily understand what the problem is.
My JS code is
<head>
</head>
<body>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$.ajax({
url: "http://www.betsmart.org/betsmart/models/test.php",
method: "get",
dataType: "json",
crossDomain: true,
success: function(result){
console.log(result);
$("#text").html(result);
}
});
</script>
<h1 id="text"></h1>
</body>
My PHP code in test.php is
<?php
header("Access-Control-Allow-Origin: *");
echo "test";
?>
The success callback isn't executing. I understand the same origin policy will probably come into play here but i thought that doesn't matter with Phonegap.
Please do let me know where i'm going wrong or an alternate way to do this. If i have to use jsonp, what will be the client side and server side code?
Thanks
Gagan

Categories

Resources