Javascript function does not exist - javascript

I have following Javascript code that creates a button element that has a click event.
function Button(id, url, blockMsg){
var id = id;
var url = url;
var blockMsg = blockMsg;
var message;
this.getId = function(){
return id;
};
this.getMessage = function(){
return message;
};
block = function(msg){
$.blockUI({
message: msg
});
};
unblock = function(){
$.unblockUI();
};
showErrors = function(){
console.log('errors');
}
$(id).bind('click', function(){
$.ajax({
url: url,
type: 'POST',
beforeSend: function(){
block(blockMsg);
},
error: function(response){
message = $.parseJSON(response);
message.action();
unblock();
console.log(action);
},
success: function(response){
message = $.parseJSON(response);
[message.action]();
unblock();
console.log(action);
}
});
});
};
$(document).ready(function(){
var buttonRegister = new Button('#btnCompanyRegister', '/company/register/', 'register ...');
});
When I click on the button everything works fine and my PHP script returns
json_encode(array('action' => 'showErrors'));
In FireBug I can see the error: ["showErrors"] is not a function
What am I doing wrong? Why is there no function specified? Do I have a scope problem?
Thank you for your help.

Instead of [message.action](); use window[message.action]();.
message.action is the string "showErrors" - which is not a function. You can get the global function showErrors from the window object.

There's missing ; after function declaration.
showErrors = function(){
console.log('errors');
};

Related

variable not redefining jquery

So, I've created my first function in jQuery. Now I have problems redefining a variable in my function.
fileValid is not defining to what I need it to. As you can see in my ajax call, if(result=="true"){fileValid = false; }else{ fileValid = true;}. Here fileValid is not being redefined and stays it's default value.
Here is my code:
(function( $ ) {
$.fn.checkFile = function(file){
var fileValid = true;
var form_data = new FormData();
form_data.append("op", "235353")
form_data.append("file", file);
$.ajax({
url:"ajax/scripts/message.php?w=<?php echo $workspace_id?>",
type:"POST",
data:form_data,
contentType: false,
processData:false,
success:function(data){
var result = $.trim(data);
if(result=="true"){fileValid = false; }else{ fileValid = true;}
}
});
return fileValid;
}
}( jQuery ));
Ajax is async, so you can't return its results like that. Use callbacks:
$.fn.checkFile = function(file, complete){
...
success: function(data){
var result = $.trim(data);
complete(result=="true" ? true : false);
});
Or even:
$.fn.checkFile = function(file, valid, invalid){
...
success: function(data){
var result = $.trim(data);
if (result=="true") { valid(); } else { invalid(); }
});
Now, if you have a global variable fileValid you can redefine it like:
$(...).checkFile("myFile", function() {
fileValid = true;
});

Close the Chrome Extension automatically

I am trying to close the extension automatically after saving my data.
Here is the code which is used to save the data:
$(function(){
function displayMessage(string){
alert(string);
}
var submit = $('#submit');
$('#create').submit(function(){
$('#loading_image').html('<img src="images/wait.gif">');
var user_email = localStorage.getItem('email');
var api = localStorage.getItem("user_api_key");
var auth = "apikey" +' ' +(user_email+":"+api);
var favicon_key = localStorage.getItem("favicon_image_key");
var peoples = [];
var tags_peoples = $("#s2id_people .select2-choices .select2-search-choice");
for (i=0; i<tags_peoples.length; i++) {
peoples.push({"label": tags_peoples[i].childNodes[1].textContent})
}
var subjects = [];
var tags_subjects = $("#s2id_subjects .select2-choices .select2-search-choice");
for (i=0; i<tags_subjects.length;i++) {
subjects.push({"label": tags_subjects[i].childNodes[1].textContent})
}
var places = [];
var tags_places = $("#s2id_places .select2-choices .select2-search-choice");
for (i=0; i<tags_places.length; i++) {
places.push({"label": tags_places[i].childNodes[1].textContent})
}
var begin = $(".daterangepicker_start_input")[0].childNodes[1].value;
var end = $(".daterangepicker_end_input")[0].childNodes[1].value;
var data = {
'content': $('#title').val(),
'people': peoples,
'subjects': subjects,
'begin_date': begin,
'end_date': end,
'places': places
}
$.ajax({
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
url: "https://my_site_url/api/v3/data/",
dataType: "json",
data: JSON.stringify(data),
contentType: "application/json",
success: function(data) {
$('#loading_image').hide();
window.location.href = 'saved.html';
setTimeout(function(){
window.close();
}, 2000);
},
error: function(data) {
$('#div1').text("Error on saving the data");
$('#loading_image').hide();
},
complete: function() {
submit.removeAttr('disabled').text('Save');
}
});
return false;
});
});
I am using this to close the extension
setTimeout(function(){window.close();}, 3000);
But this doesn't work. Should I write any EventListener to close the extension automatically?
Appreciated the answers
Consider this snippet from your code:
window.location.href = 'saved.html';
setTimeout(function(){
window.close();
}, 2000);
This will not work. As soon as you change location, the page starts to navigate away, eventually wiping the window state and all timeouts set when the new page loads.
You need to set the timeout from saved.html for this to work.

