Trouble with AJAX within a form - javascript

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.

Related

don't get my data with XMLHttpRequest POST across [duplicate]

I am trying to submit a form via ajax using the post method and a FormData object.
Here is a simplified version of the JavaScript:
var form=…; // form element
var url=…; // action
form['update'].onclick=function(event) { // button name="update"
var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var formData=new FormData(form);
formData.append('update', true); // makes no difference
xhr.send(formData);
xhr.onload=function() {
alert(this.response);
};
};
The form has:
a button (type="button" name="update") to run the script
no action and method="get"
My PHP script has the following:
if(isset($_POST['update'])) {
print_r($_POST);
exit;
}
// more stuff
print 'other stuff';
When I try it, the PHP falls through to the rest of the code, and I get the other output, rather than what I expect from the print_r statement.
I have tried the following variations:
new FormData() (without the form). This does work if I add the update data manually.
new FormData(form). This does not work, whether I add the update manually or not.
changing the form method to post.
Firefox, Safari & Chrome on MacOS; all current versions.
The from itself looks something like this:
<form id="edit" method="post" action="">
<p><label for="edit-summary">Summary</label><input id="edit-summary" name="summary" type="text"></p>
<p><label for="edit-description">Description</label><input id="edit-description" name="description" type="text"></p>
<p><label for="edit-ref">Reference</label><input id="edit-ref" name="ref" type="text"></p>
<p><label for="edit-location">Location</label><input id="edit-location" name="location" type="text"></p>
<p><button type="button" name="update">OK</button></p>
</form>
What should I do to submit the get this to work?
No jQuery, please.
The content type when sending a FormData object is multipart/form-data not url encoded.
Further more the proper boundary must be set for the request, which the user is unable to do. For this XMLHttpRequest sets the correct content type with the required boundary.
So all you have to do is not set the content type and it'll work.
var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
//xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");<--don't do this
var formData=new FormData(form);
formData.append('update', true); // makes no difference
xhr.send(formData);
xhr.onload=function() {
alert(this.response);
};
Change the name of the button to something other than "update" (and change it in your form['update'].onclick... as well). I think its clashing with the value you are trying to set on the FormData to trigger the PHP code.

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.

Apache file system does not respond my AJAX request

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.

grabbing text from a text field and updating db with it

I am trying to grab text from a text field and then use that to update my db with it. I have tried using session, get, post and cookie to grab the value using php and this doesn't work. I am new to php so I am thinking this comes out blank because it is server side. I did this with javascript and it grabs the value but I am not sure how to use it with php or to update mysql. any help is appreciated. here is some sample code of mine: I have the update on a seperate php page but the input of my text area is not even being grabbed
<?php
function update_db(){
// echo $_POST["comment"];
$nenabled = $_GET['enabled'];
$comments_new = htmlspecialchars($_GET['comment']);
$nemail = $_GET['email'];
echo ("<script>console.log('$comments_new')</script>");
?>
<form method ="get" action ="update_user.php">
<input type="hidden" name = "enabled" value = "nenabled">
<input type="hidden" name = "comments" value = "comments_new">
<input type="hidden" name = "email" value = "nemail">
<input type="submit" >
<script>
function doFunction() {
var com = document.getElementById("comment");
alert(com.value);
// var comment = '<?php update_db(); ?>';
}
</script>
You have something like :-
<input type="hidden" name = "comments" value = "comments_new">
Then how can you expect
document.getElementById("comment");
will work?
You should add the id in your html, like:-
<input type="hidden" id="comment" name = "comments" value = "comments_new">
You won't be able to call a PHP function from inside the javascript function. Once the page is rendered PHP can no longer modify the page since it is a server side language exclusively. There are two common ways to do this however, the first is to wrap your text input in a form and include a submit button that calls a php file with your code to insert the value into your database. There are plenty of good tutorials out there if you google them but http://html.net/tutorials/php/lesson11.php is a pretty good one.
The other way, and the way that sounds like it would work best for you, is to use AJAX to make a call to a php function. You never navigate away from your page and you can handle success and error conditions. AJAX supports GET and POST data to your php file. Again, not reinventing the wheel here is a great AJAX tutorial that spells out using GET and POST, single data, multiple items, return data, etc. http://hayageek.com/jquery-ajax-post/
Hope that helps!
If you want to update your database on submit of the form, then no need to import yout php code within javascript. You just need to send an AJAX request to your php server on submit your form. For the AJAX request you can also use jQuery.
At first you've to modify your html form like:-
<form onsubmit="return false;">
<input type="hidden" id="name" name = "enabled" value = "nenabled"></input>
<input type="hidden" id="comments" name = "comments" value = "comments_new"></input>
<input type="hidden" id="email" name = "email" value = "nemail"></input>
<input type="button" onclick="update()" value="Submit">
</form>
So, on click of the submit button the update function will be called. The update function will take the input values and call another function to send the AJAX request. So I wrote:-
<script type="text/javascript">
function update(){
var data = {
name : document.getElementById("name").value,
comments : document.getElementById("comments").value,
email : document.getElementById('email').value
};
loadXMLDoc(data);
}
//Ajax request function
function loadXMLDoc(data)
{
var xmlhttp;
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","updateDB.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+data.name+"&comments="+data.comments+"&email="+data.email);
}
</script>
The AJAX request will send a POST request to
your base url + 'updateDB.php'
with data:-
name:nenabled,
comments:comments_new,
email:nemail,
So, now you can do the rest of the thing in the server side php code to update the database.

Two forms - one submit button?

I have TWO forms on my website.
Is it possible when I submit one of these, it will take form data from a particular field in the other form?
I am using the Recurly system with PHP.
You can write your own function.
function submit (){
document.getElementById("firstform").submit();
document.getElementById("secondform").submit();
}
You can then make a button that calls this function.
If this doesn't work, try again using ajax.
Example
You can do it with javascript.
For example:
var request =false;
function submit()
{
var yourobject = document.getElementById("yourobject").value;
data = "yourobject" + "=" + encodeURIComponent(yourobject);
request.open("POST", "yourpage.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(data);
}
And the input:
<input type="button" onclick="submit()" value="Submit" />

Categories

Resources