JavaScript AJAX preventDefault - javascript

I'm making a simple login page (backed by PHP and MySQL) to learn more about JavaScript and AJAX. I had it working with a form without a submit button, just a button with an onclick method call. However, I want it to be a submit button so hitting enter will call the function, and that seems the proper way to do things anyway. After endless research and trying to translate jQuery solutions, I still can't stop the form from submitting by default.
If I fill out the form with test data and submit, it submits the form with "?username=test&password=test&submit=Log+In" in the url and reloads the page, without displaying the message from the server. Why isn't the event preventDefault working? I've also tried this with adding the eventlistener to the form element with a submit event.
<?php
session_start();
if (isset($_SESSION['user']))
header("Location: home.php");
?>
<html>
<head>
<script>
document.getElementById('login_btn').addEventListener('click', login(event));
var request = new XMLHttpRequest();
function login(evt) {
evt.preventDefault();
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
request.open('POST', 'login.php', true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = process_login;
request.send('username=' + username + '&password=' + password);
}
function process_login() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseXML;
var message = response.getElementsByTagName('message').item(0).firstChild.nodeValue;
if (message == '')
window.location = 'home.php';
else
document.getElementById('message').innerHTML = '<b>' + message + '</b>';
}
}
}
</script>
<title>Log In</title>
</head>
<body>
<h2>Please Log In</h2>
<form>
<table>
<tr><td>Username:</td><td><input type="text" name="username" id="username"></td></tr>
<tr><td>Password:</td><td><input type="password" name="password" id="password"></td></tr>
<tr><td><input id="login_btn" type="submit" name="submit" value="Log In"></td></tr></form>
<tr><td colspan="2"><div id="message" /></td></tr>
</table>

document.getElementById('login_btn').addEventListener('click', login(event));
You are calling login immediately and trying to use its return value (undefined since it has no return statement) as the event handler.
Remove (event) from there.
ā€¦ at least that is what would happen if you weren't trying to call null.addEventListener. See this question and learn how to use the developer tools for your browser so you can see error messages from JavaScript.

Related

how to ajax for chatting website without page reload

want to create a fully dynamic chat UI for my website, But it reloads the whole page if a person submits the button page should not reload like many chat website.
<form action="action.php" method="post" id="formpost">
<input type="text" id="input" value="php echo">
<input type="submit" value="send">
</form>
I want to submit this form through ajax and show the last xml <message> containing <message>talk 123<message>
<messages category="short">
<person1>
<time>
r
<message>Djssjs</message>
</time>
</person1>
<person2>
<time>
r
<message>1234fdg</message>
</time>
</person2>
<person1>
<time>
r
<message> talk 123</message>
</time>
</person1>
</messages>
i want to show that talk 123 in the html document bit confused how to do that
//for form submit
$("#formpost").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: action.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
//for xml
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "name.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var msg = "";
//how to select the last person's of the <messages> child
msg = getElementsByTagName("messages").lastChild.childNodes[1].nodeValue ;
document.getElementById("demo").innerHTML = msg;
}
$("#formpost").on('submit', function(event){
event.preventDefault();
// rest of your ajax code here...
});
Points to note
1. Make sure you have also added JQuery script source on the head tag of your chat page.
2. Make sure to put preventDefault() immediately before any other code is executed.
You can use reverse ajax method pulling data from the server.
In reverse ajax a request is auto-generated at a certain time interval or hold the request for fetching new message.
There are three technologies for reverse ajax:-
Piggyback
Polling
Comet

How to call existing REST api from a HTML form?

I have a REST API that I am using in a mobile application to register/store data into a Mongo database. I would now like to view the data stored in the DB on a webpage.
I know that I basically have all of the functionality already (the login request used in my mobile application) but I am so confused on how to call my REST from my HTML page.
Something like this: How to call a REST web service API from Javascript button Handler? ?
I am also confused on how/where I should be creating my html page. Any help is appreciated.
Thanks, Joe
Typically When user would like to get data from the server. client need to send a request to the server and get a response. Usually programmer will bind a request function with an specific element and events.
In this case you need to bind a request function with form element. As you didn't mention which event you want to happen, so I couldn't tell exactly solution.
The following code is a simple code that call REST API when user type on a text input, and show the result below the input text
Note that replace "URL" with your API call.
<!DOCTYPE html>
<html>
<body>
<form>
Keyword:<br>
<input type="text" name="keyword" onkeyup="callREST()"><br>
</form>
<div id="response"></div>
<script>
function callREST() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response").innerHTML = this.responseText;
}
};
xhttp.open("GET", "URL", true);
xhttp.send();
}
</script>
</body>
</html>
This is how you do it...
HTML Code:
<form id="form" onsubmit="return setAction(this)">
<input name="senderEmail" type="email" placeholder="Email" required>
<textarea name="senderMessage" cols="30" rows="10" placeholder="Message.." required></textarea>
<button type="submit">Send message</button>
</form>
Javascript:
function setAction(form) {
const url = 'https://example.com/xyz?';
const andSign = '&';
const senderParameter = 'sender='+form.senderEmail.value;
const bodyParameter = 'body='+form.senderMessage.value;
const newUrl = url+senderParameter+andSign+bodyParameter;
fetch(
newUrl,
{
headers: { "Content-Type": "application/json" },
method: "POST",
body: ""
}
)
.then(data => data.json())
.then((json) => {
alert(JSON.stringify(json));
document.getElementById("form").reset();
});
return false;
}
This also resets your form after a successful api call is made.

