Append Javascript variable to Jquery AJAX URL - javascript

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

Related

Javascript works locally but not on the server

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();
},
});
});
});

Run JS function on .load() content

I have a function called timepicker which is usually called by using
$(document).ready(function() {
$('#timepicker').timepicker();
});
But I have been unable to make it work on content that is displayed using jQuery .load().
I have tried several methods including using the below but nothing happens?
$(document).ready(function() {
var $parent = $('#small_container');
var time = $parent.find('#timepicker');
time.timepicker();
});
The #small_container is the ID of the DIV that the content is loaded into and the #timepicker is the id of the input that should call the function when it is clicked on.
Have I added it to the correct place in the callback?
$('.edit_job').on("click", function(){
var week_start = $('input[name=week_start]').val();
var job_id_del= $('input[name=job_id]').val();
var user_id = $('input[name=user_id]').val();
$('#small_container').load('ajax/edit_weekly_job_load.php?job_id='+job_id_del+'&week_start='+week_start+"&user="+user_id);
$('#timepicker').timepicker();
$('#small_container').on("click", '#edit_job_submit', function(){
jQuery.ajax({
type: "POST",
url: "ajax/edit_weekly_job_ajax.php",
dataType: "json",
data: $('#edit_job_form').serialize(),
success: function(response){
if(response.success === 'success'){
window.opener.$("#diary").load("ajax/diary_weekly_load.php?week_start="+week_start+"&user="+user_id);
window.close();
}
},
});//end ajax
});//save_job_edit_submit
});//end edit job
The content is loaded asynchronously to the element #small_container. The timepicker function is gets called before the content is actually loaded. Try to call the function in the callback of load() method:
$('#small_container').load('ajax/edit_weekly_job_load.php?job_id='+job_id_del+'&week_start='+week_start+"&user="+user_id ,function(){
$('#timepicker').timepicker();
} );
Also validate that element #timepicker is actually appended to the element #small_container.

Can't access object made by ajax call

I have this ajax request:
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
});
as you can see it makes new row in #table. But this new objects made by ajax are not accessible from next functions. Result from ajax is not a regullar part of DOM, or what is the reason for this strange behavior?
$('#uid').on('click', function () {
alert('ok');
});
Use event delegation:
$(document).on('click','#uid', function () {
alert('ok');
});
Note that ajax calls are asynchronous. So whatever you do with the data you need to do it in a callback within the success function (that is the callback which is called when the ajax call returns successfully).
Jquery on doesn't work like that. Use have to give a parent which not loaded by ajax, and the specify ajax load element like this
$('#table').on('click','#uid' ,function () {
// what ever code you like
});
Is simple and complex at the same time. Simple to solve but complex if you are getting started with javascript...
Your event handler - onclick is being fired and bound to an object that doesnt yet exist.
So when you append the object to the #table, you need to set up your click handler as the object now exists.
So in your success part of the ajax return add the click handler event there.
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
Or how about you make it dynamic and create a function to do it for you.
function bindClick(id) {
$('#' + id).click(function() {
//Do stuff here
console.log('I made it here' + id);
});
}
Then:
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
bindClick(uid);
});
}
This is a super contrived example but you get the idea you just need to make the rest of it dynamic as well. for example some name and counter generated id number: id1, id2, id3...
Try it like this, add this $('#uid').on('click', function () { into the success
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
});

jQuery methods in $.ajax success handler don't work

I have a function:
$(".delete").click(function() {
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $(this).attr("title"),
success: function() {
$(this).parent().parent().remove();
alert("hi");
}
});
});​
I have a problem when I delete the parent object. It just does not disappear. I tried to hide - did not help.
Alert is called normal.
How to solve?
Sorry for bad English.
You're inside another function with another this value by default. Pass the this value from the outer function with the $.ajax function as follows:
$.ajax({
context: this,
...
Because the this in the ajax success callback function is different from the click callback function. You could cache it to a local variable or use the $.ajax()'s context option.
$(".delete").click(function () {
var $this = $(this);
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $this.attr("title"),
success: function () {
$this.parent().parent().remove();
alert("hi");
}
});
});
Have you tried setting the context: this, parameter in the ajax function.
When the success handler fires, the value of this won't be the same as it was before hand.
See here fore more: http://api.jquery.com/jQuery.ajax/
Try this:
$(".delete").click(function() {
$object = $(this);
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $(this).attr("title"),
success: function() {
$object.parent().parent().remove();
alert("hi");
}
});
});​

jQuery plugin bsmSelect doesn't update its values when it is called again and its select options have changed

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

Categories