How to send Json Data from Aspx page - javascript

I tried to use TokenInput Jquery for multiple value autocomplete where it requires the JSON response as input data
http://loopj.com/jquery-tokeninput/
I am using ASPX page as source
<script type="text/javascript" >
$(document).ready(function() {
$("#txtTest").tokenInput("Complete.aspx", {
theme: "facebook"
});
});
</script>
Edited From Here
Question: How to provide the JSON data from a aspx page in the desired format as i have datatable with values according to Querystring from Complete.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["q"]))
{
string json = "[{\"Id\":\"1\",\"name\": \"Test 1\"},{\"Id\":\"2\",\"name\": \"Test 2\"}]";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
}
}
Any help will be appreciated.

Alternative to the WCF, you can create WebMethod in .aspx.
[WebMethod]
public static string Info()
{
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(new string[] { "one", "two", "three" });
return result;
}
and request this WebMethod via Ajax call.
<script type="text/javascript">
$(function () {
$("#button1").click(function () {
$.ajax({
url: "Default.aspx/Info",
data: "{}",
contentType: "application/json",
success: function (data) {
alert(data.d);
},
type: "post",
dataType : "json"
});
});
});
</script>
EDIT:
Code-behind - Page_Load handler (JsonPage.aspx)
string json = "[{\"name\":\"Pratik\"},{\"name\": \"Parth\"}]";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
and request the JsonPage.aspx via TokenInput jQuery. (Sample.aspx & JsonPage.aspx are in same folder)
<script type="text/javascript">
$(function () {
$("#txt1").tokenInput("JsonPage.aspx");
});
</script>
<body>
<input type="text" id="txt1"/>
</body>

You should take a look at WCF. WCF has native support for returning JSON and you don't have to worry about string concatenation or HTTP content types.

Related

How to solve Invalid JSON Primitive error on Ajax?

I am trying to perform ajax using webmethod on Asp.net,
And I am using JQuery-3.1.1
I want to pass the value to server and get back the value. I don't know what I did wrong.
Asp.net Code
<div class="row">
<asp:Button ID="btnSave" runat="server" CssClass="btn btn-info" Text="save" />
</div>
Jquery Code
$(document).ready(function () {
$('#btnSave').click(function () {
var name= 'xxx';
$.ajax({
type: "POST",
url: "AjaxWebMethod.aspx/getFileExistOrNot",
data: '{fileName:'+name+'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert("failed ="+response.d);
},
error: function (response) {
alert("error ="+response.d); //This alert is executing
}
});
function OnSuccess(response) {
alert("Result ="+response.d.mydata);
}
return false;
});
});
C# code
public partial class AjaxWebMethod : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string mydata="ajaxworking";
return mydata;
}
}
I don't know really where I did my mistake
Error message on console
{Message: "Invalid JSON primitive: xxx.",…}
ExceptionType:"System.ArgumentException"
Message:"Invalid JSON primitive: xxx."
Can you give the solution with proper reason. that will good for me to understand more, thanks
Your postData is invalid JSON, a string needs quotes around it:
'{fileName:'+name+'}'
It should be:
'{fileName:"'+name+'"}'
The jQuery call that you are making is set up to expect JSON format in the response. It would appear that your server side code is simply returning a string which is not encoded as JSON. You either need to change the output from the server or change what is expected from the ajax invocation.

Post Ajax call says Get not allowed

I'm trying to use ajax with post method but it keep poping me this error
An attempt was made to call the method \u0027SendEmail\u0027 using a GET request, which is not allowed
Here is the js
var obj = { name: name, company: company, country: country, email: email, msg: Msg }
var json = JSON.stringify(obj);
$.ajax({
method: "POST",
url: "ContactUs.aspx/SendEmail",
contentType: "application/json; charset=UTF-8",
data: json,
dataType:"json",
success: function (data) {
var a = 3;
},
error:function(a,b){
var a = 43;
}
})
and here is the server side on c#
[WebMethod]
public static void SendEmail(string name, string company, string country, string email, string msg)
{
}
Thanks in advance!
You should follow this way:
Your backend method which you already decorated with [WebMethod] and added a reference of using System.Web.Services;, I've changed the method to return something so it can be verified whether it works or not.
[WebMethod]
public static String sendEmail(string param)
{
return "Your String";
}
within your .aspx page, add scriptManager for enabling client side calling to your code behind methods
<asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Finally within your JQuery script, call the method like this:
$(document).ready(function () {
PageMethods.sendEmail("", onSuccess);
function onSuccess(response)
{
alert(response);
}});
Hope it helps!
Try to use [HttpPost] instead of [WebMethod] and remove static.
Is it a REST API or MVC?

