Send javascript array to server - javascript

I have an array who's content I would like to get on my server. I have been wading through internet pages trying to find how to do this without succeeding yet.
Let's imagine I have a server, and that I would like this array in my javascript to go into a file on my server, how would I do that?
I have been going through internet pages looking for how to do this and I have come up with the following code:
<html>
<!-- installs jquery and ajax. -->
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var arr = ["one","two","three"];
arr = JSON.stringify(arr);
$.ajax({
url: "http://url_name_here.com",
type: "POST",
data: {
myArray : arr
}
});
alert('hello');
</script>
</html>

That's an array, there's no need to stringify it, jQuery will convert the data to a valid querystring for you
var arr=["one","two","three"];
$.ajax({
url: "/urltoMyOwnSite.php",
type: "POST",
data: {myArray : arr}
});
PHP (if that's what you're using)
$array = $_POST['myArray'];

front end stuffs
<html>
<!-- installs jquery and ajax. -->
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(function(){
var arr = ["one","two","three"];
arr = JSON.stringify(arr);
$.ajax({
url: "http://url_name_here.com",
type: "POST",
data: {
myArray : arr
}
}).done(function(data,text,jQxhr){
alert("success");
});
});
</script>
</html>
back end server (java b/c it's what I have open in dev atm)
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.json.simple.JSONObject;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.io.FileOutputStream;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException
{
JSONObject jsonObj = (JSONObject) org.json.simple.JSONValue.parse(request.getParameter("myArray"));
// write out your file IO.
JSONObject jsonObj = (JSONObject) org.json.simple.JSONValue.parse(request.getParameter("myArray"));
FileOutputStream file = new FileOutputStream(java.io.File.createTempFile("myArray-",Long.toString((new Date()).getTime())));
FileChannel fc = file.getChannel();
ByteBuffer sw = ByteBuffer.allocate(jsonObj.toJSONString().length());
sw.clear();
sw.put(jsonObj.toJSONString().getBytes());
sw.flip();
while(sw.hasRemaining()) {
fc.write(sw);
}
fc.close();
//because its much easier than a flat file, we can write it back in the server response.
org.json.simple.JSONValue.writeJSONString(jsonObj, response.getWriter());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException
{
doGet(request, response);
}
}

jQuery will stringify the array for you, so you are effectively encoding it twice in your example which is causing your problems. Try this:
var arr = ["one","two","three"];
$.ajax({
url: "http://url_name_here.com",
type: "POST",
data: { myArray : arr }
});

Related

Receive POST request sending JSON in jsp from javascript

I made an HTML page which has an input. I get the value through javascript, create a JSON, and I want to send it via ajax. I also have a JSP application, which runs a method in java that recieves this JSON and reads it so it can be stored in a database. The problem is that I don't know how to receive this call from ajax in my jsp application and sent it to my method in java. Can someone help me with this?
Javascript:
alert("I am about to POST this:\n\n" + dat);
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'JSON',
data: dat,
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
`
JSP:
'<%# page language="java" import="connection.JsonHandler" %>
<%
String json = request.getParameter("dat");;
JsonHandler gson = new JsonHandler();
gson.ReadJson(json);
%>
Java:
package connection;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import entidades.User;
import java.lang.reflect.Type;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonHandler {
public Gson CreateJson(String values) {
Gson gson = new GsonBuilder().create();
gson.toJson("Hello", System.out);
gson.toJson(123, System.out);
return gson;
}
public void ReadJson(String json){
Gson gson = new Gson();
Type type = User.class;
gson.fromJson(json,type);
}
}
You can write a servlet, which will accept your POST request. Please refer to I couldn't get the POST value in servlet page? or How to get the data from ajax request in servlet page?

Can not make ajax call to server

I've tried to use ajax in Spring MVC App but it seems not working I searched for that and found many resources but as I'm not a pro I could not understand any of those, finally I found this tutorial as a grace and tried in Controller as
#RequestMapping(value = "/getBars", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Bar> getBars(#RequestParam String bar, HttpServletResponse response) {
return barService.findBarByName(bar);
}
and javascript is
$(document).ready(function() {
$(function() {
$("#bar-search").autocomplete({
source: function(request, response) {
$.ajax({
url: "/app/getBars",
type: "POST",
data: { term: request.term },
dataType: "json",
success: function(data) {
response($.map(data, function(v,i){
return {
label: v.empName,
value: v.empName
};
}));
}
});
}
});
});
});
and finally my view.jsp is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<meta content="initial-scale=1.0, width=device-width" name="viewport">
<title>Ask Question</title>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"/></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="/app/resources/js/autoComplete.js"></script>
<script>
if (window.jQuery) {
alert('jQuery is loaded');
} else {
alert('jQuery is not loaded');
}
</script>
<!-- css -->
<link href="/app/resources/css/base.css" rel="stylesheet">
<!-- favicon -->
<!-- ... -->
<!-- ie -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="form-group form-group-label">
<div class="row">
<div class="col-md-10 col-md-push-1">
<label class="floating-label" for="login-username">Bars</label>
<input id="bar-search" name="bars" class="form-control" type="text" value=""/>
</div>
</div>
</div>
<script src="/crazy/resources/js/base.min.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
<script src="/crazy/resources/js/webfont.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
<script src="/crazy/resources/js/jquery.autocomplete.min.js;jsessionid=4891173C4BB89D06603ACA4FF7D64D20" type="text/javascript"></script>
</body>
</html>
every thing is ok when app starts but when I write some text down in input I get error
can any one solve this error for me or tell me where am I wrong.
sorry if my English is incorrect.
Ok... the first thing is that your service is configured wrongly.
Your service wants a #RequestParam, but in your ajax you are sending a json object which means you should be accepting a #RequestBody.
Also, if you are looking for a #RequestParam, you need to pass the value as part of the url like...
$.ajax({
url: "/app/getBars?bar=" + request.term,
type: "GET"
( ... )
});
#RequestMapping(value = "/getBars", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Bar> getBars(#RequestParam(value = "bar", defaultValue = "abc", required = false) String bar, HttpServletResponse response) {
return barService.findBarByName(bar);
}
or
$.ajax({
url: "/app/getBars/" + request.term,
type: "GET"
( ... )
});
#RequestMapping(value = "/getBars/{bar}", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Bar> getBars(#PathVariable String bar, HttpServletResponse response) {
return barService.findBarByName(bar);
}
For a post.
First create a bean.
public class MyRequestBean implements Serializable{
private static final long serialVersionUID = 1L;
private String bar;
public void setBar(String bar){
this.bar = bar;
}
public void getBar(){
return this.bar;
}
}
and then write your service like this...
#RequestMapping(value = "/getBars", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Bar> getBars(#RequestBody MyRequestBean bean, HttpServletResponse response) {
return barService.findBarByName(bean.getBar());
}
$.ajax({
url: "/app/getBars/,
type: "POST",
data: JSON.stringify({bar : request.term})
( ... )
});
NOTE: never have the verbs defining your service.
For example, /getBars can be changed to just /bars and let the HTTP protocol (GET, POST, PUT or DELETE etc..) descide which operation you are trying to perform.

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.

How to send Json Data from Aspx page

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.

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