Apache file system does not respond my AJAX request - javascript

I've written some java script that sends an AJAX request to get the HTML page in my computer and display on the screen.
But, every time I made changes on the HTML file like adding more div, picture or some simple text. The server (localhost) always response me back an old version of the HTML file.It looks like I haven't made any change to the HTML file (but actually I did).
For example, if this is the old HTML file.
<div class="login">
<form name="login_form" method="post" action="#">
</form>
</div>
After I made some changes
<div class="login_123245">
<form name="login_form" method="post" action="#">
<input type="submit" name="btn_submit" value="submit"/>
</form>
</div>
Here's the javascript code
function getHTMLPage(directory) {
xmlHttp.open("GET","http://localhost/NewWorkspace/webProject_01/"+directory);
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
//return xmlHttp.responseText;
html_Page = xmlHttp.responseText;
show_response_page2(html_Page);
}
}
};
xmlHttp.send();
}
show_response_page is the function that returns the requested HTML page.
I also found a way to solve this which is not so good solution.
Every time I want to make changes to HTML file, I need to create a new HTML file and change its name which is not so inconvenient for me.
Please help.

Related

Trouble with AJAX within a form

I'm a newbie to JavaScript. I tried to use AJAX from within a form and kept getting "HTTP ERROR 405".
I'd been viewing a video course, so I tested the example code in my environment and it worked perfectly. But the example was not in a form. So I removed the and from my code and the AJAX works. But I need this to work in a form. I want to make several AJAX calls to the server within this one form and need to know what to do to make them work.
Here's the failing HTML code:
<form id="Match_Results" action="#" method="post">
<fieldset>
<legend>Before the Match</legend>
<div id="which_league">
<button id=get_leagues>Get Leagues</button>
<div id="output"></div>
</div>
</fieldset>
</form>
And here's the JS:
document.getElementById('get_leagues').addEventListener('click', loadData);
function loadData() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'leagues.txt', true);
xhr.onload = function(){
console.log('READYSTATE', xhr.readyState);
if(this.status === 200) {
console.log(this.responseText);
document.getElementById('output').innerHTML = `<h2>${this.responseText}</h2>`;
}
}
xhr.onerror = function() {
console.log('Request error...');
}
xhr.send();
This is just the first step in getting this to work, so I'm just pulling in a local text file and using a button. Actual code later will do this automatically, without the button, pulling from a MySQL db via a PHP page. But I can't even get this working.

Pushing a button programmatically to submit a form on another page in Javascript

