Printing object in meteor [duplicate] - meteor

This question already has answers here:
How to use Meteor methods inside of a template helper
(6 answers)
Closed 7 years ago.
Im new with meteor.
This is my javascript code
Template.data.helpers({
data_res: function () {
//DoChart();
//var a = "aaaa";
//return a;
var a = $.ajax({
method: "post",
url: "http://10.102.4.232:124/getdata.asmx/GetCabang",
data: '',
contentType: "application/json",
success: function (data) {
console.log(data); // 6
}
});
return a;
}
});
This is my template code
<template name="data">
{{data_res}}
</template>
the javascript code is to request a web service view ajax and print it in my template. but in my template, the result is [object Object].
my question is how to print the actual value of ajax result in template???
thank you

Because in the Meteor, object would call 'toString' method before template was rendering. So we couldn't print an object in this way, but you could:
// Call your ajax method in this place, or in other place you want
Template.data.onCreated(function(){
// Using Session to storage ajax response, which will render template automatically when it changed
Session.setDefault('myObject', 'no-response');
$.ajax({
method: "post",
url: "http://10.102.4.232:124/getdata.asmx/GetCabang",
data: '',
contentType: "application/json",
success: function (data) {
console.log(data); // 6
Session.set('myObject', data)
}
});
});
Template.data.helpers({
// When receive ajax response, set it to Session 'myObject', and it would render your template 'data' reactively
data_res: function () {
return Session.get('myObject');
}
});
This is my template code
<template name="data"> // using '.' to get property in your object
{{data_res.propertyA}} {{data_res.propertyB}} {{data_res.propertyC}}
</template>
I wish it can help you to solve your problem :-)

Related

How to use ASP.NET and JSON to call C# Code

I am creating a game that I am using ajax and ASP.net to create a two player game. So I am trying to create a couple of buttons for the player to use to "play" a card if it is their turn. I am currently stuck on trying to get the json to call the c# code, but have not been successful yet.
Here is where I'm at:
$(document).ready(function () {
$("#slap").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "Pages/index/",
data: {
//Something goes here
},
success: function (result) {
alert('ok');
},
error: function (result) {
alert('There was an error');
}
});
});
}
Then in the C# code index.cshtml.cs I have a function like playCard().
Thanks in advance!
Url format is wrong. It should be like "/controller/action"

Asp.net Webform page implementing jQuery Autocomplete Widget

I want to incorporate jquery autocomplete widget to my aspx page. The "source" for the autocomplete comes from a webservice method.
My script looks like this:
$(".paisProc").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
type: "POST",
url: "/ManifestService.asmx/GetPaises",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'term': request.term }),
success: function (data) {
console.log("reading results...");
response($.map(data, function (item) {
console.log(item.CodigoAduana);
return {
label: item.Descripcion,
value: item.CodigoAduana
};
}));
},
error: function (err, status, error) {
console.log(status);
console.log(error);
}
});
With this setup, as users type in the input control, the expected values are returned from the webservice but the autocomplete does not seem to work. Inspecting the page with Firebug i see the ajax call to the service returns data with this format:
{"d":[{"__type":"dhl.domain.Pais","PaisId":1,"CodigoDHL":"AR","CodigoAduana":"528","Descripcion":"ARGENTINA"},
{"__type":"dhl.domain.Pais","PaisId":481,"CodigoDHL":"DZ","CodigoAduana":"208","Descripcion":"ARGELIA"}]}
I cannot see what the problem with my code, I have followed the indications from the many questions with the same issue in this site with no success yet.
If it can help, the line console.log(item.CodigoAduana) from success callback write "undefined" to the console.
.Net web services returning JSON do so by embedding the payload into a "d" property (as you can see in your capture of the JSON).
Try changing your processing of the response to read from data.d instead of just data, to get to the array you want to map, like this:
response($.map(data.d, function (item) {
console.log(item.CodigoAduana);
return {
label: item.Descripcion,
value: item.CodigoAduana
};
}));

jquery.forms plugin - send form to webmethod in asp.net

