Pass a variable from razor to javascript and display it - javascript

I have a variable
var result = client.DownloadString(query);
in mvc 4 rzaor. By hovering it in the debugging process, it likes the image below
What I want is to display it, so I return it to javascript with the code:
function myFunction() {
$('#response').text('#(Url.Action("result"))');
}
EDIT:
<div id="response"></div>
#{
var strSearch = "test";
var options = "include-passage-references=true";
var client = new WebClient();
var query = string.Format("http://www.xxx.org/v2/rest/passageQuery?key={0}&passage={1}&options={2}", "IP", Server.UrlEncode(strSearch), options);
var result = client.DownloadString(query);
}
However nothing found.

You have to use the ViewBag for that.
On C#:
ViewBag.result = client.DownloadString(query);
On HTML:
function myFunction() {
$('response').text('#ViewBag.result');
}

Related

How to send an integer from ajax without jquery?

I am trying to send an integer called 'petadid' from this js to the django view called 'petadlikeview'. But it looks like the data is not going there in the view.If i print 'petadid' in the view, it shows 'None'. Can anyone please tell me what is wrong? I am new to ajax and django.
Here is my js:
<script>
$(document).ready(function(argument) {
$.ajaxSetup({cache:false});
var element = document.getElementById("likes");
var petadid = $(this).attr("data-petadid");
element.addEventListener("click",function(){
var req = new XMLHttpRequest();
req.open("POST",'/petadlike/')
req.onload = function(){
console.log(req.responseText);
console.log(petadid);
var data = JSON.parse(req.responseText);
}
req.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
var data = {
'petadid':petadid,
}
req.send(data);
});
});
</script>
And here is my django-view:
def petadlikeview(request):
print("vau")
if request.method=="POST":
print("vai")
petadid = request.POST.get('petadid')
print(petadid)
petad = PetAd.objects.get(pk=petadid)
like_count = petad.petadlikes_set.all().count()
like, created = petadlikes.objects.get_or_create(user=request.user,petad=petad)
print(created)
if created is False:
petadlikes.objects.get(user=request.user,petad=petad).delete()
like_count -= 1
liked = False
else:
like.save()
like_count += 1
liked = True
dict = {'like_count':like_count}
return JsonResponse(dict)
return HttpResponse(str(like_count)+' people have liked this')
else:
return HttpResponse('Bad Request')
XMLHttpRequest will not automatically convert an object to POST data as jQuery does, you need to create the URL-encoded string yourself.
var data = "petadid=" + encodeURIComponent(petadid);
Also
var petadid = $(this).attr("data-petadid");
should probably be
var petadid = $(element).attr("data-petadid");

Unable to call new object Javascript

enter code hereI created a new javascript file/object(File 2) and I'm trying to create the new object in file 1, however; i get an "object is not defined error". I have the reference present in the aspx file.
JS File 1
dosomething function()
{
var RedNotesDisplay = new RedNotesDisplayController(redNotesArray, "22", draggedRowsContainer);
}
Js File 2
function RedNotesDisplayController(redNotesContent, JQueryPositionInformation, containerId)
{
var _redNotesContent = redNotesContent;
var _JQueryPositionFormation = JQueryPositionInformation;
var _containerId = containerId;
var _redNotesDiv = "";
}
Here's the error
var RedNotesDisplay = new RedNotesDisplayController(redNotesArray, "22", draggedRowsContainer); <- 'RedNotesDisplayController' is undefined
Try this. What is going on here is we are creating a namespace called ns. Here is another article that helps articulate this concept and how it can be applied.
How do I declare a namespace in JavaScript?
var ns = {
RedNotesDisplayController: function (redNotesContent, JQueryPositionInformation, containerId)
{
var _redNotesContent = redNotesContent;
var _JQueryPositionFormation = JQueryPositionInformation;
var _containerId = containerId;
var _redNotesDiv = "";
return "i am return string";
}
};
var RedNotesDisplay = ns.RedNotesDisplayController([1,2,3], "22", "<div></div>");
// i use console.log to display the string in developer tools [Console]
console.log(RedNotesDisplay);
since ns could be undefined in another page, you are losing scope. Try this code to verify what your constructor is for this js.
<script type="text/javascript">
var somethingNew = new ns.RedNotesDisplayController([1, 2, 3], "22", "<div></div>");
alert(somethingNew.constructor);
</script>
You should now get a response from localhost (my response for example) : function (n,t,i){var r=n,u=t,f=i;return"i am return string"}

JavaScript and jQuery code to return function by var

