This question already has answers here:
How to prevent ENTER keypress to submit a web form?
(29 answers)
Closed 3 years ago.
I am trying to trigger my onclick of a button when i hit enter to make my site more user friendly. I have tried all of the below methods and all of them have the same error
this is my html (please note im using pug)
input#userInterests.form-control(type='text' placeholder='Interests' name='userInterests')
button#AddInterest.btn.btn-success.btn-block.btn-lg(type='button', onclick='add_interest()', value='interests') Update Interests
this is the posting function:
function add_interest() {
var interests = document.getElementById('userInterests').value;
interests = interests.split(" ");
interests.forEach(function (data) {
if (!validInterest(data))
{
swal(
'Error!',
`${data} is not a correctly formatted interest`,
'error'
)
return ;
}
});
interests.forEach(function (data) {
if (validInterest(data))
{
let form =
{
interest: data
}
$.ajax({
type: "POST",
url : '/user/account/addinterest',
data: JSON.stringify(form),
contentType: "application/json; charset=utf-8",
dataType: "json",
});
}
});
document.getElementById("interestsPara").innerHTML = "Updated your interests";
$('#userInterests').val('');
}
these are all the methods ive attempted and none of them work. please note i am obviously not doing all of these at the same time and uncommented each one one at a time for testing. I have tested all of these with and without $(document).ready
$(document).ready(function(){
$("#userInterests").keyup(function(event) {
if (event.keyCode === 13) {
$('#AddInterests').trigger("click");
$('#AddInterests').click(add_interest());
$("#AddInterests")[0].click();
$("#AddInterests").click();
setTimeout(function(){ $('#AddInterests').click()}, 100);
setTimeout(function(){ $('#AddInterests')[0].click()}, 100);
add_interest();
document.getElementById("AddInterests").onclick();
document.getElementById("AddInterests").onclick = add_interest();
$('#AddInterests').trigger('click');
$("#AddInterests")[0].click(add_interest());
}
})
});
This is my 'error'
Cannot POST /user/account
my function does work and posts correctly when i manually click the button
(this is a group project and some of this isnt mine so please dont flame me too hard and give constructive criticism)
Thank you #freedomn-m
The problem was the default form behaviour to submit on enter that i didnt realise existed. I set my form to onsubmit return false as follows and this worked
<form onsubmit="return false;">
as described by This Post
I tried to use event.preventDefault() but it did not work
Related
I'm using Ajax to display a comments widget on my site and am trying to upgrade from Recaptcha v2 to Recaptcha v3. So far it's gone well, comments successfully post, but instead of displaying the "thanks for submitting" modal, it just redirects to the form submission URL with the success data. This is not ideal.
The main change I made was to change the button code in my comment_form.html to this:
<button class="button g-recaptcha" id="comment-form-submit"
data-sitekey="{{ site.reCaptcha.siteKey }}"
data-callback='onSubmit'
data-action='submit'>
Submit
</button>
</form>
<script>
function onSubmit(token) {
document.getElementById("new-comment").submit();
}
</script>
(and added the id="new-comment" to the top of the form)
previously i had
<button class="button" id="comment-form-submit">Submit</button>
the relevant javascript code is:
(function ($) {
var $comments = $('.js-comments');
$('.js-form').submit(function () {
var form = this;
$("#comment-form-submit").html(
'<svg class="icon spin"><use xlink:href="#icon-loading"></use></svg> Sending...'
);
$(form).addClass('disabled');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
showModal('Comment submitted', 'Thanks! Your comment is pending. It will appear when approved.');
$("#comment-form-submit")
.html("Submit");
$(form)[0].reset();
$(form).removeClass('disabled');
grecaptcha.reset();
},
error: function (err) {
console.log(err);
var ecode = (err.responseJSON || {}).errorCode || "unknown";
showModal('Error', 'An error occured.<br>[' + ecode + ']');
$("#comment-form-submit").html("Submit")
$(form).removeClass('disabled');
grecaptcha.reset();
}
});
return false;
});
I'm pretty sure it's like a one line change to make the Ajax process the reply, but I'm totally out of my depth with javascript, so any thoughts are greatly appreciated.
--
Edit: The other example I saw calls the onSubmit function from their callback but since I'm using this weird main.js I don't know how to reference $('.js-form').submit(function (event) { from onSubmit
The default browser behaviour after submitting a form is to redirect on success, try preventing this by calling preventDefault on the event, eg:
$('.js-form').submit(function (event) {
event.preventDefault();
// the rest of your code
});
This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
I'm trying to correct a login/sign up issue i'm having, and having trouble. I've included a jsfiddle with the code, but im not sure what I'm missing.
https://jsfiddle.net/Zemanor/fuzrkw16/1/
I am consistently able to insert users into the correct db table on submit, but it gives the "You have already created an account!" alert and inserts the info, even if the account is not in the table pre-submit. I want to reject the account if there is one in the database, or accept it if it doesn't currently exist. How do I correct this problem? (php incl in jsfiddle)
//signup js
$(document).ready(function(){
var url="http://localhost/auth.php";
$("#signup").click(function(){
var fullname=$("#fullname").val();
var email=$("#email").val();
var password=$("#password").val();
var dataString="fullname="+fullname+"&email="+email+"&password="+password+"&signup=";
if($.trim(fullname).length>0 & $.trim(email).length>0 & $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: url,
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#signup").val('Connecting...');},
success: function(data){
if(data=="success")
{
alert("Thank you for registering with us! you can login now");
}
else if(data="exist")
{
alert("You already created an account!");
}
else if(data="failed")
{
alert("Something Went wrong");
}
}
});
}return false;
});
Use double == to compare
else if(data=="exist")
{
alert("You already created an account!");
}
else if(data=="failed")
Also use double && in if to check multiple and condition.
Check this for more detail : http://www.w3schools.com/js/js_comparisons.asp
I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.
This question already has an answer here:
ajax request without data not working
(1 answer)
Closed 8 years ago.
I have asked this earlier but still I wasn't lucky to get it work. Simply I am trying to update profile picture with a default picture when Delete button is clicked and I am trying to use ajax to do this, however whenever I click on the button nothing happens and the picture is not updated. I have tested the php page by itself and it works nicely but the js isn't working so could someone spot what I am doing wrong here?
html
<button href="javascript:void(0);" onclick="delete;" class="btn btn-default delbutt">Delete</button>
js
function delete()
{
$.ajax({
type: "POST",
url: "test.php?action=delete",
cache: false,
success: function(response)
{
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
});
}
and here is the php lastly
$username = $_SESSION["userCakeUser"];
if(isset($_POST["action"]) && !empty($_POST["action"]) || isset($_GET["action"]) && !empty($_GET["action"]))
{
if(isset($_GET["action"]) == "delete")
{
$profile = 'default.jpg';
$pp = $db->prepare("update users set profile = ? where username = ?");
echo $db->error;
$pp->bind_param('ss', $profile, $username->username);
$pp->execute();
}
}
else {
echo "Something is wrong. Try again.";
}
POST queries are by default not cached in jQuery ajax (1), so you probably should just use the $.post helper instead. Also, querystring values are not parsed to the $_POST super-global, so your code as-is will always read null from $_POST["action"].
function delete(){
$.post(
"test.php",
{
action: 'delete'
},
success: function(response){
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
);
}
(1) As defined in the API reference:
Pages fetched with POST are never cached, so the cache and ifModified
options in jQuery.ajaxSetup() have no effect on these requests.
It is my understanding that jQuery AJAX requests should have a data: option in there somewhere. Also, I see you're using GET to make the request, but tell jQuery to use POST.
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data : {
action : 'delete'
success : function(response)
{
etc...
I'm no jQuery expert, but I think that may be your problem. The only other thing I can think of is the success function isn't working properly. Check your F12 menu and post any warnings/errors so we can see it.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have two files. This is my main file - index.php which has javascript in the head, here's the javascript:
<script
src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(function () {
$('form#revisionnotes').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: $('form').serialize(),
success: function () {
alert('You have successfully saved the revision notes.');
}
});
e.preventDefault();
});
});
</script>
So when my form:
<form id="revisionnotes" name="revisionnotes" method="post">
<textarea style="width:100%;height:290px; padding:10px;" id="notes" > <?php echo $db->result("SELECT * FROM revision_notes", "notes");?></textarea><br/>
<input type="submit" value="Save" name="submit" id="submit" class="btn btn-primary">
</div>
</form>
From there in my updatenotes.php I was going to do a database INSERT, however that didn't work so I then tried adding a javascript alert to see if that'd work either:
<script type="text/javascript">
alert("hi");
</script>
And that didn't work either, I'm completely stumped. Could somebody please explain to me where I'm going wrong? I've never used this type of form-submitting before.
Thanks.
You do not say where exactly the trouble lies, so this is an incomplete answer:
$(function () {
alert("Alpha - jQuery is called");
$('#revisionnotes').on('submit', function(e) {
alert("Bravo - submit received");
var data = $(this).serialize();
alert("Charlie - data serialized");
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: data, // $('form').serialize(),
success: function (data, textStatus, jqXHR) {
alert("Delta - POST submission succeeded");
}
});
e.preventDefault();
});
});
The above should allow you to see where (if) the workflow fails to follow the plan.
At this point the POST should have been fired, and using Firebug or WebDev you should be able to inspect the results. Otherwise, temporarily convert the POST to GET, copy the URL and paste into another browser window.
Note: do not put Javascript in the POST-receiving script, since chances are that it won't be executed. You're not "going" to that page, just doing a submit; that's why you don't see your alert.
Ordinarily you would return some information from the submission page in JSON format and let success() extract it from the data variable. Note that "success" only means that the target script received the submission, not that it did handle it properly.
Example of success function (and how to "talk" to it)
success: function(data, textStatus, jqXHR) {
if (data.status != 'OK') {
alert("ERROR " + data.message);
return;
}
if (data.message) {
alert(data.message);
// do not return
}
// other
}
So you'd start with a submit script like this (I repeat, this is awkward. You really want to do this with proper logging and Firebug!), commenting the various jqExit's once you check they code is working up to any given point:
<?php
function jqExit($status, $message = false) {
$packet = array('status' => $status);
if (false !== $message) {
$packet['message'] = $message;
}
exit(json_encode($packet));
}
jqExit('ERROR', "Alpha - got POST");
// Connect to database
jqExit('ERROR', "Bravo - connected to DB");
// Decode and validate POST
jqExit('ERROR', "Charlie - data ready");
// Perform update
if (...update failed...) {
jqExit('ERROR', "reason why it failed");
}
// Finally everything is OK
jqExit('OK');
?>