Submitting a form and run a function at the same time [duplicate]

This question already has answers here:
Form Submit Execute JavaScript Best Practice? [closed]
(3 answers)
Closed 11 months ago.
When I press the Submit button of a form it runs a php file which stores the answer to a db.
Is it possible to use the Submit button of a form to submit the user's choice and immediately after that run a function without further actions from the user?
For example, in the following simple form and php, how can I run a function when the user presses Submit?
<form action="db.php" method="post">
A:<input type="radio" name="answer" value="A">
B:<input type="radio" name="answer" value="B">
<input type="submit" name="submit value="submit">
</form>
<?php
$con = mysqli_connect('localhost','my user id','my password');
if(!con) {
echo 'not connected to server';
} else {
echo 'something else is wrong';
}
if(!mysqli_select_db($con,'my user id') {
echo 'Database error selection';
}
if (isset($_POST['submit'])) {
$answer=$_POST['answer'];
$sql = INSERT INTO test1 (columnName) VALUES ('$answer');
mysqli_query($con,$sql); // Execute query
}
?>
As an example let's take the following function which is a part of a larger file.
function next() {
var qElems = document.querySelectorAll('#questions>div');
for (var i = 0; i < qElems.length; i++) {
if (qElems[i].style.display != 'none') {
qElems[i].style.display = 'none';
if (i == qElems.length - 1) {
qElems[0].style.display = 'block';
} else {
qElems[i + 1].style.display = 'block';
}
break;
}
}
}
You can add an onsubmit event handler to the form
<form action="db.php" method="post" onsubmit="functionToCall()">
which will call the given function when the form is submitted. If you want to stop the form from being submitted, return false from the function. As #JokerDan said, you can also use AJAX within your function and omit the form action altogether.
function functionToCall() {
// Do something before you submit your form (save data locally or whatever)
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200) {
//Do something after submitting the form (if you want to change the page or redirect)
}
};
http.open('POST', 'db.php');
http.send(/*send post data here*/);
}
If you want to send data with the AJAX request, you will have to pull it from the form and put it in the http.send() line in the same format you pass data in the URL (data=answer&submit=true)
The proper way to do this, is to first select your form using something like document.querySelector or document.getElementById (only possible if the form element has an id).
var form = document.querySelector('[action="db.php"]');
After you selected your form, use the addEventListener of your form to add an evenListener.
form.addEventListener('submit', myListener, false);
Now you'll just need to create a function that looks like this :
function myListener(event) {
// DO STUFF
}
Here, event is an object of type Event that provides more information about the form you submitted. This function will be called every time you try to submit your form!

Submit Embedded Mailchimp Form with Javascript AJAX (not jQuery)