I am working on small api to get content from my database. I want to show data in a JavaScript/jQuery function according to variables I declared.
example
<script>
function dataset() {
var url = "www.example.com";
var name = "Mini Api";
ver version = "1.00";
this.return url;
this.return name;
this.return version;
}
</script>
How I intend to use it
<script>
minapi = new dataset();
//here I want to return only name
alert(minapi.name);
</script>
Please any idea of how to get this done?
In addition, is there a way to create jQuery function to execute once page load without using this $( document ).ready(function() {});?
I think you want this:
function dataset() {
var myData = {
url: "www.example.com",
name: "mini api",
version: "1.00"
};
return myData;
}
var myVar = dataset();
console.log(myVar.name);
JSFiddle: https://jsfiddle.net/1455d5z3/
This is what you are attempting to do. I fixed ver and assigned properties correctly.
function dataset() {
var url = "www.example.com";
var name = "Mini Api";
var version = "1.00";
this.url = url;
this.name = name;
this.version = version;
}
There might be better ways to do this depending on your situation, but this does give the result you want.
Please use like this.
function dataset() {
var url = "www.example.com";
var name = "Mini Api";
var version = "1.00";
this.returnUrl = function (){
return url;
}
this.returnName = function (){
return name;
}
this.returnVersion = function (){
return version;
}
}
var minapi = new dataset();
alert(minapi.returnName());
Refer Fiddle

Javascript to Read/Count Sharepoint 2010 List Items

I am having a lot of trouble with this. Essentially, I am trying to count the number of times Decommission appears in a particular list column. From what I can tell, the javascript is correct, but it doesn't work. Can anyone provide some guidance? Thanks!
<script type="text/javascript">
var myItems = null;
var siteUrl = &apos;https://chartiscorp.sp.ex3.secureserver.net/&apos;
function SuperDuper()
{
var queryString = &apos;<View><Query><Where><Gt><FieldRef name="End State" /><Value Type="String">Decommission</Value></Gt></Where></Query></View>&apos;;
var myContext = new SP.ClientContext(siteUrl);
var myWeb = myContext.get_web();
var myList = myWeb.get_lists().getByTitle(&apos;System_Information&apos;);
var myQuery = new SP.CamlQuery();
myQuery.set_viewXml(queryString);
myItems = myList.getItems(myQuery);
myContext.load(myItems,&apos;Includes(End State)&apos;);
myContext.executeQueryAsynch(Function.createDelegate(this,SuperDuperSuccess),Function.createDelegate(this,SuperDuperFail));
}
function SuperDuperFail(sender, args)
{
alert(&apos;Failed &apos; + args.get_message());
}
function SuperDuperSuccess(sender, args)
{
var endStateEnumerator = myItems.getEnumerator();
var decommCount = 0;
while(endStateEnumerator.moveNext())
{
//var currentEndState = endStateEnumerator.get_current();
decommCount = decommCount + 1;
}
alert(decommCount);
}
window.onload = SuperDuper;
</script>
What is the error?
Have you tried to see the script error it is throwing?
In function SuperDuperSuccess() you can simply put
var count=0;
count=this.myItems.get_count();
No need to write while loop .
Pls try to put alert and after some line and see what is coming.

modelandview var parameter using ajax.updater

In a page JSP y get by JSTL a var ModelAndView in "${model}
In this page I use JAVASCRIPT to update a DIV with ajax.updater, the code here:
document.getElementById("idFa").value=image.title;
var frm2="${model}";
var dataString = 'mail=acevallo#hotmail.com&idFar=' + image.title + "&frm2=${model.farmers}";
new Ajax.Updater( "pcBody_content2", "tabProductsFruitC2.jsp", { method: "get",parameters:dataString,evalScripts: true });
my problem is, when I update the DIV with the new page tabProductsFruitC2.jsp. In this new page I haven't the var ${model}, so I have that send by parameter this var.
I tried it with var frm2, but it convert my var in string and I can not my modelandview var. How I can send by parameter my model var ${model}.
thanks, guys
Finally I found one solution for this problem....
I had that using JSTL into JavaScript, get my data in one array and send by parameter using LOAD of jquery, so:
enter code here
function productsLoad(image){
var contactTypesList = new Array();
var tmpArray = new Array();
var newOption,newOption2;
var i=1;
<c:forEach items="${model.farmers2}" var="contactType">
newOption = '${contactType.farmerId}';
contactTypesList.push(newOption);
if ((newOption==image.title)&&(i==1)){
<c:forEach items="${contactType.products}" var="prd">
newOption2 = '${prd.key}';
tmpArray.push(newOption2);
</c:forEach>
i=i+1;
}
</c:forEach>
var dataString = 1;
$j("#pcBody_content2").load("jsp2/tabProductsFruitC2.jsp",{ 'choices[]': tmpArray } );
}
</script>

Categories

Resources