Ajax form submission using button - html

Seems there are a ton of answers to nearly identical questions, but I can't seem to solve this. Please forgive me if you've seen this a thousand times:
I have a form I need to submit using ajax, but I can't get it to do it properly. It needs to submt, and not refresh (as you'd expect), but it doesn't seem to matter what I do, all I can get it to do is append the POST to the current URL of the page. I've stripped the form down to the bare minimum, and am still getting this result, so I must be doing something really wrong. Any help is appreciated, thanks!
<html>
<body>
<form class="form horizontal" id="logForm">
<fieldset>
<div class="control-group">
<div style="float: left">
<label for="from">Start Date: </label>
<div class="controls">
<input type="text" id="from" name="from" />
</div>
<label for="to">End Date:</label>
<div class="controls">
<input type="text" id="to" name="to" />
</div>
</div>
</div>
</fieldset>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="subButton" style="float: left">Search!</button>
</div>
</form>
<script>
$("#logForm").submit(function() {
$.ajax({
url: 'logQuery.php',
type: 'get',
dataType: 'json',
data: $('form#logForm').serialize(),
success: function(html) {
alert('worked good');
return false;
}
});
});
</script>
</body>
</html>

Change your script add ready and return false on proper line. You return false when asynchronus operation is done which may be after the function returns. That is why you don't prevent the standard behaviour of submit event.
Return should be inside submit() function.
Hint:
You don't need to use form#logForm because there is only one element with id=logForm (it should be at least) #logForm is enough.
Also always use document.ready when you binding events to elements. This will make you sure that all elements on site are loaded so you can bind events to them.
You can use also preventDefault() but return false is good too.
$(function (){
$("#logForm").submit(function() {
$.ajax({
url: 'logQuery.php',
type: 'get',
dataType: 'json',
data: $('form#logForm').serialize(),
success: function(html) {
alert('worked good');
}
});
return false;
});
});

Related

Simple Flask jQuery AJAX

