To pass parameter from server side to client side - javascript

In the below code I have a dropdown in this I call js function from server side and I want to pass parameter to js function. In my case parameter is not passing. Please help me to solve this issue.
codebehind:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", "<script type=text/javascript> AddItem(" + EnumRows + ");</script>", true);
js:
function AddItem(EnumRows) {
// Create an Option object
// var opt = document.createElement("option");
alert('this');
// Add an Option object to Drop Down/List Box
document.getElementById("<%=cbField.ClientID%>").options.add(opt);
// Assign text and value to Option object
opt.text = Value;
}

Try this
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", "AddItem('" + EnumRows + "');", true);

Below will help you
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", "AddItem(" + EnumRows + ");", true);

Try to use escape_javascript method on your parameter.
<%= escape_javascript(your_parameter) %>

Related

Asp Date to Javascript Function

Why is my date, when passed to the javascript function performing math operations on the values??
HTML:
<td><button type="submit" form="frmParams" onclick="ChangeDate(<% =Session("ECN") %>, <% =datStart3 %>);" value="Submit">Click Me To Change Date</button></td>
where Session("ECN") = '1111' and datStart3 = "6/02/2017"
Whenever I click this button, I my ajax request is for:
http://*****/apqp/updateDate.asp?ECN=1111&Date=0.001487357461576599
I want date to = "6/02/2017" (I have also tried replacing the '/' with '-' or 'a' with no luck)
The Javascript function:
function ChangeDate(strECN, strDate)
{
// Get an xmlHTTPRequest object. Jump out with an error if the object can't be created.
xmlHTTP = getXMLHTTPObject();
if(xmlHTTP == null){
alert("Your browser does not support AJAX!");
return;
}
strURL = './updateDate.asp?ECN=' + strECN + '&Date=' + strDate;
// Setup the xmlHTTP object, open it & send the request.
xmlHTTP.open("GET", strURL, false);
xmlHTTP.send(null);
// Display the line items.
window.location.reload();
}
Wow, Im an idiot.
Just realized that I was passing it in as a Integer.
Putting '' around datStart3 in the HTML portion of :
<td><button type="submit" form="frmParams" onclick="ChangeDate(<% =Session("ECN") %>, <% =datStart3 %>);" value="Submit">Click Me To Change Date</button></td>
fixes it.

JSP Java Code inside ajax jquery prompt nullpointer exception

This code is inside the function submitForm(){}, means, everytime when user click the save button it will trigger this part. the code shows no error, but during the page load, it gives this error:
PrintDebug.println("Final SeqNo: "+finalSeqno);
%>
<%ResultSet rsVal = aDBManager.retrieveRec(sqlgetSeq);%>
<%if(rsVal.next()){ %>
[Stacktrace:] with root cause
java.lang.NullPointerException
I have tried to remove this part of code,and everything work as expected.Seems like the resultset of the select statement giving me the error.for the stored proc resultset , it works fine. This actually confuse me, why the stored proc is ok but not the select statement in ajax jquery.If this can't be done, is there another way for me to pass the value from select statement to input label?
Thanks in advance..
callback: function (result) {
if(result){
var forTempValue = "";
var forFieldValue = "";
var forMandatory = "";
var forDataImageNoApp = "";
var loopInt = 0;
$('input[type=textbox][name^=tmpField],select[name^=tmpField],input[type=text][name^=tmpField]').each(
function(index){
var input = $(this);
forTempValue+=("'" + input.prop('value').replace(/&/g,"") + "' Col" + loopInt + ",");
forFieldValue+=("'" + input.prop('value').replace(/&/g,"") + "'" + "±");
loopInt++;
}
);
$('input[type=hidden][name^=MandatoryName]').each(
function(index){
var input = $(this);
forMandatory+=(input.val() + ",");
}
);
$('input[type=hidden][name^=tempNoAppLoop]').each(
function(index){
var input = $(this);
forDataImageNoApp+=(input.val() + ",");
}
);
$.ajax({
type: "POST",
url: "../ESSCheckerMakerOperation",
data: "sTabID=<%=sTabID%>&sFieldNameApp=<%=sFieldNameApp%>",
success: function(msg){
<%
String getSeqNo = "SELECT MAX(fldSeqno) FROM "+MappingID+"";
String finalSeqno="";
ResultSet rs = aDbManager.retrieveRec(getSeqNo);
if(rs.next()){
finalSeqno=rs.getString(1);
}rs.close();
String cmd="EXEC sp_RelationshipValidation '"+MappingID+"'," + finalSeqno;
aDbManager.SQLTransaction(cmd);
String sqlgetSeq= "Select fldCommonErrorFlag " +
" From tblGeneralError" +
" Where fdSeqNo '" +finalSeqno + "' "+
" And fldTableName = '" +MappingID + "' ";
PrintDebug.println("Final SeqNo: "+finalSeqno);
%>
<%ResultSet rsVal = aDBManager.retrieveRec(sqlgetSeq);%>
<%if(rsVal.next()){ %>
document.getElementById('lblError').style.visibility = 'visible';
document.getElementById('lblError').innerHTML = <%=finalSeqno%>;
Ko
<%}else{%>
bootbox.alert({
title:"Record is successfully ",
message:"There is a problem with the validation for" + <%=finalSeqno%> ,
});
<%
}%>
//}
},
error: function(msg){
bootbox.alert({
title:"Error",
message: "Failed to save the record.",
});
}
});
};
}
});
This is really a classic one: The key is to realize, where and when which code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is send to the browser) and Javascript in the browser, after the browser receives the already generated response.
Your main mistake is to use JSP scriptlet in the success handler of the AJAX call - the scriptlet is run on the server side, before when the page is generated, i.e. before the AJAX request can even be fired by the browser. Thus, the variables you expect to be filled by the call are null.

