Heyho,
I got a function to get cookies and it works fine (except the if-part in getCookies()):
function getCookies(domain, name, callback) {
chrome.cookies.get({"url": domain, "name": name}, function(cookie) {
if(callback) {
callback(cookie.value);
}
});
}
//USER ID
getCookies("http://free-way.me", "uid", function(id) {
if(id == null) { document.getElementById("submulti").disabled = true;}
else { document.getElementById("user").value = id;}
});
Well, when there's no cookie the console gives me this:
Error in response to cookies.get: TypeError: Cannot read property 'value' of null
at getCookies [...]
No surprise, but I don't know how to check if the the request worked, and return the error to disable the submit-button.
It would be nice if you could help me..
Thank you,
Markus
Why not just throw in a quick extra check on the value of cookie before attempting to access the value attribute?
chrome.cookies.get({'url': domain, 'name': name}, function(cookie) {
if (callback) {
callback(cookie ? cookie.value : null);
}
});
The ternary check there will make sure you return null when cookie is null. Let me know if that wasn't your question!
Related
What I'm trying to do is return the result of a function in Python back to my javascript through AJAX. Currently I am getting This Response while I'm expecting "True" or "False"
jquery:
var test = $.getJSON("/chk_chn", {
name: channel_name
});
alert(test.toSource())
python:
#app.route("/chk_chn")
def chk_chn_unique():
"""Checks a name against all existing Channels in a Channel List. Returns True if name is unique, False otherwise"""
name = request.args.get("name")
for channel in Channels:
if channel.get_name() == name:
return jsonify(result=False)
return jsonify(result=True)
Have you tried:
return jsonify({result: True})
You're missing your callback function and just printing out the request object.
Try this:
$.getJSON('/chk_chn', { name: channel_name })
.done(function (data) {
console.log(data);
});
I had several problems.
First, my Ajax query did not have any callback function. Thanks to Rawri for pointing that out. The code is now the following.
$.getJSON("/chk_chn", { name: channel_name} )
.done(function( json ) {
console.log(json.result)
// Check Name Uniqueness
if (json.result === false) {
$("#chn_name").after('<span class="error">Channel name already exists</span>');
}
else {
// Check Channel Length
if (channel_name.length > 20) {
$("#chn_name").after('<span class="error">Channel Name exceeds maximum length</span>');
return false
}
else {
// Create Channel
socket.emit("create_channel", {"channel_name": channel_name})
// Close the modal
return true;
}
}
})
.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
});
My second and even more stupid issue was that the Ajax query was being called by a button that existed in a Modal. When the button was clicked, the Modal was closed and the javascript was regenerated on the new page, thus discarding my query entirely.
I fix this by returning false on my form
<form role="form" id="submit_channel" onsubmit="return false">
So I am trying to write javascript code for a ribbon button in Dynamics CRM 2016 that will grab a phone number from a list of Leads that can be seen in the Active Leads window.
However, when I try to run it, I get an error telling me
As I step into my code (I'm debugging), I see this error
Here is the code I am working with.
function updateSelected(SelectedControlSelectedItemIds, SelectedEntityTypeName) {
// this should iterate through the list
SelectedControlSelectedItemIds.forEach(
function (selected, index) {
//this should get the id and name of the selected lead
getPhoneNumber(selected, SelectedEntityTypeName);
});
}
//I should have the lead ID and Name here, but it is returning null
function getPhoneNumber(id, entityName) {
var query = "telephone1";
Sdk.WebApi.retrieveRecord(id, entityName, query, "",
function (result) {
var telephone1 = result.telephone1;
// I'm trying to capture the number and display it via alert.
alert(telephone1);
},
function (error) {
alert(error);
})
}
Any help is appreciated.
What you have is an javascript error. In js you can only use forEach on an array. SelectedControlSelectedItemIds is an object not an array.
To loop though an object, you can do the following.
for (var key in SelectedControlSelectedItemIds){
if(SelectedControlSelectedItemIds.hasOwnProperty(key)){
getPhoneNumber(SelectedControlSelectedItemIds[key], SelectedEntityTypeName)
}
}
Okay, so I figured it out. I had help, so I refuse to take full credit.
First, I had to download the SDK.WEBAPI.
I then had to add the webAPI to my Javascript Actions in the Ribbon Tool Bench.
Then, I had to create a function to remove the brackets around the
SelectedControlSelectedItemIds
Firstly, I had to use the API WITH the forEach method in order for it to work.
These are the revisions to my code.
function removeBraces(str) {
str = str.replace(/[{}]/g, "");
return str;
}
function updateSelected(SelectedControlSelectedItemIds, SelectedEntityTypeName) {
//alert(SelectedEntityTypeName);
SelectedControlSelectedItemIds.forEach(
function (selected, index) {
getPhoneNumber(removeBraces(selected), SelectedEntityTypeName);
// alert(selected);
});
}
function getPhoneNumber(id, entityName) {
var query = "telephone1";
SDK.WEBAPI.retrieveRecord(id, entityName, query, "",
function (result) {
var telephone1 = result.telephone1;
formatted = telephone1.replace(/[- )(]/g,'');
dialready = "1" + formatted;
withcolon = dialready.replace(/(.{1})/g,"$1:")
number = telephone1;
if (Xrm.Page.context.getUserName() == "Jerry Ryback") {
url = "http://111.222.333.444/cgi-bin/api-send_key";
} else if(Xrm.Page.context.getUserName() == "Frank Jane") {
url = "http://222.333.444.555/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Bob Gilfred"){
url = "http://333.444.555.666/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Cheryl Bradley"){
url = "http://444.555.666.777/cgi-bin/api-send_key";
}
else if( Xrm.Page.context.getUserName() == "Bill Dunny"){
url = "http://555.666.777.888/cgi-bin/api-send_key";
}
if (url != "") {
var params = "passcode=admin&keys=" + withcolon + "SEND";
var http = new XMLHttpRequest();
http.open("GET", url + "?" + params, true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
}
},
function (error) {
// alert(error);
})
}
To elaborate, once I successfully get the number, I remove the parenthesis, dashes and white-space. Then, I add a "1" to the beginning. Finally, I insert colons in between each number. Then, I create an HTTP command and send it to the office phone of whoever is using CRM at the time. The user eval and HTTP message is my code. I'm showing you all of this because it was a great learning experience, and this feature really adds to the functionality.
I hope some of you find this useful.
Thanks for the help.
I am using an AJAX call to a web method to validate a user, and when the web call returns, I am trying to use this code to populate sessionStorage with an object so I can then access the user's information from other pages:
success: function (r) {
var info = JSON.parse(r.d);
if (info.Reply == 'OK')
{
$('#signinForm').html("<p>You're logged in!</p>");
var MemberObject = { 'MemberName': $('#MemberName').val() };
sessionStorage.setItem('MemberObject', JSON.stringify(MemberObject));
}
},
error: function (r) {
alert(r.responseText);
},
failure: function (r) {
alert(r.responseText);
}
To test this, I added this block of code at the top of the page to replace the login dialogue with a welcome message for a logged-in user by retrieving the object I added to sessionStorage, but it doesn't work:
$(document).ready(function () {
function isObject(val) {
if (val === null) { return false; }
return ((typeof val === 'function') || (typeof val === 'object'));
}
var mObj = sessionStorage.getItem('MemberObject');
if (isObject(mObj))
{
var data = JSON.parse(mObj);
$('signinForm').html("<p>Welcome, " + data.MemberName + "!</p>");
}
Why doesn't sessionStorage working?
As #nnnnnn said in comment, the if (isObject(mObj)) condition will always return false. mObj is a string at that point in time. To resolve the problem, use JSON.parse() before the condition instead of after it, or use a different condition.
I made an if and else statement in Javascript, but I can't get it to work.
This is my code, I hope you people will see whats wrong
var int = "";
function fbLoop (userLoop)
{
int=setInterval(function(){fbCheckloop(userLoop)},1000);
}
function fbCheckloop(userCheck)
{
if(userCheck.login != 'false')
{
window.clearInterval(int);
console.log(userCheck);
fbUpload(userCheck);
}
else
{
$.get("uploadtofb.php", {functie: "checklogin", fotonaam: userCheck.fotonaam}, fbCheckloop);
}
}
The if(userCheck.login != 'false') doesn't work.
The console.log(userCheck); shows this
{"login":"false","fotonaam":"NAME"}
So according to the console log he have to do the else, but he does the if statement.
What did I do wrong?
The userCheck is coming from this:
return json_encode($checklog = array(
'login' => 'false',
'fotonaam' => $_GET['fotonaam']
));
Are you sure that userCheck is a JavaScript object, and not a JSON string that has to be parsed? Your current console log result makes me suspect that it is. What does console.log(typeof userCheck) yield?
If it is, use
userCheck = JSON.parse(userCheck)
if userCheck.login is having boolean value false, use if(userCheck.login != false).
No quotes required around false.
I'm trying to break/return false if a $.post() response is null, by doing so:
....
$('#order_list li > div').remove(); // is to remove `no_data` or `search_box` when clicking on the next `li`
$.post('do.php', { OP: "news_search", category: cat_id },
function(data_response){
console.log(data_response); //outputs null if nothing retrieved, or data if otherwise
if(data_response==null) //stop code if the response is null
{
alert('if works');
$(this).append(no_data).show('slow');
return false; // doesn't do the trick
}
}, "json");
//if not null, continue with this
if( ! $('.search_box').exists())
{
$(this).append(search_box).show('slow');
}
....
But as you could read, my code doesn't do the trick. Any ideas?
UPDATE
the if(data_response==null) works, it's the return false that doesn't do its job
The A in AJAX is for Asynchronous.
When you get to the point where you want to check, it has already executed.
First you run this code:
$.post('do.php', { OP: "news_search", category: cat_id }, callback, "json");
This issues an XmlHttpRequest to the server. I intentionally wrote only callback, because the function is just passed as a parameter. It will only run when the server responded. By that time, the other parts of your code have already run.
$.post() - call to the server
the rest of your code
when the server responded, your callback
$.post('do.php', { OP: "news_search", category: cat_id },
function(data_response){
console.log(data_response);
if(data_response)
{
$(this).append(no_data).show('slow');
// return false; NOT NEEDED
} else {
// below condition should remain here, not outside of Ajax
if( ! $('.search_box').exists()){
$(this).append(search_box).show('slow');
}
}
}, "json");
People usually verify doing the following:
if (foo == null) {
foo = "Joe";
}
When what they really mean is
if (!foo) {
foo = "Joe";
}
Its because null is an object and == does type coercion.
More info in this article: JavaScript undefined vs. null