Javascript used for random button - javascript

I am a beginner in JavaScript means and programming, and I encountered a problem for a personal project. I made an anime fight website getting some information from MySQL Database each anime has ten videos and photos, through a random button it randomly takes one link for a video and photo. The problem is that it only work only one time if I random again nothing happens. I know that in order to make that work I have to rewrite the code again after the success of the first random for getting a second random but this will create an infinite loop. Can somebody help me solve this issue.
This is the code used:
<script>
$(document).ready(function () {
$('.imgResponsive').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
$('#random').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
}
});
})
}
});
})
});
</script>

I understand that $.ajax request overwrites initial .imgResponsive element, am I right? Along with overwritten .imgResponsive you permanently lose click event attached to this element.
In that case you need to attach event to element container, eg.
$(document).on('click', '.imgResponsive', function() {....
...
}
instead of
$('.imgResponsive').click(function(){ ....

You have to register EventListener in order to proceed.
Try this:
<script>
var showImage = function(e){
e.preventDefault();
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
}
});
};
$(document).ready(function () {
$('document').on('click', '.imgResponsive', showImage);
$('document').on('click','#random', showImage);
});
</script>

The way your code is written, you're handling only a single AJAX response (aside from the first one) with no way to handle more AJAX requests triggered by clicking the #random button. You need to write functions for handling button clicks and the AJAX responses instead of using anonymous functions; that way it's modular enough that you can listen for and handle more button clicks in the future.
Something like this:
<script>
$(document).ready(function () {
$('.imgResponsive').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: handleResponse
});
$('#random').click(handleButtonClick);
});
function handleButtonClick(e){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: handleResponse
});
}
function handleResponse(response){
$('#hiddenPage').html(response);
}
});
</script>
Edit: Another thing that might be happening is that your #random element is being overwritten every time you do $('#hiddenPage').html(response);. In that case you would need to attach a new event handler to the new #random element every time you handle an AJAX response:
function handleResponse(response){
$('#hiddenPage').html(response);
$('#random').click(handleButtonClick);
}

Related

How can I ajax only html table rows instead of sending the entire form inputs?

I have tried to ajax using post to jsp script my html table rows for weeks now with no success.Can anyone please guide me on this?Below is what I have done so far.
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
$('#notSoCoolGrid > tr').each(function(event) {
event.preventDefault();
var postData = {
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
};
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData.$('input, select').serialize() ,
success: function(msg){
alert("submitted");
}
});
});
});
If I correctly understand your need, you want to transmit the content of your rows, each in the form showed in your current postData.
So this can be made at once for all rows (instead of ajaxing successively each of them).
It might be something like this:
window.addEventListener("DOMContentLoaded", function () {
var form = document.getElementById("updateDealPmtForm");
document.getElementById("btn").addEventListener("click", function () {
event.preventDefault();
var postData = [];
$('#notSoCoolGrid > tr').each(function(event) {
postData.push(
paymentId:$('#paymentId').text(),
id:$('#deald').text(),
pType:$('#pType').text(),
pAmt:$('#pAmt').text(),
currency:$('#currency').text(),
pInvDate:$('#pInvDate').text(),
pRecDate:$('#pRecDate').text(),
comments:$('#comments').text()
);
});
console.log(postData);
$.ajax({
async: false,
type: "POST",
cache: false,
url: "/update_deal_pmt_script.jsp",
data: postData,
success: function(msg){
alert("submitted");
}
});
});
});
Note that I choosed (the simplest way, IMO) to make a simple array of rows, where each one is an object like you already structured them.
Last point: I notice you specified async: false.
I don't know why you did that, and so I kept it unchanged.
But note that it's not recommended, and is being on the road to become deprecated.
I finally was able to solve this issue,for that I want to post my answer it might be helpful for someone out there.My previous code was submitting a form before even ajax call being triggered and I have to use Classes instead of IDs to identify my rows.I had to change the code completely to be able to submit the form
$('#btn').click(function(e) {
e.preventDefault();
$('#notSoCoolGrid tr').each(function(i, tr) {
var postData = {
paymentId : $('.paymentId', tr).val(),
id : $('.deald', tr).val(),
pType:$('.pType', tr).val(),
pAmt:$('.pAmt',tr).val(),
currency:$('.currency',tr).val(),
pInvDate:$('.pInvDate',tr).val(),
pRecDate:$('.pRecDate',tr).val(),
comments:$('.comments',tr).val()
}
$.ajax({
async: false,
type: "post",
url: "/update_deal_pmt_script.jsp",
data: postData
})
.done(function(response) {
console.log(response);
})
.fail(function(x, status, error) {
alert("Error: " + error);
});
});
});

Submit Ajax Form via php without document.ready

