ajax post data error [object HTMLCollection] - javascript

I wrote this script to for a contact form on my website, everything works however instead of storing the data in me database all is get is
[object HTMLCollection] c
an anyone tell me what this is?
or what is going wrong? i have had a look on google but i cant find much information on it.
<script type="text/javascript">
//when the button is clicked
$(document).ready(function() {
$("#button").click(function() {
$('.small').hide();
var name = $("input#name").val();
if (name == "") {
$("span#name").show();
return false;
}
var name = $("input#email").val();
if (name == "") {
$("span#email").show();
return false;
}
var name = $("input#subject").val();
if (name == "") {
$("span#subject").show();
return false;
}
var name = $("textarea#message").val();
if (name == "") {
$("span#message").show();
return false;
}
var dataString = 'name='+ name + '&email=' + email + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "/scripts/send_message.php",
data: dataString,
});
$("#messagearea").load("console/new_message_profile.php?sent=1");
});
});
</script>

As #Namit mentioned, you use name as a variable everywhere. Building your string, email, subject and message are uninitialised.
They should give you an undefined - but no, due to a weird Internet Explorer behaviour (see Is there a spec that the id of elements should be made global variable?) these variables hold DOM elements. As you seem to have multiple elements with the same id (NEVER DO THAT), here a <span> and an <input>, the variables even seem to hold HTMLCollection objects. Which are casted to the string [object HTMLCollection], when you concat them with other strings.

You're reusing the variable name for all the other fields as well. You need to change the field name to the respective input id.
var name = $("input#email").val(); // needs to be email
var name = $("input#subject").val(); // needs to be subject

Related

Javascript: User Authentication JSON Error

