javascript works on localhost but fails on hosting server - javascript

When i click on add-to-basket button i see an error which appears in my browser console saying :
Here is my basket.js file :
$(document).ready(function() {
initBinds();
function initBinds() {
if ($('.remove_basket').length > 0) {
$('.remove_basket').bind('click', removeFromBasket);
}
if ($('.update_basket').length > 0) {
$('.update_basket').bind('click', updateBasket);
}
if ($('.fld_qty').length > 0) {
$('.fld_qty').bind('keypress', function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
updateBasket();
}
});
}
}
function removeFromBasket() {
var item = $(this).attr('rel');
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket_remove.php',
dataType: 'html',
data: ({ id: item }),
success: function() {
refreshBigBasket();
refreshSmallBasket();
},
error: function() {
alert('An error has occurred');
}
});
}
function refreshSmallBasket() {
$.ajax({
url: '/home/u919084925/public_html/mod/basket_small_refresh.php',
dataType: 'json',
success: function(data) {
$.each(data, function(k, v) {
$("#basket_left ." + k + " span").text(v);
});
},
error: function(data) {
alert("An error has occurred");
}
});
}
function refreshBigBasket() {
$.ajax({
url: '/home/u919084925/public_html/mod/basket_view.php',
dataType: 'html',
success: function(data) {
$('#big_basket').html(data);
initBinds();
},
error: function(data) {
alert('An error has occurred');
}
});
}
if ($(".add_to_basket").length > 0) {
$(".add_to_basket").click(function() {
var trigger = $(this);
var param = trigger.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket.php',
dataType: 'json',
data: ({ id : item[0], job : item[1] }),
success: function(data) {
var new_id = item[0] + '_' + data.job;
if (data.job != item[1]) {
if (data.job == 0) {
trigger.attr("rel", new_id);
trigger.text("Remove from basket");
trigger.addClass("red");
} else {
trigger.attr("rel", new_id);
trigger.text("Add to basket");
trigger.removeClass("red");
}
refreshSmallBasket();
}
},
error: function(data) {
alert("An error has occurred");
}
});
return false;
});
}
function updateBasket() {
$('#frm_basket :input').each(function() {
var sid = $(this).attr('id').split('-');
var val = $(this).val();
$.ajax({
type: 'POST',
url: '/home/u919084925/public_html/mod/basket_qty.php',
data: ({ id: sid[1], qty: val }),
success: function() {
refreshSmallBasket();
refreshBigBasket();
},
error: function() {
alert('An error has occurred');
}
});
});
}
// proceed to paypal
if ($('.paypal').length > 0) {
$('.paypal').click(function() {
var token = $(this).attr('id');
var image = "<div style=\"text-align:center\">";
image = image + "<img src=\"/images/loadinfo.net.gif\"";
image = image + " alt=\"Proceeding to PayPal\" />";
image = image + "<br />Please wait while we are redirecting you to PayPal...";
image = image + "</div><div id=\"frm_pp\"></div>";
$('#big_basket').fadeOut(200, function() {
$(this).html(image).fadeIn(200, function() {
send2PP(token);
});
});
});
}
function send2PP(token) {
$.ajax({
type: 'POST',
url: '/mod/paypal.php',
data: ({ token : token }),
dataType: 'html',
success: function(data) {
$('#frm_pp').html(data);
// submit form automatically
$('#frm_paypal').submit();
},
error: function() {
alert('An error has occurred');
}
});
});
I tried to resolve it but couldn't find a proper solution.
Help me with this, I cannot understand the cause of this error.

This is mainly due to Rules of Origins (CORS), for some reason the javascript(browser) sees the request as not residing in the same server. And the reason for that, I believe, is because /home/u919084925/public_html/mod/basket.php is not seen as a valid url on the server, it should start with http://{hostname}/{path}.

It looks like your ajax url is totally wrong and the browser interpret that is cross origin ajax request. Please simply check in browser's address bar if your ajax provided urls are valid.

Related

How can I console "Sucess" present on $.ajax?

How can I show "success" up on Console screen? In a nutshell, I want to show on Console the erros that I forced to happen in a register formulary.
function getRoot() {
var root = "http://" + document.location.hostname + "/login_AMUBA/";
return root;
}
$("#formCadastro").on("submit", function (event) {
event.preventDefault();
var dados = $(this).serialize();
function response() {
return $.ajax({
url: getRoot() + 'controllers/controllerCadastro',
type: 'post',
dataType: 'json',
data: dados,
success: function (response) {
console.log(response);
}
});
}
if (response) {
console.log(success);<--Here
}
});
Finally, the final function (on a php file) should show the error(errors) on console screen, but only "else" works (when it is not commented)
public function validateFinalCad($arrVar)
{
if (count($this->getErro()) > 0) {
$arrResponse = [
"retorno" => "erro",
"erros" => $this->getErro()
];
} else {
/*$this->cadastro->insertCad($arrVar);*/
}
return json_encode($arrResponse);
}

