Load javascript on page load using asp.net - javascript

I have some working code (jQuery/Javascript) that makes a call to an API and submits data to it. The same service then returns a success or failure message depending on whether the data was inserted into the API db. The below works flawlessly when loaded in the browser.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(document).ready(function () {
var groupType = getParameterByName('group').trim();
if (groupType == 'm') {
groupId = 'ICM.RealLife.Mobile';
} else if (groupType == 'd') {
groupId = 'ICM.RealLife.Desktop';
}
var email = getParameterByName('email').trim();
var mobileTel = getParameterByName('mobile').trim();
var panelistId = mobileTel;
var password = 'icm001';
var locale = 'en';
alert('email=' + email + '\n\nMobile=' + mobileTel + '\n\nGroup=' + groupId);
if (mobileTel != '' && email != '' && groupId != '') {
//Build up querystring to pass to API
var dataString = "panelistId=" + (encodeURIComponent('+') + mobileTel) + "&groupId=" + groupId + "&emailAddress=" + email + "&password=" + password + "&locale=" + locale + "&mobileNumber=" + (encodeURIComponent('+') + mobileTel) + "";
//var apiResult;
//send to API
$.getJSON('https://www.analyzeme.net/api/server/prereg/?', dataString + '&callback=?', function (getResult) {
//apiResult = JSON.stringify(getResult);
//alert(apiResult);
});
//} else {
// alert('Incorrect parameters!');
}
});
I now have to get this working using a 1x1 tracking pixel using aspx like below;
<img src="http://www.somedomain.com/pixel.aspx?email=email#email.com&mobile=+441111222222&group=d" width="1" height="1"/>
BUT, I do not know how to get my JavaScript to fire in the asp.net page when it is hit? I know I need to do something with RegisterStartupScript but how do I get all that JS into it and how do I get it to fire when the page is hit. I know how to return an img/gif using response headers, so I am cool with that.
Help greatly appreciated! :)

Call the JS function from your Page_Load event in code behind. This will fire every time the page is loaded.
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Page, GetType(), "myFunction", "myFunction();", true);
}
JavaScript
function myFunction() {
//Code you want to run from document.ready
}

Related

Unable to receive parameter in query string when redirected to other page

Hi I am developing one application in java-script. I have two pages default.aspx and addnewitem.aspx. there is one html table in default.aspx and one button. When i click on button i want to redirect to addnewitem.aspx page. I have some parameters to send in query string. I am able to redirect to addnewitem.aspx but page not found error i am getting. I am not sure why i am getting page not found error. I am trying as below.
function getValues() {
var Title = "dfd";
var PrimarySkills = "fdfd";
var SecondarySkills = "dfdf";
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=" + encodeURIComponent($(Title)) + "&PrimarySkills=" + encodeURIComponent($(PrimarySkills)) + "&SecondarySkills=" + encodeURIComponent($(SecondarySkills));
window.location.href = url;
}
I am checking querystring in addnewitem.aspx as below.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["Title"] != null && queryString["PrimarySkills"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Title:</b> " + queryString["Title"] + " <b>PrimarySkills:</b> " + queryString["PrimarySkills"] + " <b>SecondarySkills:</b> " + queryString["SecondarySkills"];
$("#lblData").html(data);
alert(data);
}
});
</script>
"http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=%5Bobject%20Object%5D&PrimarySkills=%5Bobject%20Object%5D&SecondarySkills=%5Bobject%20Object%5D"
I tried lot to fix this. May i know where i am doing wrong? Thanks for your help.
You should use the relative path in your url instead of hard coding the entire folder structure, which is probably incorrect since you are getting a 404. And you need to change the url every time you publish the site to the hosting enviroment when you hard code it like that.
So change
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=...
into
var url = "/AddNewItem.aspx?Title=...
if both the pages are in the same folder. Should AddNewItem.aspx be located in the Pages folder, you have to add that folder of course: var url = "/Pages/AddNewItem.aspx?Title=...

How to execute a C# method from JavaScript code without refreshing the page?

