I'm trying to make two Ajax calls in one page using jQuery. The first Ajax runs successfully and produces results. Second Ajax is supposed to fire up on button click and show the result, but it runs twice every time I click on the button. And initially on the first time clicking on the button, I have to click twice before it produces a result. Here's what I'm trying to do:
function showPicture() {
$("button").click(function() {
var id = this.id;
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': $(this).val()},
success: function(data) {
console.log(id);
$("#" + id).replaceWith("<img src=" + data + " />");
}
});
});
}
Here's my button:
<button id=" . $count . " onclick=showPicture() value=" . htmlentities($result['Poster']) . ">Click Me!</button>
I have seen similar questions on Google but I cannot figure out what the problem is. Any help would be greatly appreciated.
You have 2 onClick handlers, somewhat:
onClick
$("button").click()
Remove one of the handlers.
Example
function showPicture(id) {
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': $(this).val()},
success: function(data) {
console.log(id);
$("#" + id).replaceWith("<img src=" + data + " />");
}
});
}
<button id=" . $count . " onclick=showPicture(" . $count . ") value=" . htmlentities($result['Poster']) . ">Click Me!</button>
Your function 'showPicture' which you are calling from the html attribute below
<button id=" . $count . " onclick=showPicture()
is calling your function as you would expect.
but the function showPicture() itself is then binding a onclick event
function showPicture() {
$("button").click(function() { <------- this
......
So it is being hit twice as you have the attribute onclick and the even binding onclick.
The event click is on all html buttons.
What you should do: Remove the binding in the function to all buttons
function showPicture(caller) {
var id = $(caller).attr("id");
var val = $(caller).val();
console.log(id);
console.log(val);
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': val },
success: function(res) {
--you are replacing the button with an image... or something like that
$("#" + id).replaceWith("<img src=" + res+ " />");
}
});
}
html
<button id=".$count." onclick="showPicture(this)" value=".htmlentities($result['Poster']).">Click Me!</button>
Related
i have a Click function , inside it ajax post method,
this method is getting info from database
after i click the button the info show up for 1 second and then they vanish .
this is the code
$('.ViewVisitorMsg').click(function() {
var requestsID = $(this).attr('data-id');
$.ajax({
type: 'post',
url: baseURL + "admin/Messenger/get_messages_to_admin",
data: {
request_id:requestsID
},
dataType: 'json',
success: function(data) {
for (var i = 0; i < data.length; i++) {
if (data[i].sender == 1) {
chatBox.append("<li class= 'clearfix'><div class='message-data align-right'></div><div class='message other-message float-right'>" + data[i].message + "</div></li>");
} else {
chatBox.append("<li><div class='message-data'><span class='message-data-name'> Vincent</span></div><div class='message my-message'>" + data[i].message + "</div></li>");
}
}
}
});
});
i tried to put manually one ID and it works.
it's like when the click function finish , it resets all variables
EDIT:
it's link not a form
You are probably clicking on a button inside a form which is interpreted as a submit button (<button type="submit">), which will submit the form and refresh the page. Change the button to <button type="button"> to prevent it from submitting the form.
My excuses: First off all, I would like to explain that I've been searching for an answer a long time. I found so many similar questions, but none with a solution for my scenario.
The Problem: After an Ajax call, where I dinamicaly add HTML code, the code added looses its styles and action responses (on click, for example).
HTML : The HTML that is loaded with page loading. It renders the collection of the user's images correctly. I mean... the style is ok and the JS functions bind to the classes 'visualizaImagem' and 'deletaImagem' works fine.
<div class="row">
<div class="col-sm-12" id='imagens'>
<?php
if(isset($imagens)){
if(count($imagens) > 0){
foreach($imagens as $imagem){
echo "
<div class='file-box' data-path='" . $imagem['path'] . "' id='" . $imagem['nome'] . "'>
<div class='file'>
<a class='visualizaImagem' data-path='". $imagem['path'] ."'>
<div class='icon'>
<img src='../" . $imagem['path'] . "' style='height:100%'>
<a class='deletaImagem' data-path='". $imagem['path'] ."' data-divid='" . $imagem['nome'] . "'>
<i class='fa fa-trash' style='position:absolute;top:10px;left:10px;font-size:18px;'></i>
</a>
</div>
<div class='file-name'> " . $imagem['nome'] . "</div>
</a>
</div>
</div>";
}
}
}
?>
</div>
</div>
JS : When I click to the upload button (that is not part of this code), the image data is passed through "data: dados", read by "salvaImagem" in the specific controller and than appended to the page. The image is actually appended, but with no css style and no response to the functions that should have been bind to the same classes presented above.
jQuery.ajax({
type: "POST",
url: "salvaImagem",
data: dados,
dataType: "json"}).done(function(response)
{
if(response.sucesso){
toastr['success'](response.msg);
var img = "" +
"<div class='file-box' id='" + response.nome + "' data-path='" + response.path + "'>" +
" <div class='file'>" +
" <a class='visualizaImagem' data-path='"+response.path+"'>" +
" <div class='icon'>" +
" <img src='../"+response.path+"' style='height:100%'>" +
" <a class='deletaImagem' data-path='"+response.path+"' data-divid='"+response.nome+"'>" +
" <i class='fa fa-trash' style='position:absolute;top:10px;left:10px;font-size:18px;'>" +
" </a>" +
" </div>" +
" <div class='file-name'> "+response.nome+"</div>" +
" </a>" +
" </div>" +
"</div>";
$('#imagens').append(img);
}
else{
toastr['error'](response.msg);
}
});
I think I should give a little bit more about the code. Here is an example of how I bind functions to those classes. Actually as I wrote the function inside the bind, I was expecting that would't be necessary to rebind.
$('.deletaImagem').on('click', function (){
var path = $(this).data('path');
var div_id = $(this).data('divid');
jQuery.ajax({
type: "POST",
url: "deletaImagem",
data: {'path':path},
dataType: "json"}).done(function(response)
{
if(response.sucesso){
toastr['success'](response.msg);
$('#'+div_id).remove();
}
else{
toastr['error'](response.msg);
}
});
return false;
});
Trying to use some of the tips friends gave me here, I tried the following, but no success either.
jQuery.ajax({
type: "POST",
url: "salvaImagem",
data: dados,
dataType: "json"}).done(function(response)
{
if(response.sucesso){
toastr['success'](response.msg);
var img = <HTML original code here>
$(img).appendTo('#imagens').find('.deletaImagem').on('click', deletaImagem);
$('.visualizaImagem').on('click', visualizaImagem);
}
else{
toastr['error'](response.msg);
}
});
function deletaImagem(){
var path = $(this).data('path');
var div_id = $(this).data('divid');
jQuery.ajax({
type: "POST",
url: "deletaImagem",
data: {'path':path},
dataType: "json"}).done(function(response)
{
if(response.sucesso){
$('#'+div_id).remove();
toastr['success'](response.msg);
}
else{
toastr['error'](response.msg);
}
});
return false;
}
Since I assume you are binding events (click etc... ) on document.ready, any new items added later will not have those events.
After adding the the new items, just add the events again.
$('#something').append("<div class='somethingWithClicklistener'>a</div>"); // It won't have the event, you have to add it
$('.somethingWithClicklistener').click(function(){ etc..
Though that approach might double the event handlers on pre-existing classes but you get the point
As for styles it shouldn't happen unless you use jquery animation etc...
if you get an ajax response as html, you have to write your javascript code relatively to your root element in witch you input your html (received from ajax).
1.
<div class="some-root-div">
// the place where you put your html from response
</div>
And you should append the html like this: $('#imagens').append($(img));
3.
(function($){
"use strict";
$('.some-root-div', '.deletaImagem').on('click', function(){
// your logic on `.deletaImagem` link click
})
})(jQuery);
Your problem is that event handlers are not being attached to the new elements. It is pretty simple to do so while you attach the element to the DOM.
Change this
$('#imagens').append(img);
to
$(img).appendTo('#imagens').find('.deletaImagem').on('click', function (){
var path = $(this).data('path');
var div_id = $(this).data('divid');
jQuery.ajax({
type: "POST",
url: "deletaImagem",
data: {'path':path},
dataType: "json"}).done(function(response)
{
if(response.sucesso){
toastr['success'](response.msg);
$('#'+div_id).remove();
}
else{
toastr['error'](response.msg);
}
});
return false;
});
I've been here. My solution and understanding is that AJAX comes at the end/during javascript, javascript coming way after CSS. I ended up setting the styles that need to be the most dynamic in javascript with a function that takes an element as a parameter. works like a charm!
function styleElement(elem){
elem.style.visibility = "hidden";
}
I have this jQuery AJAX Like Dislike Script
<script>
$(function(){
var PostID = <?php echo $PostID; ?>;
$('.like-btn').click(function(){
$('.dislike-btn').removeClass('dislike-h');
$(this).addClass('like-h');
$.ajax({
type:"POST",
url:"rate.php",
data:'Action=LIKE&PostID='+PostID,
success: function(){
}
});
});
$('.dislike-btn').click(function(){
$('.like-btn').removeClass('like-h');
$(this).addClass('dislike-h');
$.ajax({
type:"POST",
url:"rate.php",
data:'Action=DISLIKE&PostID='+PostID,
success: function(){
}
});
});
});
</script>
Now I want to transform this script to multi post Like Dislike System.
How i can do this? HTML will look like this:
Like
Dislike
LIKE/DISLIKE will be action, 1 will be ID of post to like/dislike. Thanks
you can make something like this. Each post it is each div with postId and two controls inside (like and dislike buttons). When you click like - function will get post id and send with post to server. You must to check ajax part of function.
$(function () {
$('.like').click(function () { likeFunction(this); });
$('.dislike').click(function () { dislikeFunction(this);});
});
function likeFunction(caller) {
var postId = caller.parentElement.getAttribute('postid');
$.ajax({
type: "POST",
url: "rate.php",
data: 'Action=LIKE&PostID=' + postId,
success: function () {}
});
}
function dislikeFunction(caller) {
var postId = caller.parentElement.getAttribute('postid');
$.ajax({
type: "POST",
url: "rate.php",
data: 'Action=DISLIKE&PostID=' + postId,
success: function () {}
});
}
<div class="post" postid="10">
<input type="button" class='like' value="LikeButton" /> </input>
<input type="button" class='dislike' value="DislikeButton"> </input>
</div>
If you have some questions or need more help you can ask me :)
If you want more than one post per page you can do this:
function send(action, id)
{
var opposite;
opposite = action === 'like' ? 'dislike' : 'like';
$('#' + opposite + '-' + id).removeClass(opposite + '-h');
$('#' + action + '-' + id).addClass(action + '-h');
$.ajax({
type:"POST",
url:"rate.php",
data:'Action=' + action + '&PostID=' + id,
success: function(){
}
});
}
Now you only need to attach the handlers properly ($PostID must be different for every post in a loop):
<a href="#"
id="like-<?php echo $PostID; ?>"
onclick="send('like', <?php echo $PostID; ?>)">Like</a>
<a href="#"
id="disloke-"<?php echo $PostID; ?>"
onclick="send('dislike', <?php echo $PostID; ?>)">Dislike</a>
That's just a layout of the code, there may be defects. It's pretty different from where we started, so only you can actually test it and see where it need refinement.
Have a JQUERY AJAX call in a $(document).ready(function()..) that loops through MongoDB docs and adds HTML Divs to the page with a .get
Included in each Div is a <button type='button' id='deleteItem' class='close' onClick='deleteThisItem(" + i + ")' aria-hidden='true'>×</button>"
Each Div also has a form field, with a hidden value for returning the doc _id to then use in Express/Node.js to find and delete the correct doc (this does work in another app..)
"..<form name='theForm' id='theForm" + i + "'>
<input type='hidden' name='iD' id='iD' value='" + doc._id + "'>.."
Am looking to have the button delete the MongoDB doc onClick using an AJAX .post
// handle DELETE (x) button clicks
$('#deleteItem').click(function(i) {
number = i;
alert(number);
// make an ajax call
$.ajax({
dataType: 'json',
data: $('#theForm' + number).serialize(),
type: 'POST',
url: "http://localhost:9999/delete",
success: gotAllSuccess,
error: gotAllFailure
});
});
Tried using a global variable (not ideal) var number = 0;, to pass the i parameter through a function outside of the $(document).ready(function()..) and have been researching callback techniques to callback the ajax, but nothing has done the trick..
function deleteThisItem(i)
{
number = i;
alert(number);
//some callback to the Jquery in the ready doc?
}
Since you have multiple records, don't use id for the button since id of an element must be unique, use class attribute to group them. Also there is no need to have an inline click handler
<button type='button' class='close deleteItem' data-id='" + i + "' aria-hidden='true'>×</button>
then use delegated event handler like
jQuery(function ($) {
$(document).on('click', '.deleteItem', function () {
var $this = $(this);
var number = $this.data('id');
alert(number);
// make an ajax call
$.ajax({
dataType: 'json',
data: $('#theForm' + number).serialize(),
type: 'POST',
url: "http://localhost:9999/delete",
success: gotAllSuccess,
error: gotAllFailure
});
});
})
Here's a simple question:
On the page there are two javascript.
The first script gets JSON and used it to build multiple forms with buttons:
$.getJSON("http://api.server.com/my/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<div class='accordion-group span4'><div class='accordion-heading'>Video Frame<blockquote><a href='http://server.com/video/?my=" + result.File + "' target='_blank'><img src='http://jpg.server.com/" + result.File + ".jpg' class='img-polaroid'/></a><p>" + result.ListId + "</p><small>" + result.OwnerId + "</small><small>" + result.updatedAt + "</small> </blockquote><a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion2' href='#" + result.File + "'>Share video</a></div><div id='" + result.File + "' class='accordion-body collapse'><div class='accordion-inner'><form class='share_file_form'>Set list<input name='nd' id='user_id' type='hidden'><input name='file' value = '" + result.File + "' type='hidden'><div class='list'></div><input type='text' placeholder='New list'><div class='modal-footer'><button class='share_file_submit'>Share video</button></div></form><div id='user_info_result'></div></div></div></div>");
});
$('#mytile').html(results.join(""));
}
);
The second script is a response by pressing a button on the form of constructing the first script:
$(document).on('click', '.share_file_form', function(event) {
$(this).validate({
submitHandler: function(form) {
$.ajax({
type: "GET",
url: "http://api.server.com/set/",
timeout: 20000,
data: $(form).serialize(),
beforeSend: function() {
$(".share_file_submit").attr("disabled", true);
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
},
success: function(msg){
console.log("Data Saved: " + msg);
$("#share_file_submit").attr('disabled', false);
$("#share_file_submit").html("Share video");
$("#user_info_result_2").html(msg);
},
error: function(msg){
//////////////// $('#user_info_result_2').html("<div class='alert alert-error span3'>Failed from timeout. Please try again later. <span id='timer'></span> sec.</div>");
}
});
}
});
});
Everything works, but at the time of the second script, the inscription appears on the buttons of all forms, and I need only one button, which I click.
The problem is this line:
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
It sets the html for all elements with the "share_file_submit" class on the entire page. You can fix it by adding a context to the selector:
$(".share_file_submit", $(form)).html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
If you really want to use validate plugin properly you shouldn't initialize it within a click handler.
Should be initializing right after the form building code.
Within $.getJSON
$('#mytile').html(results.join(""));
$('.share_file_form').validate(/* options*/);
The submitHandler will over ride the default submit event of the form and validation will be active while user fills out form.
To fix button issue:
submitHandler: function(form) {// form is current form elemnt
$.ajax({
beforeSend:function(){
/* look within form for button*/
$(form).find(".share_file_submit").prop('disabled',true);
})
});
Now if user uses Enter key you aren't relying on a click event to prevent submittal by browser default