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.
});
});
Related
My Ajax request works correctly when I use change and the input is checkbox, but my Ajax request does not work when use input type submit !!
I want my type in the input submit and when I do this the Ajax request will not work and the page will reload.
$(document).on('change','.filter-form',function(event){
event.preventDefault();
$.ajax({
type:'GET',
url:'filter/',
data : $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
alert("error" + data);
}
});
});
my form :
<form action="" class="filter-form">
<input type="submit" name="price" value="new">
<input type="submit" name="discount" value="discount">
<input type="submit" name="old" value="old">
</form>
I don't think submit buttons trigger the change event, so you'll have to listen for something else, also .serialize() do not give you the name/value pair of submit buttons.
Use the click event on the buttons and use the element properties to get the data to post.
$(document).on('click','.filter-form input[type=submit]',function(event){
event.preventDefault();
$.ajax({
type:'GET',
url:'filter/',
data : {[this.name]: this.value}
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
alert("error" + data);
}
});
});
First added a clicked property to the identify which submit is clicked. Then used the clicked property to get the value & name of the submit to pass in form submit event handler.
$(document).ready(function(){
// To identify which submit is clicked.
$("form.filter-form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
// Form submit event handler
$("form.filter-form").submit(function(event) {
event.preventDefault();
$clickedInput = $("input[type=submit][clicked=true]");
dataString = {[$clickedInput.prop('name')]: $clickedInput.val()};
console.log('dataString', dataString);
$.ajax({
type:'GET',
url:'filter/',
data : dataString,
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
console.log("error" + data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="filter-form">
<input type="submit" name="price" value="new">
<input type="submit" name="discount" value="discount">
<input type="submit" name="old" value="old">
</form>
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.
I've gone through all of the solutions I could find on Stack Overflow and Google but none of them seem to help.
I have a function in Clojure (Noir framework) that takes two keys, "text" and "day-of-note" and inserts the values into a database. Regardless of whether or not that works, the function returns a JSON response with {"result":true} (for testing purposes).
(defpage [:post "/newpost"] {:keys [text day-of-note]}
[]
(println "newpost called")
(post text)
(response/json {:result true}))
My form is a simple form with one textarea, a checkbox and a button.
<form action="/newpost" id="new-post" method="post">
<textarea id="entry" name="text">Insert todays happenings</textarea>
<br />
<input checked="checked" name="day-of-note" type="checkbox" value="true">
<input type="submit" value="Add entry">
</form>
When submitting the form I have added a call to alert to show me the contents of dataString and they are formatted correctly ("text=lalala&day-of-note=true").
$(function () {
$("#new-post").submit(function (e) {
e.preventDefault();
var dataString = $("#new-post").serialize();
alert(dataString);
$.ajax({
url: "/newpost",
type: "POST",
dataType: "json",
data: dataString,
success: function () {
alert("Success!");
};
});
return false;
});
});
What happens here when the code is as it is above, there is a HTML call to /newpost when the user click on the button and the page shows {"result":true}. If I comment out the "$.ajax"-part the message box pops up with the correct content, but if I remove the comments -- no message box, just goes straight to /newpost.
What I thought was supposed to happen was that the /newpost page would never be rendered but a call with the dataString would be put to it by Ajax and a message box with "Success!" would be shown.
Where am I taking the wrong turn?
Remove the semi-colon after the success function declaration:
success: function () {
alert("Success!");
}
The success function declaration is part of an object, which separates declarations by comma.
So i have this function in JS, sending a request to insert a new Status message to the database.
function DoStatusInsert(){
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
With this form:
<input name="message" type="text" id="message" value="" size="60">
<input type="hidden" name="uID" id="uID" value="<?php echo $v["id"]; ?>">
<input name="submit" type="submit" id="submit" value="Spara">
<div id="statusResponseNow"></div>
Now I wish to do something like blocking the submit button or the message field to "read-only" until you receive response / success, so you don't have the opportunity to like press submit alot of times so it inserts alot.. (i know you could make a php for checking after double´s in DB)
So: when you click on submit then it makes either message field and/or submit button to read only
How should i do it?
function DoStatusInsert(){
$('#IdOfYourSaveButton').attr('disabled', 'disabled');
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val(),
success: function(msg){
$('#IdOfYourSavebutton').removeAttr('disabled');
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
enabled and disable the button. nice and easy :)
On calling the function, set the disabled property of the button, and then set it back on success.
function DoStatusInsert(){
$('#submit').attr("disabled", "true");
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
$('#submit').attr("disabled", "false");
}
});
}
My initial thoughts would be to insert
$('input[type=submit]', this).attr('disabled', 'disabled');
before the ajax call is started and then removed the disabled attribute with the success function of the ajax request.
Manually toggling the disabled state of the button works well enough, but jQuery has a couple helper events to make that a bit nicer: .ajaxStart() and .ajaxStop(). You can use those two handlers on your submit button and not have to worry about maintaining that manual code around your $.ajax() request.
Just throw this in with your other initialization code, probably in $(document).ready():
$('#submit').ajaxStart(function() { this.disabled = true; });
$('#submit').ajaxStop(function() { this.disabled = false; });
You can use for example jQuery BlockUI Plugin from http://jquery.malsup.com/block/ (see demo on http://jquery.malsup.com/block/#element and http://jquery.malsup.com/block/#demos).
If a div with all your form elements which you need to block has id formDiv then you can call
jQuery('#formDiv').block({ message: '<h1>Just a moment...</h1>' });
before jQuery.ajax and call
jQuery('#formDiv').unblock();
as the first line in both success and error handler of the jQuery.ajax.
Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});