I have been trying to submit an embedded Mailchimp form with AJAX but without using jQuery. Clearly, I am not doing this properly, as I keep ending up on the "Come, Watson, come! The game is afoot." page :(
Any help with this would be greatly appreciate.
The form action has been altered to replace post?u= with post-json?u= and &c=? has been added to the end of the action string. Here is my js:
document.addEventListener('DOMContentLoaded', function() {
function formMailchimp() {
var elForm = document.getElementById('mc-embedded-subscribe-form'),
elInputName = document.getElementById('mce-NAME'),
elInputEmail = document.getElementById('mce-EMAIL'),
strFormAction = elForm.getAttribute('action');
elForm.addEventListener('submit', function(e) {
var request = new XMLHttpRequest();
request.open('GET', strFormAction, true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var resp = JSON.parse(request.responseText);
request.send(resp);
} else {
console.log('We reached our target server, but it returned an error');
}
};
request.onerror = function() {
console.log('There was a connection error of some sort');
};
});
}
formMailchimp();
});
Also, I anticipate the inevitable "why don't you just use jQuery" comment. Without going into the specifics of this project, jQuery is not something I am able to introduce into the code. Sorry, but this HAS to be vanilla javascript. Compatibility is for very modern browsers only.
Thanks so much for any help you can provide!
A few days back I've had the exact same problem and as it turns out the MailChimp documentation on native JavaScript is pretty sparse. I can share with you my code I came up with. Hope you can build from here!
The simplified HTML form: I've got the from action from the MailChimp form builder and added "post-json"
<div id="newsletter">
<form action="NAME.us1.list-manage.com/subscribe/post-json?u=XXXXXX&id=XXXXXXX">
<input class="email" type="email" value="Enter your email" required />
<input class="submit" type="submit" value="Subscribe" />
</form>
</div>
The JavaScript: The only way to avoid the cross-origin problem is to create a script and append it to the header. The callback occurs then on the ā€œcā€ parameter. (Please note there is no email address validation on it yet)
function newsletterSubmitted(event) {
event.preventDefault();
this._form = this.querySelector("form");
this._action = this._form.getAttribute("action");
this._input = this._form.querySelector("input.email").value;
document.MC_callback = function(response) {
if(response.result == "success") {
// show success meassage
} else {
// show error message
}
}
// generate script
this._script = document.createElement("script");
this._script.type = "text/javascript";
this._script.src = this._action + "&c=document.MC_callback&EMAIL=" + this._input;
// append script to head
document.getElementsByTagName("head")[0].appendChild(this._script);
}
var newsletter = document.querySelector("#newsletter")
newsletter.addEventListener("submit", newsletterSubmitted);

AJAX form submission to MYSQL without refresh

I have a php code that loops to create multiple separate forms with a submit button for each. I am trying to use JS to update the MYSQL with the form data without leaving the page
The Form (simplified)
<form name='myform'>
<SELECT class='index' NAME='album' id='album'>
<option value='1'>"PUBLIC"</option>
<option value='2'>"PRIVATE"</option>
<option value='3'>"FRIENDS"</option>
</select>
<input type="text" name="title" size="40" maxlength="256" value="">
<textarea name="caption" cols="37" rows="3"></textarea>
Photo Rating:
<input type="radio" name="rate" value="1">ON
<input type="radio" name="rate" value="0" checked>OFF
<input type="checkbox" name="del" value="1"> Delete Photo
<?php
<input type='submit' name='submit' value='Save changes to this photo' onClick=\"picupdate('include/picupdate.php', '1', 'picpg');\">";
?>
</tr></table></form>
The JS
function picupdate(php_file, pid, where) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
var a = document.myform.album.value;
var b = document.myform.title.value;
var c = document.myform.caption.value;
var d = document.myform.rate.value;
var e = document.myform.del.value;
var the_data = 'pid='+pid+'&album='+a+'&title='+b+'&caption='+c+'&rate='+d+'&del='+e;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(where).innerHTML = request.responseText;
}
}
}
The PHP for updating MYSQL
$pid=$_POST['pid'];
$album=$_POST['album'];
$title=$_POST['title'];
$caption=$_POST['caption'];
$rate=$_POST['rate'];
$del=$_POST['del'];
$db->query("UPDATE photos SET album = '".$album."', title = '".$title."', caption = '".$caption."', rate = '".$rate."' WHERE pid = '".$pid."'");
The reaction on submitting should be the MYSQL updating in the background with no changes to what the user sees. However it is not updating the MYSQL at all.
The problem is that you're not doing anything to prevent the browser from submitting the form when you press the submit button. There are two ways to do this. Without using jQuery, you can use the onclick property (sort of like what your'e doing), but you have to return a value of false, otherwise the form will be submitted in addition to whatever the onclick handler is doing. So:
<input type='submit' name='submit'
onclick=\"picupdate('include/picupdate.php', '1', 'picpg');\">
Is not doing the trick. What you need is:
<input type='submit' name='submit'
onclick=\"picupdate('include/picupdate.php', '1', 'picpg'); return false;\">
You can also modify your function, picupdate to return false, and then just do this:
<input type='submit'
onclick=\"return picupdate('include/picupdate.php', '1', 'picpg');\">
Lastly, if you want to use jQuery instead, you call preventDefault() against the event object when you handle the click event:
$(document).ready(function(){
$('input[name="submit"]').on('click', function(evt){
e.preventDefault(); // prevent form submission
picupdate('include/picupdate.php', '1', 'picpg');
});
I hope this helps!
Got it to work by changing the JS to
function picupdate(php_file, pid, where) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
var a = document.getElementById('album').value;
var b = document.getElementById('title').value;
var c = document.getElementById('caption').value;
var d = document.getElementById('rate').value;
var e = document.getElementById('del').checked;
var the_data = 'pid='+pid+'&album='+a+'&title='+b+'&caption='+c+'&rate='+d+'&del='+e;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(where).innerHTML = request.responseText;
}
}
}
Thanks all

Categories

Resources