I'm making a login page for my web application, and I'm using a temporary data storage (I know this is not safe) for user verifiation. I'm trying to compate the username input to the data (only correct email is needed at the moment to get it working), but it's not working at all. I'm not getting an error message, just the alert that the username is not correct. It now displays both the user input and data, so I can see that my input is correct. What's wrong with it?
Thanks in advance!
(The data/object is in a seperate js file)
var count = 2;
function validate() {
var un = document.login.username.value; /* Username Input variable*/
var pw = document.login.password.value; /* Password Input variable*/
var valid = false;
let data = responseData;
for(var account in data.accounts){
if( un == account.responseData.authenticatUser.RSP.USR.CONT.EML){
var valid = true;
console.log("Yes");
break;
}
}
if (valid) {
alert("Login was successful. Welcome, " + un + ".")
window.location = "https://www.google.com";
return false;
}
if (count >= 1) {
alert("The correct username is " + item_name + ", you put in "+un);
count--;
}
var responseData = {
authenticatUser: {
"ERR":0,
"RSP":{
"AUTHC":"true",
"USR":{
"ID":"2",
"TJT":"FULL",
"ACTV":"true",
"BO":"1489760664786",
"CONT":{
"FNM":"John",
"LNM":"Doe",
"PHN":"5556667777",
"PHNTP":"NONE",
"EML":"ex#mple.com",
"EMLTP":"NONE"
},
"ADMIN":"false",
"LLOGN":"1489760664786",
"ACCT":{
"ID":"2",
"TJT":"ID"
}
}
}
},
When you write:
if( un == account.responseData.authenticatUser.RSP.USR.CONT.EML){
var valid = true;
You are initializing a new valid variable that is only seen in that function. When you later access it outside the function you are seeing the original valid you initialized in line 5. This is called shadowing and it's a common source of bugs.
Do this instead:
if( un == account.responseData.authenticatUser.RSP.USR.CONT.EML){
valid = true;
Now you should be changing the original valid variable.

How to store text box value to be passed to getJson request as query parameter

I need to be able to store the text value of a search box term, which can be used as a query parameter in a getJson request. I'm appending the search term to the end of the url the user is taken to after hitting the enter key, but the issue is that on the location replacement, it shows up as an error because the url for the page is /faq/search-results/.
$(".faq-search").keyup(function(e){
if(e.which == 13) {
window.location.replace("/faq/search-results/" + $(".faq-search").text());
}
});
Once the user has been sent to the search results page, I have a script which, if the user is on that url, is supposed to grab the search term from the pathname in the url, and submit it as a query parameter to the getJson request:
if(window.location.pathname == "/faq/search-results/"){
$("document").ready(function(e) {
var url = window.location.pathname;
var exp = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
var question = exp[5].split("/")[3];
$.getJSON("//search.url-to-search.com?q=" + question + "&results_type=faq", {
},
//Get results and make 'em look good
function(data) {
console.log(data);
$.each(data.data, function(i, data) {
if(data.type === "FAQ"){
$(".faq-results").append("<li class='result-item'><h3>" + data.title + "</h3><p class=\"content\">" + data.text + "</p><p class=\"category\">" + data.type + "</p></li>");
}
});
});
});
}
I believe the issue is that it won't fire off the request because its looking for only /faq/search-results/. I think I need a way to store the search term as a variable and pass it as a query parameter, but not sure how to accomplish this, as I believe it would make the variable out of scope.
A couple of things are wrong in your code:
first to collect the input value use .val() note text().
Secondly you are not passing the input value as a query string you are adding it to the url path /helloWorld. I think it is better to add as a query string ?q=helloworld.
I have therefore adjusted your code, removed your code to extract the text from the path and implemented a function to extract a named query param, this function is called getParameterByName.
The code below should be pretty much self explanatory.
$("document").ready(function(e) {
//
// Collects the input param as passes it as a query string note
// ?q= our string
//
$(".faq-search").keyup(function(e) {
if (e.which == 13) {
window.location.assign("file:///C:/Users/spydre/Desktop/text.html?q=" + $(".faq-search").val());
}
});
// snippet gets a query param from url
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// collect any query string param whos name is q
var question = getParameterByName("q");
if (question) {
// pass question to our getJson
$.getJSON("//search.url-to-search.com?q=" + question + "&results_type=faq", {},
//Get results and make 'em look good
function(data) {
console.log(data);
$.each(data.data, function(i, data) {
if (data.type === "FAQ") {
$(".faq-results").append("<li class='result-item'><h3>" + data.title + "</h3><p class=\"content\">" + data.text + "</p><p class=\"category\">" + data.type + "</p></li>");
}
});
});
} //if question
})

How to pass a variable from View to Controller in ASP .NET

I found similar questions to mine, but in all of those examples, the variable was part of the model. I am trying to pass a variable that is created in javascript, which is not part of the model.
Code:
$(document).ready(function () {
var url = document.URL;
var index = url.indexOf("?email=");
var email;
/* If there is an EMAIL in URL, check directory to confirm it's valid */
if (index > -1) {
/* There is an email */
email = url.substr((index + 7));
email = email.substr(0, (email.length - 4)) + "##mymail.ca";
/* Check directory to see if this email exists */
#Html.Action("CheckDirectory", "Home", new { email = ???});
}
});
Is there a way to fill in the ??? with the email above?
You can pass your value as a GET parameter in the controller URL:
$(document).ready(function () {
var url = document.URL;
var index = url.indexOf("?email=");
var email;
/* If there is an EMAIL in URL, check directory to confirm it's valid */
if (index > -1) {
/* There is an email */
email = url.substr((index + 7));
email = email.substr(0, (email.length - 4)) + "##mymail.ca";
/* Check directory to see if this email exists */
window.location.href = '/CheckDirectory/Home?email=' + email;
}
});
To answer your question of
Is there a way to fill in the ??? with the email above?
No. The Razor code is similar to, say, PHP, or any other server-side templating language - it's evaluated on the server before the response is sent. So, if you had something like
#Url.Action("checkdirectory", "home")
in your script, assuming it's directly in a view, it would get replaced by a generated URL, like
/home/checkdirectory
Your code, which uses
#Html.Action("checkdirectory", "home")
actually executes a separate action, and injects the response as a string into the view where it's called. Probably not what you were intending.
So, let's try to get you on the right path. Assuming your controller action looks something like
[HttpGet]
public ActionResult CheckDirectory(string email = "")
{
bool exists = false;
if(!string.IsNullOrWhiteSpace(email))
{
exists = YourCodeToVerifyEmail(email);
}
return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
}
You could, using jQuery (because XMLHttpRequests are not fun to normalize), do something like
$(function(){
var url = '#Url.Action("checkdirectory", "home")';
var data = { email : $('#email').val() };
$.get(url, data)
.done(function(response, status, jqxhr) {
if(response.exists === true) {
/* your "email exists" action */
}
else {
/* your "email doesn't exist" action */
}
})
.fail(function(jqxhr, status, errorThrown) {
/* do something when request errors */
});
});
This assumes you have an <input /> element with an id of email. Adjust accordingly. Also, the Url helper can only be used within a view; if you're doing this in a separate JavaScript file, replace it with a hard-coded string (or whatever else works for you).
Edit:
Since it seems I didn't entirely get what you were trying to do, here's an example of returning a different view based on the "type" of user:
public ActionResult ScheduleMe(string email = "")
{
if(!string.IsNullOrWhiteSpace(email))
{
ActionResult response = null;
var userType = YourCodeToVerifyEmail(email);
// Assuming userType would be strings like below
switch(userType)
{
case "STAFF":
response = View("StaffScheduler");
break;
case "STUDENT":
response = View("StudentScheduler");
break;
default:
response = View("ReadOnlyScheduler");
break;
}
return response;
}
return View("NoEmail");
}
This assumes you would have 4 possible views: the three you mentioned, plus an "error" view when no email parameter was given (you could also handle that by redirecting to another action). This variation also assumes a user has somehow navigated to something like hxxp://yourdomain.tld/home/scheduleme?email=peter#innotech.com

Fetch all built-in and custom fields in contacts in CRM 2011

Contact entities in CRM 2011 have a lot of built-in fields, and I've added some custom fields as well.
I want to fetch all field names as a list using Javascript. If you want to create a email template, CRM will let you choose from all of the fields from a dialog. I'd like to get the field names and values as they appear in that dialog.
I used the following code to fetch all attributes for a contact, but this list includes all object properties, not just the contact fields.
ODataPath = GetServerUrl() + "/XRMServices/2011/OrganizationData.svc";
var retrieveRecordsReq = new XMLHttpRequest();
var result = "";
retrieveRecordsReq.open('GET', ODataPath + "/AccountSet(guid'" + guid + "')", false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.send();
var entity = JSON.parse(retrieveRecordsReq.responseText).d;
When I inspect the entity object using IE developer tools, it shows me all of the contact's properties, but with different names. For example, in CRM Contact, there is a field mobilephone, but in IE it is entity.MobilePhone. Further, IE does not display any of the custom fields.
You don't get different names, with the REST endpoint you get the Schema Name.
Read this article for more information: http://www.mohamedibrahim.net/blog/2012/10/04/dynamics-crm-entity-and-field-display-name-field-schema-name-and-field-logical-name-attribute-name/
The entity contains also the custom fields, the endpoint returns all fields, OOB and custom one.
Your solution for get a list of all attribute is correct. as Guido told it is Schema Name.
i test your code and add some line off Codes for create a list off all attribute:
ODataPath = GetServerUrl() + "/XRMServices/2011/OrganizationData.svc";
var retrieveRecordsReq = new XMLHttpRequest();
var url = "";
if (entityname == 'account')
url = "/AccountSet(guid'" + guid + "')";
else if (entityname == 'contact')
url = "/ContactSet(guid'" + guid + "')";
else if (entityname == 'lead')
url = "/LeadSet(guid'" + guid + "')";
else if (entityname == 'systemuser')
url = "/SystemUserSet(guid'" + guid + "')";
retrieveRecordsReq.open('GET', ODataPath + url, false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.send();
var entity = JSON.parse(retrieveRecordsReq.responseText).d;
var AllContactFields = new Array();
for(var x in entity)
{
if (typeof entity[x] == 'object') {
if (entity[x] == null)
AllContactFields.push(x);
}
else {
AllContactFields.push(x);
}
}
the AllContactFields array is the result list.
Good Luck

Meteor insert record using form values

First of all, I'm a complete JS novice. I'm experimenting with Meteor.My objective is to to build a simple form that inserts records into a table. I've set up variables to grab values from each input, and I've placed those variables into an insert method. When I click the button, it recognizes the click, but doesn't pull any values from the inputs. I'm sure I'm missing something simple here, I just can't figure out what it is.
Here's the JS:
var Leads = new Meteor.Collection("Leads");
if (Meteor.is_client) {
Template.Leads.LeadsArr = function(){
return Leads.find();
};
Template.AddLeads.events = {
"click input.submit" : function () {
var name = document.getElementById('input#name').value();
var email = document.getElementById('#email').value();
var type = document.getElementById('#type').value();
var date = document.getElementById('#date').value();
var message = document.getElementById('#message').value();
Leads.insert({leadName : name, leadEmail : email, leadType : type, leadDate : date, leadComment : message});
}
};
} // end is_client
document.getElementById expect the id, not the selector. Also, value is a property of an input, not a function. So your input queries should be like this.
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var type = document.getElementById('type').value;
var date = document.getElementById('date').value;
var message = document.getElementById('message').value;

Categories

Resources