I am trying to get the logic of using jQuery AJAX and Flask, however I am not coming right. I have been following tutorials here and here, but no resolution. To get the logic - I simply want to input dates in two separate fields, and return those dates to the same page in a normal <p> tag. My suspicion is a problem in the server receiving the dates. Submitting the relative form does not return anything to #result
HTML FORM
<form>
<input name="StartDate" id="StartDate" type="date" class="form-control"></div>
<input name="EndDate" id="EndDate" type="date" class="form-control"></div>
<button class='btn btn-info'>Generate</button>
</form>
<p id=result></p>
jQuery - located at the bottom of the <body> tag, after importing jQuery itself.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('a#generate').bind('click', function () {
$.getJSON($SCRIPT_ROOT + '/generate_report', {
StartDate: $('input[name="StartDate"]').val(),
EndDate: $('input[name="EndDate"]').val()
}, function (data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
Flask Server - I have imported relevant dependencies
#app.route('/generate_report', methods=['GET', 'POST'])
def generate_report():
start_date = request.args.get('StartDate', 0, type=str)
end_date = request.args.get('EndDate', 0, type=str)
return jsonify(result=start_date + "-" + end_date)
Please use the button to send the form, an anchor within the form does not make sense.
I would advise you to use the "submit" event
of the form, although the "click" event of the button would also work. The preventDefault function bypasses the standard behavior of the form, so that you can send the form yourself using getJSON. To serialize the form data, I use the serialize
function which converts all form data into a conforming string. Thus the data is sent as "application/x-www-form-urlencoded".
The variable $SCRIPT_ROOT is not used by me in this example because it is
basically empty under localhost and is not absolutely necessary.
<form name="my-form">
<div class="form-group">
<label for="start-date">Start</label>
<input type="date" name="start-date" id="start-date" class="form-control">
</div>
<div class="form-group">
<label for="end-date">End</label>
<input type="date" name="end-date" id="end-date" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Generate</button>
</form>
<p id=result></p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("form[name='my-form']").submit(function(event) {
event.preventDefault();
const formData = $(this).serialize();
$.getJSON("/generate_report", formData, function(data) {
$("#result").text(data.result);
});
});
});
</script>
The result of request.args.get is by default of type str.
If the form field is empty, get always returns None. A possible KeyError due to a missing value is bypassed.
#app.route('/generate_report')
def generate_report():
start_date = request.args.get('start-date')
end_date = request.args.get('end-date')
return jsonify(result=f'{start_date} - {end_date}')

Autocomplete input suggestions

I'm trying to set up an input with autocomplete places list. I want to use Here autosuggest tool.
https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-autosuggest-brief.html
For this I did this code :
<div class="autocomplete input-group has-warning">
<input id="search-where" name="w" type="text" class="form-control input-lg" placeholder="A quel endroit?" required="required" value="" autocomplete="on" onkeyup="mySearch(this.value)" />
<span class="input-group-btn">
<button type="submit" class="btn btn-lg btn-warning"><span class="glyphicon glyphicon-screenshot"></span></button>
</span>
</div>
{literal}
<script type="text/javascript">
function mySearch(e){
$.ajax({
url: "https://places.ls.hereapi.com/places/v1/suggest",
type: 'GET',
data: {
at: '44.771079,5.742806',
q: 'savoie',
app_id: '2FXOZOY',
app_code: 'b_9sMKgQmSjWUj1rlyY0wI'
},
headers : { "Authorization": "Bearer" + $('b_9sMKgQ5qzJF0SusExJJx9irrHHimSjWUj1rlyY0wI').val()},
beforeSend: function(xhr){
xhr.setRequestHeader('Accept', 'application/json');
},
success: function (data) {
alert(JSON.stringify(data));
}
});
$( "#search-where" ).autocomplete({
source: mySearch
});
}
</script>
{/literal}
But I get this error when I try to write in the input :
I'm clearly completely lost ... If anyone can help me it would be much appreciated.
Thanks for reading me anyway
I think you are doing an XMLHttpRequest to a different URL than the page you are on. In such scenarios, browser blocks it completely giving CORS error due to security reasons. There are a lot of ways to set this. A tutorial is available here.

Can't submit the page even though using preventDefault in laravel

I can't submit the form even though I used preventDefault, (page refreshed and doesn't take any action) My form inputs are filled dynamically here is my code.
HTML
<div class="modal-body">
<form id="update_form">
<!-- loaded below -->
</form>
</div>
another request that fill my form data
#csrf
<div class="form-row">
<div class="form-group col-md-6">
<input type="hidden" name="request_type" value="{{RegisterTypesNames::Faculty}}">
<label>University</label>
<select name="university" class="custom-select" id="university{{$action}}">
<option selected value="1">University of Cansas</option>
</select>
</div>
<div class="form-group col-md-6">
<label>Faculty</label>
<input type="text" class="form-control" name="faculty" id="faculties{{$action}}">
</div>
<div class="form-group col-md-6">
<label>Init</label>
<input type="text" class="form-control" name="short_name" id="short_names{{$action}}">
</div>
</div>
<button type="submit" class="btn btn-primary"><span class="fa fa-save"></span> Save</button>
And jquery code
$('#update_form').submit(function (e) {
$.ajax({
url: '/update_data',
type: "POST",
data: $('#update_form').serialize(),
dataType: "json",
success: function (data) {
console.log(data.result);
}
});
e.preventDefault();
});
Note: I use multiple partial forms like this all others works fine
I can't submit the form even though I used preventDefault, (page refreshed and doesn't take any action)
Interpretation: the statements "page refreshed" and "used preventDefault" indicate that the problem is that the code inside the $("#id").submit( is not firing and the page's default submit is kicking in hence the "page refreshed".
As the jquery event is not firing, it likely means that the HTML does not exist when the script runs. This can usually be handled by putting in a doc.ready; OP indicates that it's already in doc.ready.
The alternative is to use event delegation. Though it's not clear if the code is running before the HTML is generated or if the HTML is added after (subtle difference).
The solution for event delegation is to use:
$(document).on("submit", "#update_form", function(e) {
e.preventDefault();
$.ajax({...
});

How to make it so ajax does not run when page loads, but only when submit on a form is pushed?

I have a form that i want an administrator to fill out, then click submit and have the ajax run. At the moment this works, however, it also runs as soon as the page is loaded, something I do not want to happen. The code is as follows:
<script src ="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script>
<script src ="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<style type="text/css">
</style>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function() {
$.ajax({
type: "POST",
url: "ajaxtest.php",
async:false,
data: { product_id: "1" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
</head>
<body>
<form id="frmAJAX" action="" method="POST" >
<input type="hidden" name="product_id" value="<?php echo $product_id; ?>"/>
<p><strong>ID:</strong> <?php echo $product_id; ?></p>
<label name="product_sku" type="text">Item SKU</label>
<input type="text" value="<?=$product_sku?>" name="product_sku"/><br />
<label name="product_name" type="text">Item</label>
<input type="text" value="<?=$product_name?>" name="product_name"/><br />
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"></div>
</body>
</html>
What I would like to do is keep the ajax from running when the page loads, but let it run when the submit button is used. Any suggestions?
You could try to change the submit button to type="button" and then change the form submit function to the click event of this button. This change in the form submit logic might help fix the problem or uncover what the problem was.
example:
$('#[buttonid]').click(function(){
//put ajax function here
});
You may need return false at the end of the AJAX call. Also I'd personally, try #TheAmazingJason's way.
you could try by giving id to select form rather than by tag like
$("#frmAJAX").submit(function() {

Send JSON from HTML form with NODEJS backend

I haven't done front end HTML since I was 10 and that was drag and drop frontpage stuff. with static pages. As a result I'm really rusty.
What I need to do is put together a web client for a rest API that I wrote in NodeJS. My question is how, do you send a request from a form (say a log in form) to the server where the body of the POST request is a JSON of the email/password?
HTML form:
<form id="loginForm" action="" method="" class="form-horizontal">
<fieldset>
<legend>Log in</legend>
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" class="input-xlarge" id="email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" class="input-xlarge" id="password">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<button class="btn">Cancel</button>
</div>
</fieldset>
</form>
I suggest a lot of reading. To get you started with a very basic example, though, you will find a page with a sample form below that does what you need. You just need to replace the string your URL here with the actual URL you expect will be doing the handling.
The serializeObject() function was taken from here: Convert form data to JavaScript object with jQuery
<html>
<body>
<form id="loginForm" action="" method="">
Username: <input type="text" name="username" id="username" /> <br />
Password: <input type="password" name="password" id="password" /> <br />
<input type="submit" />
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function () {
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#loginForm").bind("submit", function(evt) {
console.log(JSON.stringify($("#loginForm").serializeObject()));
$.ajax({
url: "your URL here",
type: "POST",
contentType: "application/json",
data: JSON.stringify($("#loginForm").serializeObject()),
success: function (data, textStatus, jqXHR) {
// do something with your data here.
},
error: function (jqXHR, textStatus, errorThrown) {
// likewise do something with your error here.
}
});
return false;
});
});
</script>
</body>
</html>
The problem with your form is that input elements don't have name attributes. The name attribute is essential in many ways, so I would fix your html by setting each element's name attribute to the same value as its id attribute. The serializeObject function relies on form elements having names.
Here's an example using jQuery:
<form name="myform" action="#" method="POST">
Username: <input type="text" id="user" name="username"/><br/>
Password: <input type="password" id="pass" name="password"/>
<input type="submit" id="login" value="Login"/>
</form>
<script type="text/javascript">
var user=$('#user').val(), pass=$('#pass').val();
$('login').bind('click', function() {
$.ajax('/my/url', {
type: 'POST',
contentType: 'text/json',
data: JSON.stringify({username:user, password:pass}),
complete: function() { /* Do something with the response. */ }
});
return false; // Prevent form submit.
});
</script>
This might help you. Here is the form below: If you notice there is action and method if you don't know what these are, just go on and search for it. Action is the target server file that handles the information you send and method is get which is retrieving not updating.
Existing Users Username: Password:
Keep Me
Logged In
Here is the jquery part to handle the ajax call:
$.ajax({
type: "GET",
url: action,
data: form_data,
success: function(response)
{
if($.trim(response) == 'success')
window.location.replace("profile.php");
else
$("#result").html(response);
}
});
return false; });
});