How can i execute a C# method from JavaScript Code without refreshing the page?
this is the function that i want to execute:
protected void submitData(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
string worker = workerNameInput.Text;
string project = projectNameInput.Text;
string status = statusInput.Text;
string color = colorInput.Text;
if (worker.Equals("") || project.Equals("") || status.Equals("") || color.Equals(""))
return;
try
{
conn = new MySqlConnection();
conn.ConnectionString = connectionString;
conn.Open();
string com = "insert into " + table + " values ('" + worker + "','" + project + "','"+ status + "','"+ color + "');";
MySql.Data.MySqlClient.MySqlCommand command = new MySql.Data.MySqlClient.MySqlCommand(com, conn);
string res = command.ExecuteNonQueryAsync().ToString();
Console.WriteLine(res);
Console.WriteLine("Insert command pass successfully");
}
catch (Exception ex)
{
Console.WriteLine("Failed to update database with \"insert\" command");
Console.WriteLine(ex.Message);
}
}
and i know that i should use
public partial class Home : System.Web.UI.Page, IPostBackEventHandler
and
public void RaisePostBackEvent(string eventArgument)
{
submitData(null, null);
}
inside the JS i used this code:
project.updateTable = function() {
var projectName = project.projectName();
var workerName = project.workerName();
var status = project.status();
var color = project.color();;
if (projectName == "" || workerName == "" || status == "" || color == "")
return;
project.rows.push({ projectName: ko.observable(projectName), workerName: ko.observable(workerName), status: ko.observable(status), color: ko.observable(color) });
project.projectName("");
project.workerName("");
project.status("");
project.color("");
var argumentString = projectName + "," + workerName + "," + status + "," + color;
var pageId = '<%= enterToDB.ClientID%>';
__doPostBack(pageId, argumentString);
};
This is how i configure my button:
<p><asp:Button runat="server" ID="enterToDB" Text="Add Project" data-bind="click: updateTable" onmouseover="this.style.background='orange', this.style.color='darkslateblue'" onmouseout="this.style.background='darkslateblue', this.style.color='orange'" /></p>
Can you correct my mistakes please?
and show me where i'm wrong?
You can use ASP.NET WebForm's UpdatePanel control to run the code-behind async. This is commonly known as "AJAX" (Asynchronous JavaScript and XML) or "XHR" (XML HTTP Request), and is built-in to the WebForms framework.
Here's a great resource on MSDN to get you started: https://msdn.microsoft.com/en-us/library/bb399001.aspx
It is possible to call JavaScript functions from C# form or class and to call C# functions from the JavaScript.
Javascript to C#
-------C# code--------------------
[System.Runtime.InteropServices.ComVisible(true)]
// execute the following instruction in the form initialisation
WebBrowser1.ObjectForScripting = this ;
// define a public method
public void ShowMessage (string msg) { MessageBox.Show(msg); }
-------HTML and Javascript----------------
<input type="button" value="JavaScript is calling Dotnet"
onclick="window.external.ShowMessage('JavaScript message');" />
C# to Javascript
-------C# code--------------------
object [] MyArgs = { "Hello" } ; WebBrowser1.Document.InvokeScript("MyJsFunction",MyArgs ) ;
-------Javascript----------------
function MyJsFunction(s) { alert(s) ; }

Call JS function from code behind C#