Laravel link a controller function using xmlhttp.open

I am new to laravel 5 and I want to know how can I use xmlhttp.open to send a GET request.
Here is what supposed to be my javascript code:
xmlhttp.open("GET", "reg_validation?field=" + field + "&query=" + query, false);
So how can I link that one to a function inside a controller and return its value with xmlhttp.responseText
Create a new route for this request :
Route::get('reg_validation', 'YourController#yourAction');
Then use the return in your action :
use Illuminate\Support\Facades\Input; //Import 'Input' class in the top of controller
function yourAction(){
$field = Input::get("field");
$query = Input::get("query");
return $field.' -- '.$query;
}
Hope this helps.

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 + "",
}

ASP WebForms re-evaluate property on post back

Basically I want to set the default date on a jQuery calendar. I have a little script that runs fine when the page loads.
<script type="text/javascript">
$(function () {
var calendarPicker = $('input[name="ctl00$MainContent$ucDetails$LeftPanel$fieldDate$dateValue$calendarPicker"]');
if (calendarPicker.val() == "") {
calendarPicker.datepicker("option", "defaultDate", '<%# CalendarDefaultDate %>');
}
});
</script>
However, when the user changes the value on a combo box, the page posts back and runs some code which causes the value of CalendarDefaultDate to update. The problem is that even though the value of the property has changed, it doesn't get reflected on the page.
Any ideas how to fix this? Many thanks.
Update 1. Tried using the ClientScriptManager as advised. (with no joy)
StringBuilder builder = new StringBuilder();
builder.AppendLine("$(function(){var calendarPicker = $(\"input[name='ctl00$MainContent$ucDetails$LeftPanel$fieldDate$dateValue$calendarPicker']\")");
builder.AppendLine("if (calendarPicker.val() == '') {");
builder.AppendLine("calendarPicker.datepicker(\"option\", \"defaultDate\", '" + CalendarDefaultDate + "')");
builder.AppendLine("}});");
Page.ClientScript.RegisterStartupScript(GetType(), "CalenderDefaultDate", builder.ToString(), true);
You can use the ClientScriptManager to run your function on the reload:
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
Try to declare your function on aspx file this way.
<script type="text/javascript">
function assignCalendar () {
var calendarPicker = $('input[name="ctl00$MainContent$ucDetails$LeftPanel$fieldDate$dateValue$calendarPicker"]');
if (calendarPicker.val() == "") {
calendarPicker.datepicker("option", "defaultDate", '<%# CalendarDefaultDate %>');
}
};
</script>
Then in code behind call it like below:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "assignCalendar ", "<script type='text/javascript'>assignCalendar();</script>", false);
If you put it on PageLoad event i think it will work

Categories

Resources