jQuery Execute function after asynchronous data load

I have created a jQuery function extending its own object $. This function translate those elements attached to the element this:
$.fn.extend({
translate: function(sourceLang, targetLang) {
if($(this).text().trim().length < 1 || !isNaN(parseInt($(this).text().trim())) || sourceLang == targetLang)
return;
let $function = this;
$($function).each(function() {
let $each = this;
$.ajax({
url: 'https://translate.yandex.net/api/v1.5/tr.json/translate',
method: 'GET',
dataType: 'JSONP',
crossDomain: true,
data: {
key: /* my-secret-key */,
text: $($each).text(),
lang: sourceLang + '-' + targetLang
},
success: function(response) {
try {
if(response.code !== 200)
throw "Response: " + response.code;
$($each).text(response.text[0])
} catch(error) {
console.error('Translation error on element: ', $($function).text());
console.error('Message returned by the server:', error);
}
},
error: function(xhr, status, error) {
console.error('Translation error on element: ', $($function).text());
console.error('Message returned by the server:', xhr.responseText);
}
});
});
}
});
After loading the code I do this:
$(document).ready(function() {
let lang = $('html').attr('lang').split('-')[0];
$('td td:visible').translate(lang, "en");
});
Note: the HTML tag looks like this <html lang="es-ES"> depending on the logged user language.
The issue I have is the table loads after a couple of seconds (since we are not in Production environment they could be more than 30). Therefore the previous code block is not useful.
Note: the <tbody> tag is created when the data is added.
What I have tried is:
1. Create a setInterval() and clearInterval() when the $('td:visible').length is greater than 0:
let iv = setInterval(function() {
let lang = $('html').attr('lang').split('-')[0];
let rows = $('tbody td:visible');
if(rows.length > 0) {
rows.translate(lang, "en");
clearInterval(iv);
}
}, 1000);
2. Set a .delay() before the translation:
let isTranslated = false;
while(!isTranslated) {
let lang = $('html').attr('lang').split('-')[0];
let rows = $('tbody td:visible');
if(rows.length > 0) {
rows.delay(1000).translate(lang, "en");
isTranslated = true;
}
}
The memory consumed by the browser is greater than 200MB. I also tried with $('table').on('DOMSubstreeModified', 'tbody', function() {}) but it didn't work.
So, what approach would you recommend to use this translation plugin on this table after it loads its tbody?
Edit 1:
I have changed my code so I perform less API requests, thanks to the recommendation of #lucifer63:
let $function = this;
let collection = [];
let translation = '';
$(this).each(function() {
collection.push($(this).text());
});
let text = collection.join('::');
$.ajax({
url: 'https://translate.yandex.net/api/v1.5/tr.json/translate',
method: 'GET',
dataType: 'JSONP',
crossDomain: true,
data: {
key: /* my-secret-key */,
text: text,
lang: sourceLang + '-' + targetLang
},
success: function(response) {
try {
if(response.code !== 200) {
throw "Response: " + response.code;
}
translation = response.text[0].split('::');
$($function).each(function() {
$(this).text(translation.shift());
});
} catch(error) {
console.error('Message returned by the server:', error);
}
},
error: function(xhr, status, error) {
console.error('Message returned by the server:', xhr.responseText);
}
});
But still, I need to figure out how to print after data has loaded.
Well... I think I found the answer I was seeking:
$('body').on('DOMNodeInserted', 'table', function() {
$('td:visible').translate('es', 'en');
});
It seems it is working correctly.

Ajax callback is firing after function call

Hi Have a ajax call in a function thats called on date input change event to check if a date is already in use for User. the success in the Ajax call fires after the click function is finished.
How do I get the success results and continue on with the #datepicker change funtion as I need the json results for rest of function.
controller
public ActionResult IsDateAvailable(DateTime date, int Id) {
var dateAvailable = !(_context.Trading.Any(t => t.uId == Id && t.TradingDate == date));
if (!(dateAvailable)) {
return Json(new {
status = false, msg = "This date already exists."
});
}
return Json(new {
status = true
});
}
JavaScript
$(document).ready(function() {
var message;
var isDateValid;
function CheckDate(para) {
var dateValid;
var mesg;
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}
$("#datePicker").change(function() {
$("#alert").css({
'display': 'none'
});
if (Id == 0) {
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text('Please select a User.');
$("#alert").show();
return false;
}
var date = $(this).val();
var para = {
date: date,
Id: Id
};
CheckDate(para);
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
});
});
You should turn to being asynchronous. change your code to match with these:
.
.
.
function CheckDate(para) {
return new Promise((resolve, reject) => {
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
resolve();
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
reject();
}
});
}
.
.
.
checkDate(para).then(res => {
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
}).catch(err => { /* do something */ });
You just need to set async: false inside your ajax request. You can also remove the word return from the CheckDate, because of it's redundant:
function CheckDate(para) {
var dateValid;
var mesg;
$.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
async: false,
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}

