passing variables from code behind doesn't work in Firefox - javascript

I am successfully able to pass variables from code behind to javascript in IE, but not in firefox.
What I do is I have these public variables in my code behind:
public string passedVar = "";
and it gets assigned to a value in the page load event:
passedVar = "In code behind";
and then in the aspx page, inside a script block, I do this:
var clientVar = "<%= passedVar %>";
and then I am able to access it in other js files of that page just fine... in IE only!
If I am using javascript; however, that variable in the .js is showing up as "undefined"
I can find alternate values like hiddenfield, but I want to know why this is not working like it should!
thank you!

If you need to process data through Javascript, do an ajax call (sync or async) to an empty .aspx page (I mean code-behind only), get the data result on success event and process the data in the callback function.
Some code based on JQuery samples:
$.ajax({
type: "POST",
url: "http://myDomain/myPage.aspx",
data: "par1=val1&par2=val2",
async: false,
success: function( data ) {
/*
* data contains the myPage.aspx response
* it could be a single value or a comma-separated list of values
* initialize passedVar or whatever
*/
});

Related

How to assign ViewData value to JavaScript variable?

I'm trying to assign the value of a ViewData located in the Controller to a JavaScript variable in the front-end; and then add that variable to an AJAX URL API call.
Here is what I have so far:
Controller
public ActionResult Index()
{
ViewData["xTokenBackEnd"] = "IAMATOKEN";
return View();
}
Index.cshtml
var xTokenFrontEnd = #Html.Raw(Json.Encode(ViewData["xTokenBackEnd"]));
$.ajax({
type: 'GET',
url: 'https:&token=' + xTokenFrontEnd,
dataType: 'json'
}).done(function (result) {})
When running the app, I can see that the string of the variable is there at the end of the URL i.e. https:&token=IAMATOKEN however, I'm still not receiving anything through ajax. Is weird cause the value is there at the end of the URL but is almost as if it doesn't hold any real value. Maybe I need to do a conversion? If I take out the variable xTokenFrontEnd and put the real value IAMTOKEN then everything works fine so I'm thinking the error is in the way I'm adding xTokenFrontEnd to the end of the URL but not sure. Any ideas on how to solve this?
In you view get the value and assign to variable - for example:
string token = ViewData["xTokenBackEnd"];
then create hidden field with this variable example:
#Html.Hidden("hfToken", #token)
then you can call this value from jquery with:
$('#hfToken').val();
And finally use this value in ajax call

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.

Return result to a PHP variable from AJAX in a jQuery function

So this is the hardest thing I've ever tried to do, I cannot find any answers after 1 day of searching. Note that I am using some custom jQuery API and will explain what it does.
The setup is a php page that contains a jQuery function. That jQuery function calls the API to return a result based on a row I clicked (it is jQgrid, basically looks like an online excel sheet). That works fine, but the objective is to get that result OUT of the jQuery function and store it in a PHP variable. I am just clueless......
Main PHP Page:
$getUnitID = <<<getUnitID //This is the jQuery function. It is stored in a php variable for use in other functions of the API
function(rowid, selected)
{
var selr= null;
if(rowid != null){
selr = jQuery('#grid').jqGrid('getGridParam','selrow'); //This will give ma a number result based on the row I selected. Works fine.
$.ajax({ // I believe I need to use AJAX so here is my attempt
type: "POST",
url: "getId.php", //This is another PHP page for the reuslt. See below
dataType: "json",
data: {selr:selr},
success: function(data) {
alert (data); // This will successfully show me the row number I chose as an alert. But I don't want an alert, I want it stored as a php variable in my main document to use elsewhere.
}
});
}
}
getUnitID; //End of the function
$grid->setGridEvent('onSelectRow',$getUnitID); //Just an event that calls the function upon clicking the row
$rowResult = ??????? //I need this variable to store the result of that AJAX call or that function call
getId.php
<?php
$rId = $_POST["selr"];
echo $rId;
?>
Essentially, I have no idea why I am using AJAX, because my result is still stuck inside the main jQuery function. How in God's name do I get it OUTSIDE that function?!?!?!?!?!?!?! Do I need to $_GET the 'selr' that I POSTed to getId.php ? If so, how?
Thank you, I love you all.
By the time you get that AJAX request sent out and response received, PHP has already gone to sleep. You cant give the data back to your same page's PHP code. Your jQuery starts executing on client computer long after PHP has already finished its work on your server.
It doesn't matter whether your JavaScript function is stored in a PHP variable. PHP will not get its output back. Only way you can do so is to launch another new request to that code and send value to it. but on the same very request on the same very page, its a no no.
Example of how you can send that data to another PHP page
//Your existing jQuery
success: function(data) {
// alert (data);
var result=data;
$.ajax({
type: "POST",
url: "anotherpage.php",
data: { data: result }
});
}

How to access an HTML template argument passed from controller in a Javascript function

My app is using the play framework mvc setup. In the controller I am passing a parameter while rendering the template, like this:
public static void scenario(){
...
render(active_brands);
}
Now in my HTML page "scenario.html", I can access the parameter using the play framework tags like this:
#{list items:active_brands, as:'c'}
...
#{\list}
Or using JQuery inside an HTML table like this:
<td>${active_brands.get(1)}</td>
Just for reference, the passed in parameter is a List.
However, I am trying to access the parameter "active_brands" from a javascript function and I am not sure how to do that.
I thought using Jquery to access the variable would work and I tried to access the variable like this:
function update_brands(active_scenario_ids){
...
alert('Reached: '+ ${active_brands});
}
but that does not work. It seems to me that the HTML attribute is out of scope for the javascript function. Is that true?
It would be great if someone can help me with this. Thanks.
This works for me using Play 2.2.0:
Application.scala (controller):
def index = Action { implicit request =>
val message = "This is a test."
Ok(views.html.test(message))
}
test.scala.html (view template):
#(message: String)
<script type="text/javascript">
$(document).ready(function(){
console.log("#message");
});
</script>
Console output:
This is a test.
The root of the problem was that my template variable, which is accessible in client side HTML, was of type java.util.List, which is not accessible by client side code ie. javascript. However, it is recognized in the play tags because play tags are server side code written in client side. So the only solution I could find for reading Objects inside java collections is returning a JSON object.
Therefore I had to change my code such that instead of returning a Java List as a template variable, I retrieve the data as a JSON object through an ajax call.
$.ajax({
url: '/getBrands/',
type: 'POST',
data: {active_scenario_ids: active_scenario_ids},
dataType: "json",
success: function(data){
console.log(data);
},
error: function(req, status, error){
alert("R:"+req+"S:"+status+"E:"+error);
}
});
}

