JQuery recognize string as function dynamically callback - javascript

I have a simple jquery function that I am trying to get ajax to run dynamically. The function works fine when called as such
function widget1() {
console.log("test");
}
$(function () {
$('#thisbutton').bind('click', function() {
var htmlString = $("#uid").html();
$.ajax({
type: "GET",
url: "/getappobj",
data: {id:htmlString},
success: function(data) {
widget1();
}
});
});});
but if I try to get the function called dynamically I get an error that the string is not a function
$(function () {
$('#thisbutton').bind('click', function() {
var htmlString = $("#uid").html();
$.ajax({
type: "GET",
url: "/getappobj",
data: {id:htmlString},
success: function(data) {
var findit = data[0].widget;//returns "widget1"
findit();
}
});
});});
I have tried this every way that I can think of. Using jquery-1.9.1.min.js.

If widget1 is global, you can call window[findit]() to get the function from the window object by name.
You are trying to call a string as a function which of course won't work. You need to use the string to look-up the function to execute.

Related

generic ajax form submission

ajax/javascript problem:
I have an app which consist of multiple forms. What i want to achieve is to make a generic js function to submit forms to their respective controllers by getting form id.. I m successfully getting form ids in form_id variable but m unable to use them. I tried replacing $('patient_form') with form _id and got following error: TypeError: form_id.on is not a function
Here is the following code for better understanding of the problem:
$(function () {
var form = document.getElementsByTagName("form");
var form_id = "'#" + form[0].id + "'";
form_id.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $('#patient_form').serialize(),
success: function (result) {
alert(result);
}
});
});
});
The way you have it form_id is a string.
Try:
var form_id = $("#" + form[0].id);
$.ajax is a jquery function. If you want to use jquery (which in this case I think you should), then do it as follows:
$('form').on('submit', function () {
$(this).preventDefaults();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $('#patient_form').serialize(),
success: function (result) {
alert(result);
}
});
});
In addition to the other answers, you want to keep your form ID dynamic, right, so you can insert whatever values you want?
$(function () {
var form = document.getElementsByTagName("form");
// note you have to convert to jQuery object
var form_id = $("#" + form[i].id); // i, so you can put in the id for any form
form_id.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $(this).serialize(), // again, keep generic so this applies to any form
success: function (result) {
alert(result);
}
});
});
});
You should set the event listener to the element, not the string of the id of the element. Also I presume you have jQuery because you are using $. Set an id on the form in the HTML. Then:
$(function () {
var form = $('#theFormId');
form.submit(function(event) {
$.post('Controllers/c_insertPatient.php', form.serialize(), function() {
alert('success');
});
event.preventDefault();
});
});

Not to remove object without confirmation

I try to remove elements from my table in my django project, but I would like to have such a removal to be confirmed. Using this article
http://www.developmentwall.com/delete-row-from-html-table-jquery/
I wrote such function:
<script>
function deleteAjax(row_id){
$.ajax({
url: "delete_item/"+ row_id +"/",
type: "POST",
data: {'id':row_id},
success: function (){
if(!confirm('Are you sure you want to delete?')){
ev.preventDefault();
return false;
}else{
$('#my_row_'+row_id).remove();
}
}
});
}
</script>
Unfortunately, despite of the fact that I click that I won't to delete object, the object is removed.
Have you any hints? I suppose that it can be something wrong with ev, but I am fairly new to javascript and ajax and I do not know how to cope with this.
try this:
<script>
function deleteAjax(row_id){
if (!confirm('Are you sure you want to delete?')) { return; }
$.ajax({
url: "delete_item/"+ row_id +"/",
type: "POST",
data: {'id':row_id},
success: function (){
$('#my_row_'+row_id).remove();
}
});
}
</script>

Check for ajax call completion