jquery iframe load dynamically

I am using following jquery script to load another url after successful ajax request.
$(document).ready(function() {
var $loaded = $("#siteloader").data('loaded');
if($loaded == false){
$("#siteloader").load(function (){
if(ad_id != undefined){
var req_url = base_url+'ajax/saveclick/'+ad_id+'/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function() {
$(preloader).show();
$('#adloading').remove();
},
complete: function() {
$(preloader).hide();
},
success: function(result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url+'userpanel/cpa/'+ad_id+'/');
}
});
}
else{
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
});
}
});
<iframe src="remote_url" id="siteloader"></iframe>
I don't want to run ajax again after changing src on iframe and i have also tried to stop it by $("#siteloader").data("loaded", "true");
Please suggest me a good solution for this. thanks.
If you only want to execute the "load" handler once
Simply add the line
$("#siteloader").unbind('load');
In the success callback.
If you want the "load" handler to be executed on each src change, you may do something like that :
$(document).ready(function () {
$("#siteloader").load(function () {
// Move the test in the event Handler ...
var $loaded = $("#siteloader").data('loaded');
if ($loaded == false) {
if (ad_id != undefined) {
var req_url = base_url + 'ajax/saveclick/' + ad_id + '/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function () {
$(preloader).show();
$('#adloading').remove();
},
complete: function () {
$(preloader).hide();
},
success: function (result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url + 'userpanel/cpa/' + ad_id + '/');
}
});
}
else {
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
}
});
});
Maybe your ad_id variable is not well defined / changed ...

I don't understand AJAX callbacks

I have a javascript function which executes on the change of a dropdown:
<script type="text/javascript">
$(function()
{
// Executes when the status dropdown changes value
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
})
</script>
I am trying to get the alert call to show the return value of the following php code (which is true):
<?php
.
.
.
return true;
?>
The alert doesn't pop up. Anyone know why ???
I tried your code with another URL and it's working well.
There are three cases:
scriptUrl is not calculated properly and doesn't point to your PHP script
your server is down
you are accessing an URL not served under the same domain as the one of your script (same-origin policy)
You can see detail of your error if you add an error handler to ajax parameters :
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");
Try this
$(document).ready(function(){
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
});

Callback never called on Jquery.post();

I'm having some trouble using JQUERY Post function.
I have 2 functions that call JQUERY Post function.
Both of them is working fine, but the callback function is never called (handleLike).
When I call handleLike manually, it's works perfect.
(Even if handleLike has just an alert inside, the callback function is not called)
Could you please help me with this thing?
<script type="text/javascript">
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
if (v_cb.class == 'map'){
var elemento = $('#maplike');
}else{
var elemento = $('#commentlike'+v_cb.id);
}
if (!(elemento.hasClass('disabled'))){
elemento.addClass("disabled");
var likes = elemento.find('font').text();
likes++;
elemento.find('font').html(likes);
}
}
$('#maplike').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
var JSONObject= {
"mensagem":"Testando Json",
"id":86,
"class":"map"
};
handleLike(JSONObject);
alert("Teste");
$.post(
'/cmap/maps/like',
{ id: id },
handleLike,
'json'
);
}
});
$('[id*="commentlike"]').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
$.post(
'/cmap/comments/like',
{ id: id },
handleLike,
'json'
);
}
});
});
</script>
Diagnostic, not solution
Rationalizing and adding an error handler, you should get something like this :
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
var elemento = (v_cb.class && v_cb.class == 'map') ? $('#maplike') : $('#commentlike'+v_cb.id);
if (!elemento.hasClass('disabled')){
var f = elemento.addClass("disabled").find('font');
f.html(++Number(f.text()));
}
}
function ajaxError(jqXHR, textStatus, errorThrown) {
alert('$.post error: ' + textStatus + ' : ' + errorThrown);
};
$('#maplike').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/maps/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
$('[id*="commentlike"]').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/comments/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
});
untested
Barring mistakes, there's a good chance the error handler will inform you of what's going wrong.
I follow the Kevin B tip and use $ajax method.
It was a parseerror. Sorry.
The return of v_cb was not a json, it was a html. I correct my return, and everything was ok.

Categories

Resources