Issue to enter in a condition function - javascript

In the interactive shell of Django, I got
In [1]: contract = Contract.objects.get(pk=2)
In [2]: contract
Out[2]: <Contract: Contract with David Bouchard (en)>
In [3]: contract.request.customer.convert_fax_number
Out[3]: ''
In a JavaScript function, I created a variable var fax_number = "{{ contract.request.customer.convert_fax_number }}"; and create the following if condition function
if (fax_number == '') {
alert('Please, attach the fax number to your profile');
return;
}
I put a breakpoint of the first line of that code. Hence, I know that the compiler stopped on this line, but it has never executed the statement of that if condition.
Here is the whole function :
(function($){
var bindEvents = function(node){
$('.btn-fax', node).bind('click', function(e){
e.preventDefault();
var data = {};
var fax_number = "{{ contract.request.customer.convert_fax_number }}";
$.ajax({
url : $(this).attr('href'),
type: 'POST',
data : data,
success: function(data, textStatus, jqXHR) {
if (data.success) {
if (data.redirect_to) {
window.location.href = data.redirect_to;
}
else if (data.reload) {
window.location.reload();
}
}
else {
alert('Error! See console for details :(');
console.error(textStatus, data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (fax_number == '') {
alert('Please, attach the fax number to your profile');
return;
}
console.error(textStatus, errorThrown);
}
});
return false;
});
};
and here the modification I did to convert unicode string to simple string :
#property
def convert_fax_number(self):
fax = self.fax
return unicodedata.normalize('NFKD', fax).encode('ascii','ignore')
It's not working even it the output of convert_fax_number is a simple empty string ''. How could I fix it?
Thanks in advance!

First of remember to use triple equals === when comparing strings to make sure that it's not doing weird asumptions.
Can you do a console.log('whatever') in the line on top of the if statement just to make sure that it's executing the error function? although I know that you said:
I know that the compiler stopped on this line
It's better to be completely sure.
Then, you should try with a console.log(fax_number == '') and console.log(fax_number === '') to see what's happening just below the variable declaration. Let me know what you find out.

This code is not being rendered by Django - presumably it is in a separate JavaScript file, not in a Django template. You'll need to pass the value into your JS from the actual template itself.

Related

Value of variable is not being changed (Ajax validation)

I have been dealing with these issue for a few days, and I can't seem to be able to fix it on my own. I've already asked a question here on Stack regarding this, however I've been told this is resolved by using callback functions. I've done exactly that but the variable inside the callback still isn't changed.
I am using abide validation that is built into the Foundation framework, and I am trying to have my own custom validator for checking if an email already exists in our database. Everything works, even the console.log returns the correct results, but the variable value is not changed from false to true. Only check the code from emailVerification downwards.
Thank you for your help.
$(document).foundation({
abide : {
live_validate : false, // validate the form as you go
validate_on_blur : false,
patterns: {
positive_price: /^\+?[0-9]*\,?[1-9]+$/,
},
validators: {
positiveNumber: function(el, required, parent) {
var value = el.value.replace(/,/, '.'),
valid = (value > 0);
return valid;
},
emailVerification: function (el, required, parent) {
var email = el.value,
ajax = 1,
valid = false;
function checkServer(callback) {
$.ajax({
type: "GET",
url: "/check.do?action=userEmailAvailable",
data: "userEmail1=" + email + "&ajax=" + ajax,
success: callback
});
}
checkServer(function(data) {
if (data.result == 1) {
console.log(data.result + "does not exist");
valid = true;
} else {
console.log(data.result + "already exist");
valid = false;
}
});
return valid;
}
}
}
});
the valid that you declare in positiveNumber function is locally scoped to that function only. the next time you attempt to access it outside the function you actually create a global var called valid
As many answered, you need async validation and Abide does not support this.
I would suggest you use the excellent Parsley.js library which supports async validators through its Remote plugin
$.ajax runs asynchronously. You function returns "valid" before callback function is called. You can try running your ajax request synchronously or you need to add logic in your callback function that updates "valid" when it's called
How to create sync ajax
Add validation function to you callback
checkServer(function(data) {
if (data.result == 1) {
console.log(data.result + "does not exist");
valid = true;
} else {
console.log(data.result + "already exist");
valid = false;
}
DoCoolValidation(valid)
});
If you are sure that your server validation is fast enough you can do
function Validate(dataToSend) {
return JSON.parse($.ajax({
url: '/check.do?action=userEmailAvailable',
type: "GET",
dataType: "json",
data: dataToSend,
async: false
}).responseText);}
And use it:
valid = Validate("userEmail1=" + email + "&ajax=" + ajax);
Have a look at this post. It can help

SyntaxError: expected expression, got ')'

I've been stuck at this error for a few days and still couldn't figure out what is wrong. Would be great if someone could just point me to the right direction of solving this issue.
Update:
I realise that error is gone when I commented "addMessages(xml)" in the updateMsg() function. How do I make it work then?
Error:
http://i.imgur.com/91HGTpl.png
Code:
$(document).ready(function () {
var msg = $("#msg");
var log = $("#log");
var timestamp = 0;
$("#name").focus();
$("#login").click(function() {
var name = $("#name").val();
if (!name) {
alert("Please enter a name!");
return false;
}
var username = new RegExp('^[0-9a-zA-Z]+$');
if (!username.test(name)){
alert("Invalid user name! \n Please do not use the following characters \n `~!##$^&*()=|{}':;',\\[\\].<>/?~##");
return false;
}
$.ajax({
url: 'login.php',
type: 'POST',
dataType: 'json',
data: {name: name},
success: function() {
$(".login").hide();
}
})
return false;
});
$("#form").submit(function() {
if (!msg.val()) {
return false;
}
$.ajax({
url: 'add_message.php',
type: 'POST',
dataType: 'json',
data: {message: msg.val()},
})
msg.val("");
return false
});
window.setInterval(function () {
updateMsg();
}, 300);
function updateMsg() {
$.post('server.php', {datasize: '1024'}, function(xml) {
addMessages(xml);
});
}
function addMessages(xml) {
var json = eval('('+xml+')');
$.each(json, function(i, v) {
tt = parseInt(v.time);
if (tt > timestamp) {
console.log(v.message);
appendLog($("<div/>").text('[' + v.username + ']' + v.message));
timestamp = tt
}
});
}
function appendLog(msg) {
var d = log[0]
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
msg.appendTo(log)
if (doScroll) {
d.scrollTop = d.scrollHeight - d.clientHeight;
}
}
});
It might help to read up on eval a bit. It looks like it doesn't do what you think it does.
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.
Also
There are safer (and faster!) alternatives to eval() for common use-cases.
It looks like what you're trying to do is get data from the server in the form of JSON. You'll need to make sure that your server returns something that is valid JSON, which you can verify here. Most server-side programming languages have a library that will turn an object into JSON to make that a piece of cake. Here's an example for php.
On the client-side, you'll need to change var json = eval('(' + xml + ')'); to var json = JSON.parse(xml); This will give you the javascript version of your php/perl/python/etc object. If it's an array, you can then iterate through it with a for loop, Array.prototype.forEach, or a variety of functions from different libraries, such as $.each or _.each.
SyntaxError: expected expression, got ')' usually cause by something like
exeFunction(a,b,)
See if your form submit function ajax causing such error
$("#form").submit(function() {
if (!msg.val()) {
return false;
}
$.ajax({
url: 'add_message.php',
type: 'POST',
dataType: 'json',
data: {message: msg.val()}, <-------
})
msg.val("");
return false
});
If you are triggering the java script on click or trigger any click. sometimes missing of 0 gives the above error.
delete
would JSON.stringify({datasize: '1024'}) do the trick? just a guess

Retrieving a JSON.parse() string from a server

I will start by saying that I am learning how to program in jquery/javascript, and am running into an issue using JSON.parse(). I understand the format, and why people use it... but have not been able to get it to work in any of my code projects.
I have read in books/online on here in how to use it, but I think I read too much on it. I am now confused and second guessing what I know about it.
With that said, my jquery/javascript class I am taking is asking me to use it for an assignment, through AJAX using MAMP/localhost as the server.
The two codes below are for the section that I need to fill in the //TODO information. One is javascript (client-side), the other is php (server-side). I think that I've set the other //TODO information correctly, but I keep getting a token error for the JSON part.
I looked on here for a solution, but again, I think I've confused myself badly and need help. Appreciate any feedback, insight, or information.
-Javascript-
var calculateMpg = function () {
// These lines are commented out since the server will perform these checks
// if (!checkNumber("miles") || !checkNumber("gallons")) {
// return;
// }
var miles = $("#miles").val();
var gallons = $("#gallons").val();
console.log("ajax request issued.");
var result;
$.ajax({
url: "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons,
cache: false,
dataType: "text",
success: function(msg) {
console.log("ajax response received.");
// TODO: parse the JSON string returned from the server (see JSON.parse())
JSON.parse("result");
if (result.status === 'success') {
// TODO: get the mpg value returned from the server and display it to the user.
$("#mpg").val($_GET("result"));
console.log("JSON Working!");
}
else {
// TODO: get the name of the variable with the error. Hint: look at the 'fail' result from service.php
$_GET[fail(id)];
// TODO: report the error to the user using invalidNumber() function.
alert("{status: 'failure', variable: <variable name>}");
}
}
});
};
$(document).ready( function () {
$("#miles").blur(function () {
checkNumber("miles");
});
$("#gallons").blur(function() {
checkNumber("gallons");
});
$("#calculate").click(calculateMpg);
$("#miles").focus();
});
-PHP-
<?php
if ($_GET) {
if ($_GET['action'] == 'calculateMPG') {
$miles = htmlspecialchars($_GET['miles']);
$gallons = htmlspecialchars($_GET['gallons']);
// validate miles
if (strlen($miles) == 0) {
fail("miles");
}
$miles_chars = str_split($miles);
for ($i=0; $i< count($miles_chars); $i++) {
if ($miles_chars[$i] < "0" || $miles_chars[$i] > "9") {
//error_log("miles_chars check failed at: " + $i);
fail("miles");
}
}
// validate gallons
if (strlen($gallons) == 0) {
fail("gallons");
}
$gallons_chars = str_split($gallons);
for ($i=0; $i< count($gallons_chars); $i++) {
if ($gallons_chars[$i] < "0" || $gallons_chars[$i] > "9") {
fail("gallons");
}
}
// validate $miles and $gallons calling $fail along the way
$result = $miles/$gallons;
if ($result) {
success($result);
} else {
fail("mpg");
}
exit ;
}
}
function fail($variable) {
die(json_encode(array('status' => 'fail', 'variable' => $variable)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
Edited Additional 1
I have made changes to the JSON information in regard to 'var result' (thanks to several of the responses here). I'm starting to understand JSON a bit better.
Another question I have (now) is how to isolate a part of the JSON message from the whole being transmitted?
A piece of the 'JSON.parse(msg)' returned DOES include the answer to the equation miles/gallons, but I don't know how to... extract it from the JSON.
The solution to the equation miles/gallons appears in the 'msg' output.
Thanks.
Edited Additional 2
This question has been solved! While perusing around stackoverflow for a solution to the question in my previous edited section, I found my answer here: JSON response parsing in Javascript to get key/value pair.
The answer is this: under the //TODO section asking for the mpg value, I put the following code - $("#mpg").val(result.message); - which says that in the JSON section of the variable result, take the part of the JSON marked 'message', the value being the equation solution.
Thank you to all who responded with their solutions to my problem. I appreciate the fast responses, the great suggestions, and the information in understanding JSON.
-ECP03
JSON.parse() requires that you send it a valid JSON string.
"result" is not a valid JSON string. In your success function you have defined a parameter msg - what does this contain? Try console.log(msg) at the beginning of your success function and look at the console output.
You have two options:
Option 1: -- Parse the string returned.
Change JSON.parse("result"); to:
var result = JSON.parse( msg );
Option 2: -- Request JSON instead of plain text - no need to parse
Use $.getJSON() which is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Instead of parsing the JSON yourself, jQuery already provides you with a convenient function that will parse JSON:
var path = "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons;
$.getJSON(path, function (data) {
if (data.status == 'success') {
console.log('Success! Message:', data.message);
} else {
console.log('Failed :( Variable:', data.variable);
}
});
For your original code, what you would need to do is call JSON.parse(msg) in your success callback, which would return a JavaScript object with the values you sent from your PHP script. By specifying dataType: 'json' in the $.ajax call, jQuery does this for you. The $.getJSON method does this and some other things for you.
You need to use the result returned by the success function:
var result = JSON.parse(msg);
Then, you could do stuff like result.status.
When you put JSON.parse("result") you're saying "parse the string 'result'," which doesn't make any sense. However, if you say JSON.parse(msg) you're saying "Parse the variable that was returned from the ajax action," which makes sense.
JSON.parse() is used to convert your json data to object, then you can manipulate it easly.JSON.parse(msg); instead of JSON.parse("result").
For example:
var json = '{"value1": "img", "value2":"img2"}'
var obj = JSON.parse(json);
for ( k in obj ) {
console.log(obj[k])
}
This is totally wrong: JSON.parse("result");. .parse() expects a JSON string, e.g. the string that came back from you ajax request. You're not providing that string. you're providing the word result, which is NOT valid JSON.
JSON is essentially the right-hand side of an assignment expression.e.g.
var foo = 'bar';
^^^^^---this is json
var baz = 42;
^^---also json
var qux = ['a', 'b', 'c'];
^^^^^^^^^^^^^^^---even more json
var x = 1+2;
^^^---**NOT** json... it's an expression.
What you're doing is basically:
var x = parse;
^^^^^^---unknown/undefined variable: not JSON, it's an expression

jQuery Ajax call object property scope

I have been working on a peske problem the last few days. I have created an object to handle a login script. The login script is processed by a PHP script witch echo's out a json object:
{'status' : true} // could also be false
The ajax request completes everytime and I can console.log() it. The problem is in the callback function. I have tried the following allowable parameters/functions from the docs:
complete
success
.done()
In the call back I am attempting to set an object property/variable depending on the return. It does not see this assignment until the second time the script is run. I am assuming it is because something runs before the other or a scope issue?
So to clarify:
Lets say the script runs and I get back true. I then want to set the status of the object property to that instead of false. I put a console.log() inside the callback and that works everytime however the main object wont see it unless i submit it twice.
Here is the code. Any and all help is appreciated:
var loginAuth = {
form : $('form'),
status : false,
init : function() {
loginAuth.ajaxCall();
},
ajaxCall : function(loginData) {
// Get Post variables
var loginData = {
username : $('input[name=username]').val(),
password : $('input[name=password]').val()
};
// Proccess the form
$.ajax(
{
url : "http://localhost/url-where-results-are",
dataType : "json",
type : "post",
data : loginData,
}).done(function(data) {
if(typeof data != 'object')
{
$.parseJSON(data);
} else {
loginAuth.status = data;
console.log(loginAuth.status);
}
});
}
} //// END loginAuth Object ////
You have some things wrong. You only want to $.parseJson if it is an object. Furthermore, you do not need to call that as jQuery handles the parsing for you.
if(typeof data != 'object')
{
$.parseJSON(data);
} else {
loginAuth.status = data;
console.log(loginAuth.status);
}
This would be correct:
if(typeof data == 'object') {
alert(data.status);
if(data.status == true) {
loginAuth.status = true;
} else {
loginAuth.status = false;
}
} else {
console.log(data);
}

Return String From XHRGet

I'm creating a tree using Dojo and two seperate sets of data. One set of data makes up the main tree structure. The second set of data is dependent on a value from the first set. I'm using xhrGet and Dojo 1.7.3 to get the data.
Once the second set of data has been returned, I'm looking at the values of the JSON to determine a value of a variable, that's then passed into the tree. The variable displays a "!" if an "alert" value is present in the JSON returned and blank if there isn't.
var theAlert = dojo.xhrGet({
url: proxy + serviceurl + targetId,
handleAs: 'json',
load: function(data){
if(typeof data.alerts[0] != 'undefined'){
var hello = "!";
return hello;
}
else{
console.log("There is nothing there");
},
error: function(error){
console.log(error)
}
});
The problem I'm having is that when I write "theAlert" variable where I need to, it appears as "[object Object]" and not as "!".
I feel like I'm doing something wrong, but I can't figure out what.
I have already tried using theAlert.valueOf(); to no success. Help?
The data is received correctly as well, I can view it via console log.
dojo.xhrGet() returns a Deferred - http://dojotoolkit.org/reference-guide/1.9/dojo/Deferred.html
You need to do something like:
var deferred = dojo.xhrGet({
url: proxy + serviceurl + targetId,
handleAs: 'json'
});
deferred.then(
function(data){
if(typeof data.alerts[0] != 'undefined'){
processAlert("!");
} else{
console.log("There is nothing there");
}
},
function(error){
console.log(error)
}
);
function processAlert(a) {
alert(a);
}
Look at the docs.
You need to return data, not hello.

Categories