I am trying to trigger a post request when a user clicks the submit button for a comment. Right now clicking the submit button triggers nothing, I even tried to console.log($(this)) I got no output. The first code below is the jQuery event code and ajax code. The block of code below that is the html button. thanks for the help.
$('#submitComment').on('click', '#content', function() {
$.ajax({
url: 'http://localhost:3000/comments',
type: 'POST',
data: data = { comment: {
body: $(this).find('input[name="createComment"]').val(),
user_id: 1,
image_set_id: 2}
}
}).done(function(response) {
console.log(response);
});
});
the button I am trying to target with jQuery event
<div class="container">
<div id="content">
//the code between comments is in a Handelbar template
<input name="createComment">
<button type="submit" id="submitComment">Create Comment</button>
//end of handelbar template
</div>
</div>
You need to bind the delegated handler to an ancestor(#content) of the target element(submitComment)
$('#content').on('click', '#submitComment', function () {
$.ajax({
url: 'http://localhost:3000/comments',
type: 'POST',
data: data = {
comment: {
body: $(this).find('input[name="createComment"]').val(),
user_id: 1,
image_set_id: 2
}
}
}).done(function (response) {
console.log(response);
});
});
Related
I have a simple code, and I try to make a post without redirecting the page. So far my code looks like this:
$(function() {
$('#btn').on('click', '.document', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/save',
data: {
html: '<p>Sucess</p>',
delay: 1
},
dataType: 'html',
success: function(data) {
console.log('success');
$('.document').append(data);
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="/save" method="post" autocomplete="off" id="theForm">
<button id="btn" type="submit" name="send">
Send
</button>
</form>
<span class="document"></span>
Can anybody try to help me with this? I don't know why my code doesn't work, I want to be able to POST without reloading and redirecting the page.
You're attaching a delegated event handler to a span with no content, and the primary selector isn't a parent of that span.
The correct approach would be to attach a submit event handler to the form element instead.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="/save" method="post" autocomplete="off" id="theForm">
<button id="btn" type="submit" name="send">Send</button>
</form>
<span class="document"></span>
jQuery($ => {
$('#theForm').on('submit', e => {
e.preventDefault();
$.ajax({
type: 'post',
url: '/save',
data: {
html: '<p>Sucess</p>',
delay: 1
},
dataType: 'html',
success: function(data) {
console.log('success');
$('.document').append(data);
}
});
});
});
This is my code:
var onloadCallback = function() {
$( "#submit" ).each(function() {
grecaptcha.render($( this ).attr('id'), {
'sitekey' : '6Lcjvi4UAAAAAIR7_ckItF2HfMEFHx427WUDdGDk',
'callback' : onsubmitforgotpass
});
});
};
function onsubmitforgotpass(token) {
$(document).ready(function() {
$("form.formajax").submit(function() {
$.ajax({
type: "POST",
url: "admin/login/forgotpass.php",
data: $("form.formajax").serialize(),
cache: false,
success: function(result) {
$(".forgotpassresult").html(result);
$(".forgotpassresult").css("opacity", "1");
}
});
return false;
});
$("form.formajax").submit();
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="" method="post" class="formajax">
<input type="text">
<input type="submit" id="submit">
</form>
I am unable to submit this ajax form multiple times.
It is probably because of these 2 lines:
$("form.formajax").submit(function()
and
$("form.formajax").submit();
If I replace those line with $("#submit").click(function() and $("#submit").click();
Then I can submit the form multiple times.
Anyway to submit the form multiple times using .submit(); function? (It will help me in some other part of my code also, so I do not want to use click();
hey please test the following things:
Please remove the actions
action="abc.com"
to
action=""
add ajax call on button click like below example:
$("#submit").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "admin/login/forgotpass.php",
data: $("form.formajax").serialize(),
cache: false,
success: function(result) {
$(".forgotpassresult").html(result);
$(".forgotpassresult").css("opacity", "1");
}
});
});
});
In my page I have a select menu inside:
<div class="div1" style="float: left">
<strong>Cerca Prodotto</strong>
<br/><br/>
<form class="form">
<div><input type="text" id="tags" value=""></div>
<div>
<img class="btnaggiungi" src="http://lainz.softwebsrl.it/img/carrello.jpg" alt="Aggiungi" id="add_newProduct"/>
</div>
</form>
</div>
which is controlled and generated by the following jQuery:
$( "#tags" ).autocomplete({
minLength: 2,
source: function (request, response) {
$.ajax({
url: "http://lainz.softwebsrl.it/ajax/autocompletecibo",
dataType: "json",
crossDomain: true,
type : 'post',
data:
{
valore: request.term,
},
success: function (data)
{
response(data);
console.log(data);
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, data ) {
var selezione = data.item.label;
$.ajax({
type : 'POST',
url: "http://lainz.softwebsrl.it/ajax/autocompletecibolista/valore/"+selezione,
dataType: "html",
success: function(msg){
$(".div2").html(msg);
},
error: function()
{
alert("Chiamata fallita, si prega di riprovare...1");
}
});
}
});
Now I need to add a mouse over event on every entry. I mean that when the user puts the mouse over an opion of the list, there are some other js code to be executed which, in the end, will show a map. How shall I add it?
UPDATE
This could be a solution:
<script>
$(document).on("mouseenter", "li", function() {
$(".div5").show();
});
$(document).on("mouseleave", "li", function() {
$(".div5").hide();
});
</script>
You have to bind the event to the static elements and then delegate it to your dynamically generated ones. I mean if <div class="div1"> is the container for your dynamically generated HTML, you have to do something like this:
$('.div1').on('mouseover','.div2 .dynamicallyGeneratedList',function(){
console.log('do something');
})
Your question is'nt quite entirely. How does your data response look like? Maybe does this help you.
$(data).each(function() {
var $li = $("<li>"+data+"</li>");
$li.bind("mouseover", showMap);
$("ul").append($li);
});
function showMap() {
// show map
}
I am working on a small tool which just consists of a single JSP which is used for view as well as for processing the AJAX response.
If the call is of type 'GET', I am showing a form the user.
<form id="submitForm" method="post">
<div class="ui-widget">
<label for="tags">Please Select the Merchant : </label>
<input id="tags" name="mechant" style="width:300px;height:40px;border: 0.5px solid;border-radius: 5px;">
<input type="submit" value="Get Data" style="border: 0.5px solid;border-radius: 5px;">
</div>
</form>
And following is the code which will make the call.
$("#submitForm").submit(function() {
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Once the user submits the form which goes as 'POST' the logic in the same JSP is returning the response.
Right now I am trying with a very simple logic.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Hello World");
Now when this response is return the whole of initial page is washed off and I just see "Hello World" on the page. Even though as per my understanding only the div with id "data" should be updated with value.
Kindly anyone have a look and let me know what might be going wrong here.
Thanks in advance.
You could try preventing the default handler as well as prevent bubbling up the DOM.
$("#submitForm").submit(function(event) {
// Prevent the default action
event.preventDefault();
// Pevent propagation of this event up the DOM
event.stopPropagation();
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Good day, fellow programmers.
There's this index.php that does an Ajax call to login.php and appends the DOM elements and some javascript from inside this into the body of the index. This login.php consists out of a a single div that contains a form and a submit button, which fadeIn() as soon as it is all appended.
However: the submit button is unresponsive!
I did find, after a while, that this does not happen when you directly access login.php via URL (.../.../login.php) instead. This means it's the fact that the index appends the whole, which makes them unresponsive.
(Also: in light of this, I've added a $(document).ready(function(){ ... }); around the entire script in the login.php, but that did not seem to help at all. Instead it caused all functions to return errors...)
I'm out of ideas. Perhaps some of you might have had any experience with these matters?
As always, thank you for the time!
Here's the (simplified) code:
index.php
$('#logInButton').click(function(){
loadContent('/login/login.php', 'body');
});
loadContent();
function loadContent(url, appendDiv, optionalData, cb) {
if (appendDiv == '#contentCenter') {
// vanity code
}
if (cb) {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(appendDiv).append(html);
},
complete: function(){
cb();
}
});
}
else {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(appendDiv).append(html);
}
});
}
}
login.php (deleted some styling. If you want some specific info, just ask!)
<style>
// some styling
</style>
<div id="loginBlack">
<div class="login" style="z-index:9999;">
<form id="myform1" name="myform1">
<div>
<img src="images/inputEmail.png" />
<div id="emailOverlay">
<input id="email" type="text"/>
</div>
</div>
<input id="iets" name="iets" type="submit"/>
</form>
</div>
</div>
<script type="text/javascript">
// $(document).ready(function(){ // <-- been trying this out.
$('#loginBlack').fadeIn(t)
// some functions pertaining to logging in and registering
// });
</script>
Use jquery on() instead of click()
$('body').on('click', '#logInButton' ,function(){
loadContent('/login/login.php', 'body');
});
That should make the elements behave properly
Note: you can also replace body selector with something nearer to the click button ( its nearest parent )
EDIT::
With this you can have the styling in your normal css file. Put it outside of the login.php
And your js goes into into the success handlers. So just leave the php with the actual html
function loadContent(url, appendDiv, optionalData, cb) {
if (appendDiv == '#contentCenter') {
// vanity code
}
if (cb) {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(html).hide().appendTo(appendDiv).fadeIn('slow');
},
complete: function(){
cb();
}
});
}
else {
$.ajax({
url: url,
cache: false,
type: 'post',
data: optionalData,
success: function(html){
$(html).hide().appendTo(appendDiv).fadeIn('slow');
}
});
}
}