I am submitting a number of forms on my page via php using Ajax. The code works great in forms preloaded with the page. However, I need to submit some dynamic forms that don't load with the page, they are called via other javascript functions.
Please, I need someone to help me review the code for use for forms that don't load with the page. Also the 'failure' condition is not working.
The code is below:
<script type="text/javascript">
feedbar = document.getElementById("feedbar");
jQuery(document).ready(function() {
$('#addressform').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $('#addressform').serialize(),
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
failure: function () {
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
Thanks.
You need to bind event by existing html (e.g body).
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()
see api: https://api.jquery.com/on/
Try like this:
$("body").on('submit', '#addressform',function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $('#addressform').serialize(),
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
failure: function () {
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
you can delegate to document:
$(document).on('submit', '#addressform', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $(this).serialize(), // <----serialize with "this"
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
error: function () { //<----use error function instead
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
As you have posted this line as below:
I need to submit some dynamic forms that don't load with the page
What i understand with this line is you want a common submit function for all forms which are generated dynamically, then you can do this:
$(document).on('submit', 'form', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $(this).serialize(), // <----"this" is current form context
success: function () {
//some stuff
},
error: function () { //<----use error function instead
//some stuff
}
});
e.preventDefault();
});
});
For your last comment:
You can try to get the text in ajax response like this:
success: function (data) {
feedbar.innerHTML='<div class="text-success">'+ data +'</div>';
},
error: function (xhr) { //<----use error function instead
feedbar.innerHTML='<div class="text-danger">' + xhr.responseText + '</div>';
}
if Success:
here in success function you get the response in data which is the arguement in success function, this holds the response which it requested to the serverside.
if Error:
Same way if something goes wrong at the serverside or any kind of execption has been occured then xhr which is the arguement of error function holds the responseText.
And finally i suggest you that you can place your response in feedbar selector using jQuery this way:
var $feedbar = $('#feedbar');
so in success function:
$feedbar.html('<div class="text-success">'+ data +'</div>');
so in error function:
$feedbar.html('<div class="text-success">'+ xhr.responseText +'</div>');

Submit unresponsive after ajax call + fadeIn()

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');
}
});
}
}

Tooltip script. Need to correct code

$(function() {
$('.challenge').tooltip({html: true, trigger: 'hover'});
$('.challenge').mouseover(function(){
var that = $(this);
var ajaxQueue = $({
url: "<?=base_url();?>/ajax/challenge_tip",
type: 'POST',
cache: true,
data: {
'idd': $(this).attr("rel"),
},
dataType: 'json',
success: function(challenge_j) {
that.tooltip('hide')
.attr('data-original-title', challenge_j)
.tooltip('fixTitle')
.tooltip('show');
}
});
$.ajaxQueue = function(ajaxOpts) {
var oldComplete = ajaxOpts.complete;
ajaxQueue.queue(function(next) {
ajaxOpts.complete = function() {
if (oldComplete) oldComplete.apply(this, arguments);
next();
};
$.ajax(ajaxOpts);
});
};
});
});
it's my first experience with js and i need some help. for tooltips i use bootstrap tooltips.
when cursor hover on link, script send post data to controller and receive callback data. in the first hover script receives the data, but tooltip doesn't pop up, only the second hover. how i can fix it?
and one more question. can script will send the request only the first mouse hover, and the following hover will use the information from the cache?
and sorry my english ;D
It is hard to test cross domain
Here is what I THINK you need
$(function() {
$('.challenge').tooltip({html: true, trigger: 'hover'});
$('.challenge').mouseover(function(){
var that = $(this);
$.ajax({
url: "<?=base_url();?>/ajax/challenge_tip",
type: 'POST',
cache: true,
data: {
'idd': $(this).attr("rel"),
},
dataType: 'json',
success: function(challenge_j) {
that.tooltip('hide')
.attr('data-original-title', challenge_j)
.tooltip('fixTitle')
.tooltip('show');
}
});
});
});
Create flag for ajax query.
var isTooltipTextEmpty = true;
$('.challenge').mouseover(function(){
if(isTooltipTextEmpty) {
...add ajax query here)
}
}
And you need to trigger tooltip show event, when ajax query is ready like this
.success(data) {
$('.challenge').show();
isTooltipTextEmpty = false; //prevents multiple ajax queries
}
See more here: Bootstrap Tooltip

Prototype conversion ajax.updater

I have got a website that currenty uses prototype that im trying to get away from. These are the only 3 functions that use it.
I have been trying all morning to convert these but as my understanding of jquery isnt great im so struggling.
function GetCountries() {
new Ajax.Updater('country_list','site_countries.php', {parameters: '&onchange=1', onComplete: GetRegions});
}
function GetRegions() {
new Ajax.Updater('region_list','site_regions.php', {parameters: '&regionID='+$('regionID').value+'&countryID='+$('countryID').value+'&onchange=1', onComplete: GetTowns});
}
function GetTowns() {
new Ajax.Updater('town_list','site_towns.php', {parameters: '&regionID='+$('regionID').value+'&countryID='+$('countryID').value});
}
this is what i have come up with but it doesnt work:
function GetCountries() {
$.ajax({
type: "POST",
url: "site_countries.php",
data: '&onchange=1',
success: function( transport ){
$('#country_list').html(transport.responseText)
GetRegions
}
});
}
the page that is calls just returns a select dropdown list that replaces one within span called country_list on the page then it calles GetRegions which does the same.
Any assistance would be greatly received!
Steve
It is possible that the way you are providing the data field might be the issue here.
Try something like the following:
$.ajax({
type: "POST",
url: "site_countries.php",
data: {onchange: 1},
success: function( transport ){
$('#country_list').html(transport.responseText)
GetRegions
}
});
OR
function GetCountries() {
$("#country_list").load("site_countries.php", {onchange: 1}, function(){
// call your GetRegions() here
});
}

Categories

Resources