I'm having a problem filling and accessing a global variable with ajax. I have the following code (stripped down a bit):
var answers;
$(document).ready(function() {
showResults();
console.log(answers);
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
return answers;
});
}
My question is the following: When I log answers in the done function it gives me a nice array. That would mean the array variable is filled. But when I log it from $(document).ready, It returns an empty variable. This is probably because the AJAX call is asynchronous, and the log gets executed before the variable is filled.
However, I need to use that variable on another page, so I need to access it from the $(document).ready ... Any idea about how to check if the variable is filled? Or when the showResults() is completed? Thanks in advance for your help!
Edit -
Thanks for your replies! But I'm still struggling with the following: As I understand, I can call another function from the ajax callback, and pass it the data. The thing is, I have to do a lot of different stuff with it after the call, and the only way I can get it to work now is by calling a function in the ajax callback, then calling another one from that one, etc...
So I end up wit showResults(); in the doc.ready, which then executes a lot of functions that are all "linked" together. Is there anyway I can return the data to the variable, for use in other places? I hope I have made this clear, English is not my native language, sorry.
Execute the functionality that is dependent on the answers array after the AJAX call. Call your function from within done(..)
A very rough idea:
var answers;
function functionalityDependentOnAnswers() {
//the code dependent on answers array.
}
$(document).ready(function() {
showResults();
//Move code here to functionalityDependentOnAnswers()
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
functionalityDependentOnAnswer();
});
}
You can use the when method provided by jQuery (look at this SO link).
Or look at this SO link where a similar situation is explained.
Check the documentation for success: this will only be executed when successful callback is done.
var answers;
$(document).ready(function() {
showResults();
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).when(function (data) {
console.log(answers);
answers = data.questionary;
return answers;
});
}
Idea: Have a hidden input field and add change listener to it.
<input type="hidden" id="answers_input" />
Now have a listener to this.
var answers;
$(document).ready(function() {
$('#answers_input').on('change', function() {
// trigger your custom code
console.log(answers);
})
showResults();
console.log(answers);
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
$('#answers_input').val(answers);
});
}
Solution is kinda like a hack, let me know if this works for you
You're in the right way.
Do stuff with answers inside the DOM callback.
var answers;
$(document).ready(function() {
showResults();
}
function showResults(){
$.ajax({
url: "/wp-content/themes/hoekiesikeenschool/question-storage.php",
data: { action: "get_results" },
type: "post",
dataType: "json"
}).done(function (data) {
answers = data.questionary;
console.log(answers);
// Manage answers here
});
}

Code after ajax (code) block needs a delay

I had a long question along with my complete code but now it is shorter one.
function showRecord(tbl) {
myDataTable.fnDestroy();
$.ajax(
{
data: "tableName=" + tbl,
url: "showTable.php",
dataType: "html",
success: function (data) { $("#example").html(data); }
});
alert('I get desired output as long as I do not comment/remove this alert');
myDataTable = $('#example').dataTable();
}
BUT if i just comment the alert I do not get data from database
If I do not use $('#example').dataTable(); (a jquery plugin for pagination from datatables.net ) then code works fine without alert.
function showRecord(tbl) {
//myDataTable.fnDestroy();
$.ajax(
{
data: "tableName=" + tbl,
url: "showTable.php",
dataType: "html",
success: function (data) { $("#example").html(data); }
});
//alert('I get desired output as long as I do not comment/remove this alert');
//myDataTable = $('#example').dataTable();
}
I need to know why alert is necessary in first sample of code. If it causes delay, why delay is necessary here and how to achieve this without using alert
Ajax calls are asynchronous. In the first block of code (if there is no alert) ajax call get executed and then immediately after that (before server responds) this line executes:
myDataTable = $('#example').dataTable();
and since server did not return result yet $('#example') is empty. You can put it it like this:
function showRecord(tbl) {
myDataTable.fnDestroy();
$.ajax(
{
data: "tableName=" + tbl,
url: "showTable.php",
dataType: "html",
success: function (data) {
$("#example").html(data);
myDataTable = $('#example').dataTable();
}
});
}
Try this.
function showRecord(tbl) {
//myDataTable.fnDestroy();
$.ajax(
{
data: "tableName=" + tbl,
url: "showTable.php",
dataType: "html",
success: function (data) {
$("#example").html(data);
myDataTable = $('#example').dataTable(); }
});
//alert('I get desired output as long as I do not comment/remove this alert');
//
}

Setting data-content and displaying popover

I'm trying to get data from a resource with jquery's ajax and then I try to use this data to populate a bootstrap popover, like this:
$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);
and the function for retrieving data is:
get_data_for_popover_and_display = function() {
var _data = $(this).attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}
What is happening is that the popover is NOT showing when I click, but if I hover the element later it will display the popover, but without the content (the data-content attribute). If I put an alert() inside the success callback it will display returned data.
Any idea why is happening this? Thanks!
In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display().
Don't worry! The this keyword is hairy; misinterpreting its value is a common mistake in JavaScript.
You can solve this by keeping a reference to this by assigning it to a variable:
get_data_for_popover_and_display = function() {
var el = $(this);
var _data = el.attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
el.attr('data-content', data);
el.popover('show');
}
});
}
Alternatively you could write var that = this; and use $(that) everywhere. More solutions and background here.
In addition to the answer above, don't forget that according to $.ajax() documentation you can use the context parameter to achieve the same result without the extra variable declaration as such:
get_data_for_popover_and_display = function() {
$.ajax({
type: 'GET',
url: '/myresource',
data: $(this).attr('alt'),
dataType: 'html',
context: this,
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}

Categories

Resources