How to convert data from JSONP to JSON - javascript

I'm using an API that returns a JSON. Unfortunately because of CORS, I'm unable to set datatype as JSON and have to use JSONP, which the API doesn't support.
From my understanding, I can convert JSONP to JSON by giving it a callback function. It's not working and I couldn't find solutions online. Any help would be appreciated for me to convert the JSONP datatype to JSON.
$(document).ready(function() {
$.ajax({
type:'POST',
url:'http://api.smmry.com/&SM_API_KEY=XXXXXX&SM_URL=HTTP-URL',
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonpFunc',
jsonp:'callback'
});
});
function jsonpFunc(data){
console.log(data);
};
Error I'm getting
Uncaught SyntaxError: Unexpected token :

The simplest way to do this is to use a server-side proxy on your server. You do not run into CORS issues with this model.
A simple example C# proxy might be:
using System;
using System.Web.UI;
using System.Net;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ProcessRequest(this.Page);
}
public void ProcessRequest(Page context)
{
WebClient client = new WebClient();
string BaseUrl = ConfigurationManager.AppSettings["PassthroughTargetURL"];
string _url = BaseUrl;
context.Response.AddHeader("Content-type","application/json");
string _out = client.DownloadString(_url);
context.Response.Write(_out);
}
}
with a calling ASPX page as follows;
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Passthrough-proxy.aspx.cs" Inherits="_Default" %>
And a config entry for the remote URL, like so:
<add key="PassthroughTargetURL" value="http://api.smmry.com/&SM_API_KEY=XXXXXX&SM_URL=HTTP-URL"/>
Assuming the URL you are calling is constant, you should get the expected result, but via your proxy - which is local to your server, so JSON will work as expected.
Your code would then become something like:
$(document).ready(function() {
$.ajax({
type:'POST',
url:'http://your.server/proxy.aspx',
dataType: 'json'
});
});

Related

AJAX POST request in Spring-MVC does not works

I am learning Spring MVC and I have stuck at how to send a simple string value from client using AJAX and print it at JAVA server (controller). I have written below code for doing this. But when I click button to send string, error.... response is popped-up in my browser and the browser console displays POST http://localhost:8090/addUser 404 (). It has been a day since I am trying to solve this issue. Can someone please tell what can be the problem? Or please tell a working alternative solution for sending data from client using AJAX and printing/saving it on JAVA server (Spring-MVC).
UserController.java
#Controller
public class UserController {
#RequestMapping(value = "/addUser", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public JSONArray addUser(#ModelAttribute("UserTest") JSONArray name) {
System.out.println(name.toString());
return name;
}
}
AJAX Request:
<script>
function addUser() {
var json = '{"uname":"John", "Age":42}';
obj = JSON.parse(json);
$.ajax({
url : "/addUser",
data : obj,
type : "POST",
async: false,
contentType: "application/json",
success : function(response) {
alert( response );
},
error : function() {
alert("error...."); //this is being popped-up in my browser
}
});
}
</script>
POST http://localhost:8090/addUser 404 ()
Your request is going to http://localhost:8090/addUser, which is not correct. Your request url should have your application and included.
http://localhost:8090/<app_name>/addUser
AFAIK, your request url should have application name included. Now, to achieve this, you are suppose to change your ajax url
url : "/<app_name>/addUser"
The URL for the ajax call is not correct. It should be like
Url:YourApplicationContextPath/ControllerName/addUser

404 Not Found calling Http Method from JavaScript in ASP