How can I post message in Yammer Group with link user?

Yammer REST api json. My code send message in group succesfull. But I need to send msg with "cc", link some user, like this:
function yamPostRequest(val) {
var msg_value = document.getElementById('msg_body').value;
var groupID = document.getElementById('group_id').value;
if (msg_value == "") {
alert("Message body cannot be empty!");
return false;
}
if (groupID == "") {
var conf = confirm("Group ID is empty, message will be posted to All Company");
if (conf == false) {
return false;
}
}
yam.platform.request({
url: "https://api.yammer.com/api/v1/messages.json",
method: "POST",
data: {
"body": msg_value,
//"title" : msg_title,
"group_id": groupID,
},
success: function(msg) {
alert("Post was Successful!");
},
error: function(msg) {
alert("Post was Unsuccessful");
}
})
}
I found it.
function PostYammerWithNotification(group_id, message, userCC) {
var yammerData;
yammerData = {
group_id: group_id,
body: message
};
yammerData.cc = "[[user:" + userCC + "]]";
yam.platform.request({
url: "https://api.yammer.com/api/v1/messages.json",
method: "POST",
data: yammerData,
success: function(msg) {
alert("Post was Successful!");
},
error: function(msg) {
alert("Post was Unsuccessful");
}
});
}
You need to use user ID:
PostYammerWithNotification(/*Group ID*/,"test msg",/*User ID*/)
Found it here

django request.user.is_authenticated() isn't returning true after page refresh (sometimes)

I have a registration form. After it is submitted, the page refreshes and I get some information back based on request.user. Sometimes request.user.is_authenticated() is returning True and everything works fine.... and sometimes False seemingly randomly.
I appreciate any insight into why this might be happening.
Registration form code
$('#reg_form').submit(function(e) {
e.preventDefault();
e.stopPropagation();
var serializedData = $(this).serializeArray();
var names = serializedData.map(function(r) {
return r.name;
});
var index_user = names.indexOf("regusername");
var index_pass = names.indexOf("regpassword1");
var index_email = names.indexOf("regemail");
var data2 = {};
data2["username"] = serializedData[index_user].value;
data2["password1"] = serializedData[index_pass].value;
data2["password"] = serializedData[index_pass].value;
data2["password2"] = serializedData[index_pass].value;
data2["email"] = serializedData[index_email].value;
console.log(data2);
var serializedFormData = $(this).serialize();
$.ajax({
url: window.url_root + '/accountsjson/register/',
type: 'POST',
dataType: 'json',
data: data2,
success: function(data) {
console.log(data); //remove
if (data.hasOwnProperty('success')) {
console.log("successful registration detected!!");
utils.loginAfterRegister(data2);
$('.register').slideUp();
$('.frame').hide();
} else {
utils.showRegister();
}
},
error: function() {
console.log("ERROR posting registration request. Abort!");
},
});
Function called from loginAfterRegister which has the refresh
function sendRating(rating, reload_on_return) {
$.ajax({
type: "POST",
dataType: 'json',
url: window.url_root + "/savecommentrating/1/" + rating.cid + "/",
data: {
"rating": rating.r2 / 100.0
},
success: function(data) {
if (data.hasOwnProperty('success')) {
console.log("data was sent!");
if (reload_on_return) {
location.reload();
}
}
},
error: function() {
console.log("rating didn't get sent!!");
}
})
}
mobile function within views.py
def mobile(request):
create_visitor(request)
os = get_os(1)
disc_stmt = get_disc_stmt(os, 1)
return render_to_response('mobile.html', context_instance = RequestContext(request, {'url_root' : settings.URL_ROOT,
'loggedIn' : str(request.user.is_authenticated()).lower(),
'client_data': mobile_client_data(request),
'client_settings': get_client_settings(True),
}))
create_visitor()
def create_visitor(request):
# See if we need to create a visitor here
if not request.user.is_authenticated() and not request.session.get('visitor_id', False):
visitor = Visitor()
visitor.save()
request.session['visitor_id'] = visitor.id

Categories

Resources