ajax call for string method not working

I want to set a html content to TinyMCE editor content in ASP.NET MVC
so I come come with a solution that convert that HTML file to string in server side and then call it using ajax in client side
this is C# controller method
[HttpGet]
public string TyneMice()
{
return System.IO.File.ReadAllText(#"C:\Users\..\myhtml.html");
}
this is ajax call ,
<script type="text/javascript">
tinymce.init({
...,
setup: function (ed) {
ed.on("init", function (ed) {
$.ajax({
type: "GET",
url: "Brochure/TyneMice",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
tinyMCE.activeEditor.setContent(data);
},
error: function () { alert("Ajax Error"); }
});
})
}
});
</script>
But Once I put debug point on above string method it is not invoking
Then I put above script inside $( document ).ready(function() { ... }
But the same result it doesnt work.
Your Action should return of type ActionResult. The action will return Json object with JsonRequestBehavior set as AllowGet.
[HttpGet]
public JsonResult TyneMice()
{
return Json("TyneMice Example", JsonRequestBehavior.AllowGet);
}

Unknown WebMethod error while calling it from Jquery using Ajax

I have a web method that i am trying to call from jquery ajax but it is not getting invoked.
In firebug When i saw the response i get,
<title>Unknown web method MyMethod.<br>Parameter name: methodName</title>
error.I am not able to get the reason why this error is coming when that method is available at the server side..
Here is my client side code..
$("#excel").on("click", function (e) {
e.preventDefault();
var img = "image";
$.ajax({
type: "POST",
url: "Default.aspx/MyMethod",
data: JSON.stringify({ imageData: img }),
contentType: "application/json; charset=utf-8"
}).done(function (o) {
console.log(["Response:", o]);
});
});
And here is my server side code..
[WebMethod()]
public static void MyMethod(string imageData)
{
string fileNameWitPath = "D:/Kabir/custom_name.png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);//convert from base64
bw.Write(data);
bw.Close();
}
}
}
Please help me to solve this issue as i am completely struck into this.
Thanks in advance..
Using this worked for me System.Web.Services.WebMethod
Try this
[System.Web.Services.WebMethod]
public static void MyMethod(string imageData)
{
}
System.Web.Services.WebMethod()
Initializes a new instance of the System.Web.Services.WebMethodAttribute class
System.Web.Services.WebMethod
Adding this attribute to a method within an XML Web service created using ASP.NET makes the method callable from remote Web clients
If the above doesn't works, make sure that the url you are passing is correct. And still if it doesn't works Check this out
This did worked on my system
Default.aspx
<form id="form1" runat="server">
<div id="excel">
Here</div>
</form>
<script type="text/javascript">
$("#excel").on("click", function (e) {
e.preventDefault();
var img = "image";
$.ajax({
type: "POST",
url: "Default.aspx/MyMethod",
data: JSON.stringify({ imageData: "Hello" }),
contentType: "application/json; charset=utf-8"
}).done(function (o) {
console.log(["Response:", o]);
});
});
</script>
Default.aspx.cs
[System.Web.Services.WebMethod]
public static string MyMethod(string imageData)
{
return imageData;
}
If you're looking for an answer about VB.net, you need to make your function Public Shared. I just ran into this issue myself.

jQuery.ajax() parsererror