I've looked at a couple of threads now where they want to call a C# method from JavaScript in an ASP project. I can't figure out what I'm doing wrong. Here is my C# class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;
namespace Selfservice.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public String GetCredentials()
{
return User.Identity.Name.ToString();
}
}
}
And here is the JavaScript I'm trying to call:
window.onload = function () {
LiveSearch();
getCredentials();
//FetchAllUsers();
};
function getCredentials() {
$.ajax({
type: 'POST',
url: '#Url.Action("GetCredentials", "Home")',
dataType: 'json',
cache: false,
contentType: 'application/json; charset=utf­8',
data: JSON.stringify(""),
success: function (cred) {
alert(cred);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
I keep getting a 404 Not Found status back. It's an ASP site that's deployed on an IIS, on one of my workplaces servers. We are using Windows Authentication, so I'd like to get the credentials of whoever is logged in and store it for something else later.
I'm kind of at my wits end here. Anyone got any ideas?
Have you just tried to reach "/Home/GetCredentials" as URL? Also like mentioned, change to GET method, remove the contentType and change dataType to "text" as your controller is not returning JSON.

Angular JS Post is not working

I am using angularjs and ionic.I post multiple data from angular js to Api Controller in asp.net mvc
I have below code in order to post multiple form data to controller in asp.net mvc from angularjs.
$http({
method: 'POST',
url: 'http://localhost:51425/api/values/Response',
params: { PropertyFirst: "1", PropertySecond: "2" },
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function (data) {
alert("ok");
});
If i use below code this works
[HttpPost]
public object Response(string PropertyFirst , string PropertySecond)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
return null;
}
However, if i use below code it is not working
PropertyClass
public string PropertyFirst{ get; set; }
public string PropertySecond{ get; set; }
Controller side
[HttpPost]
public object Response(PropertyClass propertyValues)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
return null;
}
I get below error :
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Question:
How can i post PropertyFirst and PropertySecond to PropertyClass ?
Any help will be appreciated.
Thanks.
From the Angular $HTTP docs :
params – {Object.} – Map of strings or objects which will be serialized with the paramSerializer and appended as GET parameters.
I don't know much about asp MVC framework, but if you change the 'params' key to a 'data' key, your request will be correct.
Unfortunately I can't really help with the ASP controllers, as I am entirely unfamiliar with that language.

Getting JSON Object Result from $.post()

I'm attempting to call a web service via AJAX in a WebForms application.
My script looks something like this:
$.post('UpdateServer.asmx/ProcessItem',
'itemId=' + $(this).text(),
function (result) {
alert(result);
});
My web service looks something like this.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class UpdateServer : System.Web.Services.WebService
{
[WebMethod]
public string ProcessItem(int itemId)
{
return new JavaScriptSerializer().Serialize(
new { Success = true, Message = "Here I am!" });
}
}
The web method is called as expected and with the expected argument. However, the argument passed to my success function (last parameter to $.post()) is of type document and does not contain the Success and Message members that I'm expecting.
What's are the magic words so that I can get back the object I'm expecting?
EDIT
On closer inspection, I can find the data I'm looking for as follows:
result.childNodes[0].childNodes[0].data:
"{"Success":true,"Message":"Server successfully updated!"}"
The reason you're seeing that odd structure of nodes that end with JSON is because you're not calling the service the necessary way to coax JSON out of ASMX ScriptServices and then returning a JSON string anyway. So, the end result is that you're returning an XML document that contains a single value of that JSON string.
The two specific problems you're running into right now are that you're manually JSON serializing your return value and you're not calling the service with a Content-Type of application/json (.NET needs that to switch to JSON serializing the response).
Once you fixed those issues, you'd also run into an "invalid JSON primitive" error due to the data parameter being URL encoded instead of a valid JSON string.
To get it working, do this on the server-side:
[ScriptService]
public class UpdateServer : System.Web.Services.WebService
{
[WebMethod]
public object ProcessItem(int itemId)
{
return new { Success = true, Message = "Here I am!" };
}
}
You could also create a data transfer object (aka ViewModel) to return instead of using an anonymous type and object, if you want.
To successfully get raw JSON out of that, do this on the client-side:
$.ajax({
url: 'UpdateServer.asmx/ProcessItem',
type: 'post',
contentType: 'application/json',
data: '{"itemId":' + $(this).text() + '}',
success: function(result) {
// This will be { d: { Success: true, Message: "Here I am!" } }.
console.log(result);
}
});
If you have a few minutes, read through the posts in the communication section of jQuery for the ASP.NET developer. You'll find a lot of that information helpful as you continue down this path.
Note: The links that helmus left were relevant. Nothing has fundamentally changed between 2.0 and present with regards to using ASMX ScriptServices to communicate via JSON. If you're interested in the truly cutting edge approach to this problem in .NET, ASP.NET Web API is the way to go.
Add this attribute to your ProcessItem method:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Be more explicit in your $.post call.
$.ajax({
type:'post',
url:'UpdateServer.asmx/ProcessItem',
data: {'itemId':$(this).text()}
}).done(function (result) {
alert(result);
});

Jquery .ajax does not work after changing url of the aspx page holding webmethod

I'm new for Jquery. I'm trying to call server method from my user control with Jquery ajax. It is wired for me that when the server page that the request is sent to is located in root path, ajax works. But when I moved the page into a subfolder and changed the url parameter of Jquery ajax, nothing happened...
Below is the web method in WebForm1.aspx.cs:
namespace WebApplication11
{
public partial class WebForm1 : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string test2()
{
return "TestString";
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
When the page is located under root, it works. My ajax function in the user control is here:
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="WebUserControl1.ascx.cs"
Inherits="WebApplication11.NewFolder1.WebUserControl1" %>
<script type ="text/javascript">
function ajaxTest()
{
$.ajax({
type: "post",
url: "WebForm1.aspx/test2",
data: "{}",
contentType: "Application/json; charset=utf-8",
dataType: "json",
success: function (r) {alert(r.d);}
})
}
</script>
<input type = "checkbox" id = "c1" onchange = "ajaxTest()" />
But after I move the WebForm1.aspx page from root to a subfolder "NewFolder2", and changed the "url" in ajax method from "WebForm1.aspx/test2" to "/NewFolder2/WebForm1.aspx/test2" or
"NewFolder2/WebForm1.aspx/test2", nothing happened.
I am frustrated now. Can anybody give me a hint to figure it out? Thank you very much!
Are you putting the path from the controls folder to the ajax method or from the page the control is put on? When a control is placed on a page, its ajax method calls must follow the path as if it was on the page itself because that is how it is rendered.

Categories