I have a function onRowClick called RowClick and is working fine. I am trying to move it to a button and call the function from the code behind. For some reason is not triggering the function.. Anyone knows why and how I can fix this?
aspx.cs
if (e.CommandName == "Addvoucher")
{
GridDataItem item = (GridDataItem)e.Item;
var id = item.GetDataKeyValue("RowID");
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "RowClick("+id+");", true);
}
aspx
<script>
var popUpObj;
function RowClick(sender, eventArgs) {
var filterId = eventArgs.getDataKeyValue('RowID');
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
function LoadModalDiv()
{
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display="block";
}
function HideModalDiv() {
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display = "none";
}
</script>
IN page voucher.aspx
<script type = "text/javascript">
function OnClose() {
if (window.opener != null && !window.opener.closed) {
window.opener.location.reload(); //refreshing parent when popup close
// window.opener.HideModalDiv();
}
//if (window.closed==true) window.open("~/routedoc.aspx");
}
window.onunload = OnClose;
</script>
Change your js function like this
function RowClick(filterId) {
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
There is no need of this line now var filterId = eventArgs.getDataKeyValue('RowID'); Now you can directly use the parameter filterId in your js function.
Calling JavaScript function on code behind i.e. On Page_Load
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
If you have UpdatePanel there then try like this
ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
Because you are calling RowClick() and in your code you are calling the second parameter eventArgs and actually it's an undefined value.
Make sure you pass the correct parameters.
Since you just calling a javscript function then I would recommend to just on the grid row data bound just assign the value to an anchor a tag or a button to just call the javascript.
The problem is you are not passing any arguments for that js function from server side but you are getting data key value in client function as in your edited question pass row id from server side and change the client side function as below,
function RowClick(rowId)
{
// use rowId
popUpObj = window.open("voucher.aspx?param=" + rowId + "",
}

how to append if found, and replace if not found at all? (xml find.each loop)

I'm trying to search a string value in an xml file, and then append to a div if the string value is found. If not found at all, then I need to display an error text in the same div that the search term was not found.
This is basically supposed to be a search page which loads the searched items into div content.
Currently my content is loading fine. The searched term if found loads all the corresponding divs from the xml, but I've been unable to display an error if the search term was not found.
My XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<item>
<animal_id>1_1</animal_id>
<animal_title>Sparrow</animal_title>
<animal_generic>Birds 1</animal_generic>
<animal_category>Birds</animal_category>
<animal_code>a1</animal_code>
<animal_img>http://i.imgur.com/R0754lr.png</animal_img>
<animal_url>1_1_Animals1.html</animal_url>
</item>
<item>
<animal_id>1_2</animal_id>
<animal_title>Crow</animal_title>
<animal_generic>Birds 2</animal_generic>
<animal_category>Birds</animal_category>
<animal_code>b2</animal_code>
<animal_img>http://i.imgur.com/R0754lr.png</animal_img>
<animal_url>1_2_Animals2.html</animal_url>
</item>
<item>
<animal_id>1_3</animal_id>
<animal_title>Parrot</animal_title>
<animal_generic>Birds 3</animal_generic>
<animal_category>Birds</animal_category>
<animal_code>c3</animal_code>
<animal_img>http://i.imgur.com/R0754lr.png</animal_img>
<animal_url>1_3_Animals3.html</animal_url>
</item>
</items>
HTML
<div class="list-h">
</div>
Javascript
var s_string = 'bird';
$.ajax({
url: 'https://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml', // name of file you want to parse
dataType: "xml",
success: function parse(xmlResponse){
$(xmlResponse).find("item").each(function() {
var pr_id = $(this).find("animal_id").text();
var p_title = $(this).find("animal_title").text();
var p_category = $(this).find("animal_category").text();
var p_code = $(this).find("animal_code").text();
var p_img = $(this).find("animal_img").text();
var p_url = $(this).find("animal_url").text();
var p_gen_name = $(this).find("animal_generic").text();
var p_xml_string = p_title + p_gen_name, results_string = '', error;
if(s_string)
var s_string2 = s_string.replace("%20"," ");
//console.log(p_xml_string + s_string2);
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){
//console.log("FOUND : " + p_title);
results_string = '<div class="item"><div class="item-h"><a class="item-anchor" href="' + p_url + '"><div class="item-image"><img class="item-image-first" src="' + p_img + '" alt=""><div class="item-meta"><h2 class="item-title">' + p_title + '</h2><span class="item-arrow"></span></div></div></a></div></div>';
found_string = true; //// KEEP VALUES = TRUE OR FALSE IN AN ARRAY...GLOBAL ARRAY, AND THEN SEARCH THAT ARRAY FOR TRUE. IF ALL FALSE, SHOW ERROR.
}
if(found_string){
$('.list-h').append(results_string);
$('<div id="error_div"></div>').text("found");
}
}); //xmlResponse .each function end.
}, error: function(){console.log('Error: Animals info xml could not be loaded.');}
});
// START OF NOT FOUND SEARCH SCRIPT
$(window).load(function(){
var error_found = $('#error_div').text(); console.log(error_found);
setTimeout(function(){
if(error_found != 'found'){
var results_string = '<center>Your Search Query "<b>' + $.url().param('q').replace("%20"," ") + '" was not found!</b> Maybe you entered an invalid search query.</center>';
$('.list-h').append(results_string); }
}, 0);
});
// END OF NOT FOUND SEARCH SCRIPT
And here's the js fiddle with complete XML url: http://jsfiddle.net/mohitk117/B89Ms/
Please could someone help me out regarding this? Thanks!
Some changes may sort out your problem
Add a div in your html
<div id="error_div"></div>
Change below code
if (s_string) var s_string2 = s_string.replace("%20", " ");
//console.log(p_xml_string + s_string2);
if (p_xml_string.toLowerCase().indexOf(s_string2) > -1) {
to
var s_string2='';
if (s_string) s_string2 = s_string.replace("%20", " ");
if (s_string2 && p_xml_string.toLowerCase().indexOf(s_string2) > -1) {
Change found_string code like,
if (found_string) {
$('.list-h').append(results_string);
$('#error_div').text("found");
}
Optionally add css for error_div
#error_div {
color:red;
}
Live Demo
Updated success code
var found_string = false; // define found_string globally
$(xmlResponse).find("item").each(function () {
var pr_id = $(this).find("animal_id").text();
var p_title = $(this).find("animal_title").text();
var p_category = $(this).find("animal_category").text();
var p_code = $(this).find("animal_code").text();
var p_img = $(this).find("animal_img").text();
var p_url = $(this).find("animal_url").text();
var p_gen_name = $(this).find("animal_generic").text();
var p_xml_string = p_title + p_gen_name,
results_string = '',
error;
var s_string2 = '';
if (s_string) s_string2 = s_string.replace("%20", " ");
if (s_string2 && p_xml_string.toLowerCase().indexOf(s_string2) > -1) {
//console.log("FOUND : " + p_title);
results_string = '<div class="item"><div class="item-h"><a class="item-anchor" href="' + p_url + '"><div class="item-image"><img class="item-image-first" src="' + p_img + '" alt=""><div class="item-meta"><h2 class="item-title">' + p_title + '</h2><span class="item-arrow"></span></div></div></a></div></div>';
found_string = true; //// KEEP VALUES = TRUE OR FALSE IN AN ARRAY...GLOBAL ARRAY, AND THEN SEARCH THAT ARRAY FOR TRUE. IF ALL FALSE, SHOW ERROR.
}
if (found_string) { // if found then append in list
$('.list-h').append(results_string);
}
}); //xmlResponse .each function end.
if (found_string) { // if found then empty error div
$('#error_div').text("");
} else { // else show error text or not found
$('#error_div').text("not found");
}
Updated Found Demo and Not Found Demo
I'm a bit uncertain of how everything fits together because the javascript code is not self-explanatory. But, can you start by addressing this issue here...?
if(s_string)
var s_string2 = s_string.replace("%20"," ");
//console.log(p_xml_string + s_string2);
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){
s_string2 variable is out of scope when you use it in this expression...
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){
What were you trying to do there? The expression above will always evaluate to false because s_string2 is undefined. In other words, whatever processing you are doing inside that if block will never be reached
Again, this variable is instantiated and disposed at the very same time...
if(s_string)
var s_string2 = s_string.replace("%20"," "); //<--- This variable's lifecycle ends here
and, this expression will always be false until you address the variable issue above...
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1)

How do I pull phoneNumber from Linkedin Javascript API array

I appreciate any help with those familiar with the LinkedIn JavaScript API. Question: How do I pull in the phone number and email from the field array. In my example, posted to a php script, both phoneNumber and emailAddress are undefined when set to $_POST[''];:
<script type="text/javascript">
//Runs when the JavaScript framework is loaded
function onLinkedInLoad() {
IN.UI.Authorize().params({"scope":["r_fullprofile", "r_emailaddress", "r_contactinfo"]}).place();
IN.Event.on(IN, "auth", onLinkedInAuth);
}
//Runs when the viewer has authenticated
function onLinkedInAuth() {
IN.API.Profile("me").fields("id,firstName,lastName,phoneNumbers,emailAddress,positions").result(displayProfiles);
}
// 2. Runs when the Profile() API call returns successfully
function displayProfiles(profiles) {
var p = profiles.values[0];
var phone = profiles.values[0].phoneNumbers;
for (var i in p.positions.values) {
var pos = p.positions.values[i];
if (pos.isCurrent)
var company = pos.company.name;
}
//AJAX call to pass back vars to server
var http = new XMLHttpRequest();
var postdata= "id=" + p.id + "&fName=" + p.firstName + "&lName=" + p.lastName + "&phone=" + phone + "&email1=" + p.emailAddress + "&company=" + company;
http.open("POST", "../inc/linkedin.php", true);
use fields like this http://developer.linkedin.com/documents/profile-fields
Try this...
IN.API.Profile("me")
.fields('id,email-address,first-name,last-name,date-of-birth,phone-numbers,positions,num-connections')
.result(displayProfiles)
.error(displayErrors);

Categories

Resources