when i try to get JSON from http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json with:
(jQuery 1.6.2)
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function (result) {
alert("SUCCESS!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(xhr.responseText);
alert(xhr.status);
alert(thrownError);
}
});
I get: parsererror; 200; undefined; jquery162******************** was not called
but with the JSON from http://search.twitter.com/search.json?q=beethoven&callback=?&count=5 works fine.
Both are valid JSON formats. So what is this error about?
[UPDATE]
#3ngima, i have implemented this in asp.net, it works fine:
$.ajax({
type: "POST",
url: "WebService.asmx/GetTestData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
}
});
WebService.asmx:
[WebMethod]
public string GetTestData()
{
try
{
var req = System.Net.HttpWebRequest.Create("http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json");
using (var resp = req.GetResponse())
using (var stream = resp.GetResponseStream())
using (var reader = new System.IO.StreamReader(stream))
return reader.ReadToEnd();
}
catch (Exception) { return null; }
}
It's because you're telling jQuery that you're expecting JSON-P, not JSON, back. But the return is JSON. JSON-P is horribly mis-named, named in a way that causes no end of confusion. It's a convention for conveying data to a function via a script tag. In contrast, JSON is a data format.
Example of JSON:
{"foo": "bar"}
Example of JSON-P:
yourCallback({"foo": "bar"});
JSON-P works because JSON is a subset of JavaScript literal notation. JSON-P is nothing more than a promise that if you tell the service you're calling what function name to call back (usually by putting a callback parameter in the request), the response will be in the form of functionname(data), where data will be "JSON" (or more usually, a JavaScript literal, which may not be the quite the same thing). You're meant to use a JSON-P URL in a script tag's src (which jQuery does for you), to get around the Same Origin Policy which prevents ajax requests from requesting data from origins other than the document they originate in (unless the server supports CORS and your browser does as well).
in case the server does not support the cross domain request you can:
create a server side proxy
do ajax request to your proxy which in turn will get json from the service, and
return the response and then you can manipulate it ...
in php you can do it like this
proxy.php contains the following code
<?php
if(isset($_POST['geturl']) and !empty($_POST['geturl'])) {
$data = file_get_contents($_POST['geturl']);
print $data;
}
?>
and you do the ajax request to you proxy like this
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
alert("abt to do ajax");
$.ajax({
url:'proxy.php',
type:"POST",
data:{geturl:'http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json'},
success:function(data){
alert("success");
alert(data);
}
});
});
});
</script>
tried and tested i get the json response back...
At last i have found the solution. First of all, the webmethods in a webservice or page doesn't work for me, it always returns xml, in local works fine but in a service provider like godaddy it doesn't.
My solution was to create an .ahsx, a handler in .net and wrap the content with the jquery callback function that pass the jsonp, and it works .
[System.Web.Script.Services.ScriptService]
public class HandlerExterno : IHttpHandler
{
string respuesta = string.Empty;
public void ProcessRequest ( HttpContext context )
{
string calls= context.Request.QueryString["callback"].ToString();
respuesta = ObtenerRespuesta();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write( calls +"("+ respuesta +")");
}
public bool IsReusable
{
get
{
return false;
}
}
[System.Web.Services.WebMethod]
private string ObtenerRespuesta ()
{
System.Web.Script.Serialization.JavaScriptSerializer j = new System.Web.Script.Serialization.JavaScriptSerializer();
Employee[] e = new Employee[2];
e[0] = new Employee();
e[0].Name = "Ajay Singh";
e[0].Company = "Birlasoft Ltd.";
e[0].Address = "LosAngeles California";
e[0].Phone = "1204675";
e[0].Country = "US";
e[1] = new Employee();
e[1].Name = "Ajay Singh";
e[1].Company = "Birlasoft Ltd.";
e[1].Address = "D-195 Sector Noida";
e[1].Phone = "1204675";
e[1].Country = "India";
respuesta = j.Serialize(e).ToString();
return respuesta;
}
}//class
public class Employee
{
public string Name
{
get;
set;
}
public string Company
{
get;
set;
}
public string Address
{
get;
set;
}
public string Phone
{
get;
set;
}
public string Country
{
get;
set;
}
}
And here is the call with jquery:
$(document).ready(function () {
$.ajax({
// url: "http://www.wookmark.com/api/json",
url: 'http://www.gjgsoftware.com/handlerexterno.ashx',
dataType: "jsonp",
success: function (data) {
alert(data[0].Name);
},
error: function (data, status, errorThrown) {
$('p').html(status + ">> " + errorThrown);
}
});
});
and works perfectly
Gabriel

Categories