I'm trying to send my form to a web method in asp.net page using jquery.forms plugin (primary reason for that is that I need to send files as well).
However, I can't make it work - it returns the whole page all the time.
I use the following client-side code:
<script type="text/javascript">
var ajaxUploadOptions = {
beforeSubmit: UploadFormValidate, // pre-submit callback
success: FormUploadSuccess, // post-submit callback
error: FormUploadFailure,
url: "Default.aspx/UploadFiles", // override for form's 'action' attribute
type: "POST", // 'get' or 'post', override for form's 'method' attribute
dataType: "json", // 'xml', 'script', or 'json' (expected server response type)
contentType: "application/json; charset=utf-8",
};
function FormUploadSuccess(response, statusText, xhr, jqForm) {
alert(response);
};
function FormUploadFailure(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
$("form[id $= 'form1']").ajaxForm(ajaxUploadOptions);
});
</script>
Code for the asp.net method just to return anything:
[WebMethod]
public static string UploadFiles()
{
return "Test";
}
I registered ScriptModule in web.config (also verified just calling regular jquery's $.ajax to make sure the method is available).
Any suggestions would be appreciated.
Thanks!
It seems I haven't read documentation/code carefully enough. Found out that when sending files, the forms plugin uses iframe and regular submit.

JsonResult shows up a file download in browser

I'm trying to use jquery.Ajax to post data to an ASP.NET MVC2 action method that returns a JsonResult. Everything works great except when the response gets back to the browser it is treated as a file download instead of being passed into the success handler. Here's my code:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='CreateEnvelope']").submit(function () {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (envelopeData) {
alert("test");
}
});
});
return false;
});
</script>
Action method on controller:
public JsonResult CreateEnvelope(string envelopeTitle, string envelopeDescription)
{
//create an envelope object and return
return Json(envelope);
}
If I open the downloaded file the json is exactly what I'm looking for and the mime type is shown as application/json. What am I missing to make the jquery.ajax call receive the json returned?
You are missing a "return false" in the handler of your submit event. If you don't return false, then JQuery will still pass the submit as it would do normally.
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='CreateEnvelope']").submit(function () {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (envelopeData) {
alert("test");
}
});
// IMPORTANT: return false to make sure the normal post doesn't happen!
return false;
});
return false;
});
</script>
You were almost there!
I have just started using ajax similar to this and first impressions looking at your code would indicate that you dont need to call submit on the form? You only need to do the ajax call. I may be wrong but it might be that the ajax is returning the data and the page is doing a refresh where the page data is replaced with the json data?

How to post data using jQuery in ASP.NET?

I have an ASP.NET application in which i want to post data using jQuery to another page. It means i want post the data of page.
How can i do this with jQuery or AJAX?
Please help me.
$(document).ready(function() {
alert("start");
$("#btnSave").click(function() {
alert("start1");
var aa = 'bb';
var json = "{'ItemName':'" + aa + "'}";
alert("start2");
var ajaxPage = "Default3.aspx?Save=1"; //this page is where data is to be retrieved and processed
alert("start3");
var options = {
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function(response) {
alert("success: " + response);
},
error: function(msg) { alert("failed: " + msg); }
};
alert("start4");
});
});
I am using this code I am getting all alert response but its posting page.
Jquery and JSON works great with ASP.NET. You can call a code behind method directly from javascript and return complex objects, not just string. (for this example to work you need json2.js found here https://github.com/douglascrockford/JSON-js)
//javascript
function postMethod(text){
var jsonText = JSON.stringify({ name:text });
$.ajax({
type: "POST",
url: "yourpage.aspx/GetPerson",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function(response) {
var person = response.d;
alert(person.Name);
}
});
}
//aspx code behind
[WebMethod]
public static Person GetPerson(string name)
{
Person person = new Person(name);
return person;
}
There is load function.
You may use it like this:
$('#somediv').load('http://someaddress',{key:value}, function callback(){});
Second parameter is important - only written in this way performs post.(if you pass array then it performs get)
PS> This is good when you want to read the data, if you want to just do the POST and don't care about what comes back then you may want to use:
http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype
Look at $.post() - http://docs.jquery.com/Ajax/jQuery.post
Add all your relevant data, and post away, handling the response with the supplied callback method.
There is a post function in jQuery:
$.post("test.php", { name: "John", time: "2pm" } );
This is copied directly from the jQuery API, so for more details and examples you can look there.
jQuery api
choose Ajax > Ajax Requests > $.post

Resources