Please forgive the basic question, I'm very new to Javascript and web development in general. I want to use a script on one page of my site to programmaticaly press a button to submit a form on another part of the site, making a POST request. The html I have to access is the following:
html
<form action="thing.jsp" method="post"> // Beginning of form
...
<input type="submit" id="submit" value="Do something"> // Button code
...
</form>
And I think the Javascript should look something like this:
JS
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', "/stuff.jsp", true);
var params = "???????"; // What do I need to put here?
xhr.send(params);
</script>
From reading around online, my suspicion is that I may just need to get the right value for params? Though if there's another way of achieving the same result (e.g. by just sending a POST request without doing anything to the button), I'd be perfectly happy to go with that.
Thanks in advance for your time and wisdom.
You don't need to use ajax, just use this:
<input type="button" value="GO" id="buttonId" />
<script>
function go() {
document.location.href = 'http://google.com';
}
document.getElementById('buttonId').onclick = go;
</script>
please notice the button type should be 'button', not 'submit'
Using jQuery - a JS library - you can simply send a HTTP GET Request. This can then be picked up in PHP using $_GET['key'] which will hold the value.
$(function() {
$('#unique-id-btn').click(function() {
$.get('file.php', { key: $('unique-id-input').val() }).done(function(response) {
alert(response);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="unique-id-input" placeholder="enter something...">
<button type="button" id="unique-id-btn">Click me</button>
Note, you will need to create the file.php. Inside, it will control what happens with that data being sent across, ie:
$data = $_GET['key'];
echo $data == "foo" ? "bar" : "tell me foo!";
Also note you can only run PHP in a .php file extension, not JSP.

How to modify submitted file client-side in JavaScript/jQuery

I want to modify the file submitted by user on the client side, before it reaches my server. To modify it I want to use Flash applet that would communicate with JavaScript.
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="id_file">
<input type="submit" value="Submit">
</form>
Is it possible to do it? If yes, I would appreciate any tips how should it be done :)
Should I convert it to string? Or maybe JS comes with some functions to make such operations easier?
$( "form" ).change(function(x) {
//pass file input to Flash applet
x.preventDefault();
flashApplet.proceed($('#id_file').value);
});
function callback(modified_file) {
// Flash applet has modified the file
// Now submit the form with a new, modified file
$('#id_file').value = modified_file;
trigger_submit();
}
The file can be either a video, an audio or an image.
Don't use a submit button, instead use a normal button disguised to look like a submit button, and then you can check when the button is clicked, do your stuff, then submit the form via javascript by using
document.getElementById("myform").submit();
I would replace your current html with:
<form action="" method="post" enctype="multipart/form-data" id="myform">
<input type="file">
<button id="submit">Submit</button>
</form>
And then js:
document.getElementById('submit').onclick = function() {
//do your flash stuff
}​;
function callback(){
//here we submit the form
document.getElementById("myform").submit();
// because the file itself has been modified, this is all we need to do.
}
Basically, use a false submit button, to do what you want first.

Avoid form submitting multiple times through Javascript

Let me Clear what title means:
In my code for a validation purpose of one field dependent on field "t1" I need to auto submit my form once (Just Once). But my below code is submitting it infinite times and I know the reason why its happening.
I guess Reason is everytime the form submits again JS in header runs. Please help me avoid this. Following is my code:
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("CheckForm");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("t1");
temp1.value = "Task";
}
document.CheckForm.submit();
}
</script>
</head>
<body>
<form name="CheckForm" id="CheckForm" method="Post">
<input type="text" id="t1" name="t1"/>
</form>
</body>
</html>
I tried stopping it using variable like flag and static variables like arguments.callee.count = ++arguments.callee.count || 1 and placing my CheckForm.submit() line in if clause. But nothing worked. Any advice or help is appreciable.
<html>
<head>
<script>
window.onload = function()
{
var f = document.getElementById("t1");
var temp = document.getElementById("CheckForm.t1");
if(f.name == "CheckForm")
{
var temp1 = document.getElementById("CheckForm.t1");
temp1.value = "Task";
}
if(window.location.search=="")document.CheckForm.submit();
}
</script>
</head>
<body>
<form name="CheckForm">
<input type="text" id="t1"/>
</form>
</body>
</html>
Surely your form is more complex than:
<form name="CheckForm">
<input type="text" id="t1">
</form>
That will not submit anything to the server since there are no successful controls (the only control doesn't have a name).
Since the form is just submitting to the same page, you can submit a hidden value like:
<form name="CheckForm">
<input type="text" id="t1">
<input type="hidden" name="hasBeenSubmitted" value="yes">
</form>
Now when the form submits the URL of the new page will include ...?hasBeenSubmitted=yes so you can look for that value in the URL, e.g.
if (/hasBeenSubmitted=yes/.test(window.location.search)) {
// this page loaded because the form was submitted
}
If it exists, don't submit the form again.
So since you are using a post method the easiest way's to handle this is to ubmitted to a new url , however you seem set on keeping the form submitted to the same url in which case is you are using php (or really any other language) you can check if the http request has a post attribute with a value t1
<?php
if(isset($_POST['t1']){
$your_text=$_POST['t1'];
/*do some string checking to make safe and the throw into your database or mdo whatever you please with data
if you wanted to include the ip address of the user you can get a basic and most likely client ip address like so
$ip_address= $_SERVER['REMOTE_ADDR'];
if you are handing a mulitpage form look into php session or similar tech ... cookies is kind of over kill for this scenario
then include a succes page as the form has been submitted
or you could end php with this tag ?> and then have your html and start again with <?
*/
include 'form_submitted.php';
}else{
//this would be the html page that you included in your question and can be handle in same ways as form submitted
include 'my_form.php'
}
?>
Ip address may not be best included as it would stop 2 user from filling out the form if they are in the same LAN for eg. 2 people in same office or same house (if your page is acttual on the worldwide web).
I would take a look at #RobG answer as it he is basically suggesting the same type of thing with a get instead of post
ANyways hope this helps

How do I process forms (front and back end) on the same page?

I currently have a form that looks like this (using Bootstrap):
I've traditionally processed the form via post to another php file like so
<form action="complete.php" method="post" class="form-inline" role="form">
However, it kind of ruins the user experience when they're taken to a different page, and I've seen something before, where after submitting a form, the text just changed if it was valid. So, the text and form of the above image might just be replaced with "Thank you, your email has been accepted" if they offer a valid email.
So this question is two-part:
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
Second, how do I do this on the front end? Is there a common reference term for this kind of action in JS?
Answering either part of this (both if you can!) would be wonderful. If you have reference documents for me that aren't too complicated (I'm new to this), I'd be more than happy to read them too.
Thank you!
I'm going to extend on what Sam Sullivan said about the Ajax method.
Ajax basically runs any script in the background, making it virtually unnoticeable to the user. Once the script runs you can return a boolean or string to check if the result is true or false.
JS:
function validateForm(){
$.ajax({
type: 'POST',
url: '/path/to/processForm.php',
data: $('#yourForm').serialize(),
success: function(output){
if(output){ // You can do whatever JS action you want in here
alert(output);
}else{
return true; // this will redirect you to the action defined in your form tag, since no output was found.
}
}
});
return false;
}
Then in your processForm.php script, you validate the data through $_POST. Whatever you echo out in this script, will be your output.
For more, http://api.jquery.com/jquery.ajax/
Either include the PHP and form logic on the same page:
<?php
if(isset($_POST['submit'])) {
// Submit logic
echo 'Success';
}
?>
<form action="" method="POST">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
Or you can submit it with AJAX:
<form action="" method="POST" onsubmit="submitForm(this); return false;">
<!-- etc -->
<input type="submit" name="submit" value="Submit" />
</form>
<script type="text/javascript">
function submitForm(form)
{
// This can use AJAX to submit the values to a PHP script
}
</script>
If you have jQuery, you don't need to use an inline event handler (which is better):
<script type="text/javascript">
$('form').submit(function(event) {
event.preventDefault();
$form = $(event.target);
// AJAX here
});
</script>
This should be enough to get started..let me know if you have specific questions.
Change the form to
<form action="[whatever the page name is]" method="post" class="form-inline" role="form">
First, how do I do this on the backend? I'm using php for simplicity since it was so easy to install.
At the top of the page, add
<?php
if(isset($_POST)){
// Check for the $_POST variables and process
// $content = "<div> ... </div>" // Then echo out the content in place of the original for
}
?>
You can just put form action="filename-of-the-form-processor" or leave it blank for same page. If you can't avoid to put php module on the same page where your form reside make a view.php file then just include it.
index.php <- where form process happends
index.view.php <- where form tags reside so you will have a cleaner line of codes.
Note: this is not the best way to do it.

Categories

Resources