ASP.NET get textbox value filled from Javascript in Load or Unload Event

simply, i have an ASP.net Textbox inside a webcontrol
it gets filled by a javascript function inside the same markup of the webcontrol
the problem is that i need to read that value from the serverside events of the webcontrol
tried page_load, page_unload... but they all fire before the javascript function is executed.
i even tried to move the JS code to a seperate Script file, and added a reference to it.
but again its just the same.
when i try to call that function to fill the textbox, using:
Page.ClientScript.RegisterClientScriptBlock //which calls it to early
Page.ClientScript.RegisterStartupScript //which calls it too late ;P
but again it's executed before the Script reference is included in the render of the control.
any suggestions except of Registering all the JS code using registerClientScriptBlock?
im sure im missing something important related to the life cycle of the web control, so please enlighten me and sorry for the long blablabla.
thanks in advance
As Tim implied, this is probably better done on the server, prior to output.
However, to answer your question, you could create a webservice which the client could call to notify the backend of the calculated value. Here's a very rough example:
NewWebService.asmx:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void SaveTextBox(string textValue)
{
<%-- Save the value here --%>
}
YourPage.html:
// Requires jQuery.
// Code can be refactored to use any library or none at all, if you like
<script>
$("#textBoxId").change(function() {
var textValue = this.value;
$.ajax({
type: "POST",
url: "NewWebSerivce.asmx/SaveTextBox",
data: textValue,
contentType: "application/json; charset=utf-8",
success: function (data) {
// do nothing
}
});
});
</script>

Categories