I've got a problem with some JavaScript code. It works fine when I test the website locally but doesn't work on the server unless I reload the page. The code is below. Please let me know if you need more details.
$(document).ready(function(){
$( "#header_inbox_bar" ).click(function() {
const inboxtopcount = $('#inboxtopcount')
const badgedanger = inboxtopcount.parent('.badge-danger')
$.ajax({
type: 'POST',
url: 'controllers/ctrl_client_update_inbox_notifications.php',
success (res) {
if (res) {
badgedanger.hide()
inboxtopcount.hide()
}
},
});
});
});
my guess is your DOM elements are not binding to the jQuery in time. Also, try inspecting your jQuery for syntax errors or any missing syntax.
To address any binding issues on load, try using the jQuery 'on' method so you can then pass it your #header_inbox_bar element and have it bind at a later time. like this:
$(document).ready(function() {
$('body').on('click', '#header_inbox_bar', function() {
const inboxtopcount = $('#inboxtopcount');
const badgedanger = inboxtopcount.parent();
$.ajax({
type: 'POST',
url: 'controllers/ctrl_client_update_inbox_notifications.php',
success(res) {
badgedanger.hide();
},
});
});
});
Related
I've created a news system, where i should be able to edit articles dynamically without redirect, from a modal. Also, i should be able to delete and create articles.
When something is changed, jQuery Load is called, but the problem is when i have to edit the loaded content.
$("#toolbox-items").load('inc-toolbox');
The above code loads the articles (the file is called inc-toolbox on purpose and works fine).
$(function () {
$('form').on('submit', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});
But, when ever something has to be edited or deleted, the whole page reloads and nothing changes, although i'm still able to add things.
The add-button is not loaded dynamically from the script, but is in there from the start.
What in the world might the problem be?
Try code like this
$(function () {
$(document).on('submit','form', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});
I have a project which involves live notification. So I stumbled upon using socket io but I didn't have enough time to learn it yet. So I tried doing it with AJAX and jQuery. Below is my code structure and I was wondering if this is gonna work with no drawbacks?
setInterval(function(){
if( !element.hasClass('processing') ){
element.addClass('processing');
$.ajax({
type: 'post',
dataType: 'json',
url: ajaxurl,
data: {},
success: function( response ){
/* Success! */
element.removeClass('processing');
}
});
}
}, 2500);
Some Extra Info
The way you described will work. From Experience I would just like to point out some things.
I usually do a recursive function, allows you to wait your interval between ajax calls and not a fixed rate. //OPTIONAL BUT DOES GIVE THE SERVER SOME BREATHING ROOM.
Use window.setTimeout() with an isActive flag. //ALLOWS YOU TO STOP POLLING FOR WHATEVER REASON, AND BECAUSE FUNCTION IS RECURSIVE START UP AGAIN IF NEED BE
For Sake of being thorough, I found it is always a good idea to handle the error case of the $.ajax() post. You could perhaps display some message telling the user he is no longer connected to the internet etc.
Some Sample Code:
var isActive = true;
$().ready(function () {
//EITHER USE A GLOBAL VAR OR PLACE VAR IN HIDDEN FIELD
//IF FOR WHATEVER REASON YOU WANT TO STOP POLLING
pollServer();
});
function pollServer()
{
if (isActive)
{
window.setTimeout(function () {
$.ajax({
url: "...",
type: "POST",
success: function (result) {
//SUCCESS LOGIC
pollServer();
},
error: function () {
//ERROR HANDLING
pollServer();
}});
}, 2500);
}
}
NOTE
This is just some things I picked up using the exact method you are using, It seems that Web Sockets could be the better option and I will be diving into that in the near future.
Please refer :
Jquery : Ajax : How can I show loading dialog before start and close after close?
I hope this could help you
$("div.add_post a").click(function(){
var dlg = loadingDialog({modal : true, minHeight : 80, show : true});
dlg.dialog("show");
$.ajax({
url : "/add.php",
complete : function (){
dlg.dialog("hide");
}
});
return false;
});
//--Loading dialog
function loadingDialog(dOpts, text = "пожалуйста подождите, идет загрузка...")
{
var dlg = $("<div><img src='/theme/style/imgs/busy.gif' alt='загрузка'/> "+text+"<div>").dialog(dOpts);
$(".ui-dialog-titlebar").hide();
return dialog;
}
I want to append textboxValue to the URL - test.php
The URL should be test.php?variable="textboxValue"
var textboxValue = document.getElementById("textbox").value;
window.onload = function() {
window.addEventListener('shake', shakeEventDidOccur, false);
//define a custom method to fire when shake occurs.
function shakeEventDidOccur () {
$.ajax({url:"test.php?value=var textboxValue"});
}
How do I do this?
Pretty sure you can make use of the data property for this kind of thing...
$.ajax({
url: "test.php",
data: { value: textboxValue }
});
$.ajax({url:"test.php?value="+textboxValue});
OR
$.ajax(
{url:"test.php"},
{data:{value:textboxValue}}
);
You can simply concatenate.
url:"test.php?value="+$('#id').value()}
If you will use $.ajax you need to have included the jQuery source, and then you can also use the jQuery functions to do that.
Try this:
//Into your html "head" tag you need to have this:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
//And then in your code you could have something like this:
$(document).ready(function () {
window.addEventListener('shake', shakeEventDidOccur, false); //You have now the task to find what jQuery function or method could be replacing this to make your code integrated completly
//define a custom method to fire when shake occurs.
function shakeEventDidOccur () {
var textboxValue = $('#textbox').val(); //Where textbox is the "id" attr of your textbox
$.ajax({url:"test.php"
type: 'GET', //can be POST too
url: '/wp-admin/admin-ajax.php',
data: { 'value': textboxValue},
success: function (request_data) {
//some code to execute after the call as a callback
}
});
}
});
How can I send $("#query").val()) using my Ajax function ?
If I put my Ajax call in my $(document).ready(function() , my code doesn't work anymore (the script doesn't start).
=> I can see the 'test123' string on my next page but , but if I type something in my "query" Input_Field, and then click on my link href (pointing to the same location) , the input field is reset and loose my value "query"...
Please help me :( Thank you
$(document).ready(function() {
$("#completed").live('click', function() {
alert($("#query").val());
});
$.ajax ({
url: 'http://localhost:3000/user/updateattribute',
data: { chosenformat: 'test123' , query: $("#query").val() } ,
type: 'POST',
success: function()
{
alert ('success ' );
return false; }
});
});
// do not use this anymore $(document).ready(function() {
$(function() {
event.preventDefault();
// live is no longer used use on..
$("#completed").on('click', function() {
console.log($("#query").val());
// alerts are annoying learn to use console
});
I'm using bsmSelect jQuery plugin. Basically, what it does is changing the way a select-multiple is rendered to make easier to pick up the options. It hides the select element and shows a list instead.
So, first of all I'm applying the plugin function to my select-multiple element:
$(document).ready(function() {
...
$('#my_select_multiple').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
...
});
On the other way, I have another select element (this one is simple) which has an ajax request bind to its change event. This ajax request get new #my_select_multiple options depending on the select simple value. Ajax response is the new HTML for #my_select_multiple options. So I have:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/
}).responseText;
return r;
}
...
$(document).ready(function() {
...
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val()));
}
...
});
AJAX is working as expected. New options are got correctly and they are inserted into #my_select_multiple (which is hidden by bsmSelect plugin, but I can check it with Firebug). But bsmSelect didn't realize new changes and doesn't get updated.
So, I think what I want is to reapply $('#my_select_multiple').bsmSelect(); with its new options.
I've been looking around a little bit and here is what I have tried.
1. I've tried to call again the funcion with the success and complete (one at time) of the AJAX request. Didn't work:
function getNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function() { $('#my_select_multiple').bsmSelect(); }
}).responseText;
return r;
}
2. I've tried to bind the function with the on jQuery function. Didn't work:
$('#my_select_simple').on('change', function() {
$('#my_select_multiple').bsmSelect();
});
3. I've tried 1 and 2 removing previosly the HTML generated by bsmSelect. Didn't work.
Thank you very much.
UPDATE: The exact code
First I have a global.js file which apply bsmSelect plugin to some select multiples (.quizzes):
$('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
});
And then, in the php file I define the updateQuizzes function and bind it to the select simple (project_id) change event:
<script type="text/javascript">
function updateQuizzes(project_id) {
var r = $.ajax({
type: 'GET',
url: '<?php echo url_for('event/updateQuizzes')?>'+'<?php echo ($form->getObject()->isNew()?'':'?id='.$form->getObject()->getId()).($form->getObject()->isNew()?'?project_id=':'&project_id=')?>'+project_id,
success: function() { $('.quizzes').bsmSelect({
plugins: [$.bsmSelect.plugins.sortable()],
title: 'Add',
removeLabel: 'Remove'
}); }
}).responseText;
return r;
}
$('#project_id').change(function(){
$('.quizzes').html(updateQuizzes($(this).val()));
});
</script>
As I told, the AJAX request works without problems, but not the calling bsmSelect the second time...
Not sure if this is what the problem is, but you could try
$('#my_select_simple').change() {
$('#my_select_multiple').html(getNewOptions($(this).val())).trigger('change');
}
This triggers a change event on select_multiple, and might fire bsmSelect. I'm not sure what the problem here is exactly, but that's the best I can come up with.
I think you want to set your HTML in the success of the Ajax call, something like:
function loadNewOptions(val) {
$.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).bsmSelect();
}
});
}
And then calling like:
$('#my_select_simple').change() {
loadNewOptions($(this).val());
}
$(document).ready(function() {
$('#my_select_simple').change() {
$('#my_select_multiple').load("your Url", function(){
$('#my_select_multiple').bsmSelect();
});
}
});
something like this should work.
.load will put whatever your url returns into #my_select_multiple
the first parameter is the url to load, and the 2nd is a function to call when it is done. which is where you need to set up your fancy selector.
Ok, I opened a ticket and bsmSelect developer has answered me in minutes. Great!
To let bsmSelect know about its select changes, you have to trigger a change event on the select. There is no need to call bsmSelect again.
So it can be that way:
function loadNewOptions(val) {
var r = $.ajax({
type: 'GET',
url: /*My URL*/,
success: function(data) {
$('#my_select_multiple').html(data).trigger('change');
}
}).responseText;
return r;
}
$('#my_select_simple').change(function() {
loadNewOptions($(this).val());
});