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
Related
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.
I am iterating list of Java objects with JSTL in JSP-pages like this:
<ul>
<c:forEach items="${listOfObjects}" var="o">
<li id="ObjectID" value="${o.id}" onclick="JSCall()"><a class="style">${o.id}</a></li>
</c:forEach>
</ul>
This will print to me:
1,2,3,4,5,6 etc. to the end of the list. But when I am trying to pass ObjectID's value back to controller it will only print number 1 on each clicked link. ObjectID's value should be the same which is printed.
I use jQuery's AJAX implementation for passing ObjectID to my Spring controller.
function JSCall(){
var variable = $('#ObjectID').val();
$.ajax({
type: "GET",
url: "ajaxController.html",
data: "variable=" + variable
});
}
And then I have controller which listens to that GET.
#RequestMapping("ajaxController")
public #ResponseBody
String JSCall(#RequestParam(value="variable") Integer variable){
System.out.println(variable); //prints only "1" on each link
return variable;
}
I don't get this at all, because I think it should work like planned. Maybe someone will notice something?
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);
}
});
}
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
*/
});
I'm trying to get data returned from a controller and append it to a div. Here is the code I have:
$(this).parent().find('list').append(__WHAT_GOES_HERE?__);
How should I get data to append using ajax in JQuery? I know this is a very basic question -- I'm new to JS :(
PS. Lets assume the controller's path is /ajax_get_items
I assume you want to load it into a class, so list would be .list
Something like:
$.ajax({
url: "/ajax_get_items",
type : "POST",
data : { // If you need data to be posted
id : 12,
num : "test"
},
success : function(result){
$(this).parent().find('.list').append(result);
// If a JSON object is returned, use the following line:
// $(this).parent().find('.list').append(result.html);
}
})
Or if you want to just load data without params (GET method):
$(this).parent().find('.list').load("/ajax_get_items");
If you want more information about ruby rails and jQuery: http://brandonaaron.net/blog/2009/02/24/jquery-rails-and-ajax
This is what you need:
$.ajax({
url: '/ajax_get_items',
success: function(data) {
$('#selector').parent().find('list').append(data)
}
});
Note that you can't use 'this' in this context depending on where this call is made, or you might end up with unexpected results
$('somelink').click(function(e) {
e.preventDefault();
$.ajax(url, data, success:function(resData) {
resultSet = resData.extract(resData);
}
}
Basically this part handles the response from the ajax call and extract is supposed to build up your required html from the returned data.
After this you can simply say
$(this).parent().find('list').append(resultSet);
But this assumes the major work is done in the function extract with the returned data.
There you build up your list (or whatever) html is needed.