I am using a django form with ajax using this code:
<form id="form-id">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
and the Javascript code:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
});
But here is the thing, everytime the submit event is triggered, I feel like the whole page is reloaded (it blinks). What could I do to prevent this from happening?
Your change event is submitting your form and page refreshes. Delete it and add change event to second function, where you're currently waiting for submit event.
$('#form-id').on('change', function(evt) {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
To prevent submit on enter, add keypress event to function and detect when enter is pressed. Like this:
$('#form-id').on('change keypress', function(evt) {
var key = evt.which;
if (key == 13) {
return false;
} else {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
}
});
Key number 13 is enter. When it's pressed, nothing is returned. You could have also replaced return false with evt.preventDefault(). And for other keys, Ajax will be triggered.
What if you add:
return false;
To your code, like so:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
return false;
});
});
Got this from:
https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html
A very important detail here: in the end of the function we are
returning false. That’s because we are capturing the form submission
event. So to avoid the browser to perform a full HTTP POST to the
server, we cancel the default behavior returning false in the
function.
How I specify my form in html / django template:
<form id="form-id" action="required-url-goes-here" method="post">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
The tutorial I pointed to above works in a different way then you do. It specifies, inside the ajax request:
- url
- type
- data
- dataType
It also uses a different way to reference the form, and it is the only way I know, so I can't judge if there is an error in the rest of your code.
Related
I have a laravel project where admin can change user data via form. I want this form to be submitted by ajax. But it doesn't get submited.
I have a form:
<form id="userData{{$loop->iteration}}" method="POST">
#csrf
<!--some inputs-->
</form>
<button id="changeUserData{{$loop->iteration}}" data-id="#userData{{$loop->iteration}}">Save</button>
JS:
$("#changeUserData{{$loop->iteration}}").click(function (e) {
var ele = $(this);
var formId = ele.attr("data-id");
console.log(formId);
$(formId).submit(function (e){
console.log("test2");
e.preventDefault();
$.ajax({
url: '{{url('changeUserData')}}',
method: "PATCH",
data: $(formId).serialize(),
success: function(){
console.log("test");
}
})
})
});
When I press the button the first console.log gets fired but nothing else. I checked if formId matches the form id and it does so I don't know what's wrong.
The problem is .submit() with handler argument does not submit the form itself. It just binds an event handler to the form's submit event.
You may just remove that bind and it should work:
$("#changeUserData{{$loop->iteration}}").click(function (e) {
var ele = $(this);
var formId = ele.attr("data-id");
console.log(formId);
$.ajax({
url: '{{url('changeUserData')}}',
method: "PATCH",
data: $(formId).serialize(),
success: function(){
console.log("test");
}
})
})
I know this is probably a duplicate question. I am trying to use the value of a textbox and just show it in my console.log. It appears for a second and disappears.
Here is my HTML form
<form>
<input type ="text" id="search" name="search" placeholder="Search..." size="45" required>
<input type ="submit" value="GO" id="submit">
</form>
Here is my JavaScript
$(function(){
$("#submit").on("click", function(){
var t = document.getElementById("search").value;
console.log(t);
});
});
For future context, I am trying to use that information to plug it into the wikipedia API.
var wikipediaURL = "https://en.wikipedia.org//w/api.php?action=opensearch&search="+ t +"&format=json&callback=?";
$.ajax({
url: wikipediaURL,
type:'GET',
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function(data, status, jqXR){
console.log(data);
},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("fail");
})
.always(function() {
console.log("complete");
});
Reason you see it for a moment in your console and then it's disappear is you are using submit button inside your form and whenever you click submit button it will by default submit the form and refresh the page if target is same page unless you stop form submission.
In order to avoid form submission try this.
$(function(){
$("#submit").on("click", function(){
var t = document.getElementById("search").value;
console.log(t);
e.preventDefault(); // this will also do the trick and avoid form submission.
return false; // return statement is included just as safety measure as this will make sure form is not submitted.
});
});
Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).
I'am trying to use google invisible reCAPTCHA with AJAX. But returne false is not working.
JS:
function onSubmit(token) {
var siteurl= 'http://localhost/test/';
document.getElementById("register").submit();
var formdata = $('.register').serialize();
$.ajax({
method: "POST",
url: siteurl+"app/ajax/test.php",
data: formdata
})
.done(function( msg ) {
alert(msg);
});
return false
}
HTML:
<form id="register" action="" method="post" class="register">
<input class="for-1" type="text" name="field" >
<input class="g-recaptcha" data-sitekey="6LfCqCAUAAAAAAjaAg5w_mHK" data-callback='onSubmit' type="submit" value="Submit">
</form>
this codes working well but not returning false.
iam waiting help,
thanks.
Well if you wan't to avoid your page from reloading when form is submitted
I suggest you use this flow
1 -> data-callback='onSubmit' attribute is no longer need
2 -> remove function onSubmit and replace it with event listener
this code will listen if your form register is being submitted
$(document)
.off('submit', '.register')
.on('submit', '.register', function(e) {
/** Do what you want when submitting the form **/
var siteurl= 'http://localhost/test/';
var formdata = $('.register').serialize();
$.ajax({
method: "POST",
url: siteurl+"app/ajax/test.php",
data: formdata
})
.done(function( msg ) {
alert(msg);
});
/** prevent form from submitting to your form action page **/
e.preventDefault();
});
3 -> also document.getElementById("register").submit(); remove this since your form is already been submitting
e.preventDefault(); what this line do is it will prevent form from submitting to your form action page
I am using ajax to update the db with a new folder but it refreshes the page after ENTER is hit.
on my form I have onkeypress="if(event.keyCode==13) savefolder();"
here is the javascript code that I have: what it does basically is after you hit enter it calls the function savefolder, savefolder then sends a request through ajax to add the folder to the db. Issue is it refreshes the page... I want it to stay on the same page.
any suggestions? Thank you
<script>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
// ajax request to add the folder
jQuery.ajax({
type: 'get',
url: 'addfolder.php',
data: 'foldername=' + foldername + '&foldercolor=' + foldercolor,
beforeSend: function() { alert('beforesend');},
success: function() {alert('success');}
});
return false;
}
</script>
This is working:
<form>
<input type="submit" value="Enter">
<input type="text" value="" placeholder="search">
</form>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
jQuery.ajax({
type: 'get',
url: '/echo/html/',
//data: 'ajax=1&delete=' + koo,
beforeSend: function() {
//fe('#r'+koo).slideToggle("slow");
},
success: function() {
$('form').append('<p>Append after success.</p>');
}
});
return false;
}
jQuery(document).ready(function() {
$('form').submit(savefolder);
});
http://jsfiddle.net/TFRA8/
You need to check to see if you're having any errors during processing (Firebug or Chrome Console can help). As it stands, your code is not well-formed, as the $(document).ready() is never closed in the code you included in the question.
Simply stop the propagation of the event at the time of the form submission
jQuery(document).ready(function($) {
$("#whatever-form-you-are-pulling-your-values-from").submit(function(event) {
var foldername = $('#foldername').val();
var foldercolor = $('#foldercolor').val();
event.stopPropagation();
// ajax request to add the folder
$.ajax({
type: 'get',
url: '../addfolder.php',
data: 'ajax=1&delete=' + koo,
beforeSend: function() { fe('#r'+koo).slideToggle("slow"); },
success: function() { }
});
});
Since by default on a form the enter button submits the form, you need to not only handle this with your own code, but cancel the event after.
Try this code instead:
onkeypress="if(event.keyCode==13) {savefolder(); return false;}"
The onkeypress event will that the return value of the javascript and only continue with it's events if it returns true.