how to send json data via get just as jquery does - javascript

I am trying to develop a function to send json data via get method using javascript instead of curl.
And it also works fine with the get method of jquery ajax api.For example,
$.ajax({
url : url,
type : "GET",
data : json,
dataType: "json",
//.....
//other code here.
})
But something wrong happened, when I try to send the same json data by the follow code as someone else suggest here.
xmlhttp.open("GET",url+"?pretty="+encodeURIComponent(JSON.stringify(json)),true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send();
However,it seems that the json data is too large to be encoded inside the url, and the url was truncated.
So, I wander how I can send the large json with javascript just as the jquery does.

Related

Bad formatting in JSON ajax response

I am having some odd problems with data coming back from a jquery Ajax call that I cannot figure out.
I have a c# asp.net web page that binds a valid JSON data blob to the UI with client side JavaScript on page load. This part works just fine. I set up a jquery Ajax post back that returns the same data and calls the same JavaScript data binding method, and this throws an error when I attempt to bind the data. It looks like the JSON written to the page on load is properly treated as a JSON object, but the data returned by the ajax call isn't.
Here is the ajax call:
jQuery.ajax({
type: 'POST',
data: "{'move_list': '1-2,3-2'}",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
url: 'Puzzle.aspx/ProcessMove',
complete: OnComplete,
success: function(data){BindData(data);},
error: OnError
});
Here is a sample of the JSON data that is being processed:
{"game": [{"x":0,"y":0,"color":"Blue"},{"x":1,"y":0,"color":"Green"}]}
Here is the code that loads the data when the page is first loaded:
<script type="text/javascript">
// method returns JSON object above.
// client side code appears like this:
// BindData({"game": [{"x":0,"y":0,"color":"Blue"},{"x":1,"y":0,"color":"Green"}]});
BindData(<%=Game.SerializeToJson()%>);
</script>
and finally, the JavaScript binding function:
function BindData(data)
{
try
{
document.getElementById("square1").className = data.game[0].color;
// much more of the same....
}
catch(exception)
{
alert(exception.message);
// error thrown here is 'data.game is undefined'.
// the data object is being treated like a string and not a JSON object.
// so the indexing into the object fails.
}
}
I have double checked the JSON data with several online JSON parsers, and the data is formatted correctly. The server side code generates the same output in either case.
I tried to change the jquery Ajax call to...
success: function(data){BindData(JSON.parse(data));},
...to see if it was just treating the returned data as a string as opposed to a JSON object, but that just generates this message:
SyntaxError: JSON.parse: unexpected character
BindData(JSON.parse(data));
Completely stumped by this one. I have been reading everything I can find and trying all sorts of things, but nothing seems to work.

How can i retrieve a file from one url and post it to another?

I'm trying to create a javascript api to take a word doc as input from the server side (say A) and post it to another api (say B) that will convert it to pdf. The reason I'm doing this is so that i can use the call to B against any A instead of having to modify each of the A APIs (there are multiple As that give word docs).
This is what I have done so far. The problem is when I'm calling B I'm not able to get the file that i'm sending.
Here's my code.
javascript call to server.
$("#downloadFile").click(function(){
$.ajax({
url : "/fileDownload.action",
success : function(data){
handleFile(data);
}
});
});
});
function handleFile(inputFile){
$.ajax({
url : "/convertFile.action",
type : "POST",
data : {inputFile : inputFile },
cache:false,
processData:false,
contentType: "application/msword",
success : function(data){
alert("yay?");
}
});
}
On my server side (a struts 2.3 action class) for "/convertFile.action", I have a setInputFile(File inputFile) method to set the file from request. However, it is not setting the file.
Now if I use a standard file upload with a form in HTML it sets the file (no javascript though, just plain html and server side code).
Also If I try to construct a form and post without an ajax call, I still get the same result. I tried to use the js in this answer to post the form.
What am I doing wrong? One possibility is that I need to take the input as a string or a stream. But is there anything else that I'm doing wrong/violating/can't do?

Return PDF to browser using JSON and MVC3

My requirement is whenever a Image is clicked a PDF should be opened on the browser. I am using Jquery ajax [POST call] to make a call to the ASP.NET MVC side and a file is returned on the response. A POST is required from the jquery side since I need to pass substantial data from client to server.
HTML Part:
<span data-id='printSettings' title='Generate PDF' class="preferenceSettings"></span>
JS Part: This is fired when the Generate PDF icon is clicked.
var textToSend = $('.microChartTable', self.element)[0];
var dataToSend = { htmlContent: textToSend.outerHTML };
$.ajax({
url: "/EADashboard/ConvertToPDF",
data: JSON.stringify(dataToSend),
type: 'POST',
contentType: 'application/json',
success: function (data) {
} // -- success ends here
});
ASP.NET Side : In my controller, I have the following code:
[HttpPost]
public FileResult ConvertToPDF(HtmContent content)
{
string fileName = Server.MapPath("~/SeedData/data.pdf");
string contentType = "application/pdf";
return new FilePathResult(fileName, contentType);
}
Now the PDF generation code is correct just that the PDF file is not been opened on the browser side. I have seen the post Return PDF to browser using JSON and MVC? but since there was no solution provided, I am posting this again. Can anyone let me know how this can be achieved ?
Thanks
Two things.
Why are you doing post via ajax and not a regular post? With a regular post your code would probably work.
If you indeed need to do it with ajax, you are receiving result in the data object on the success of the ajax call, and I do not see that you do anything with it, which is why you do not see anything happening.

Save form data into local json file using jquery

I have a basic form with some input fields. I want to save the form data into a json file on submitting the form.
The format of the saved data in the json file should be like this.
[
{"title":"some text","description":"some text","info":"some text","username":"some name"},
{"title":"some text","description":"some text","info":"some text","username":"some name"},
{"title":"some text","description":"some text","info":"some text","username":"some name"}
]
I tried doing this by using this code, but no data is saved in my 'story.json file'
$('form').submit(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'story.json',
data: $(this).serialize(),
success: function(data) {
alert(data.message);
},
failure: function (data) {
alert('Please try again');
}
});
});
I want to save this form data on my local file.
Please help me to find the correct way of doing this. Thanks
You need to post data to a simple php file...
like url: 'story.php'
In that php file create a 'story.json' using fopen and store that json
EDIT: if you want to use serialize() than use someting like this
data:{'mydata':$(this).serialize()}
and in php file
parse_str($_POST['mydata'],$newarray) ;
echo json_encode($newarray);
JavaScript cannot save to a file unless it's a FireFox plugin.
What you do is post a form (sent it to the webserver) then let server side script handle it.
Serialize does not turn the form values into a JSON string:
http://api.jquery.com/serialize/
And when you use $.post then you have to return false in the $('form').submit(function() or the browser will submit the form for you.
Submitting a form is when you click a button and the whole page goes white for a moment and then you get a new page.
Ajax ($.post, $.get, $.getJson ...) is when you send information to the server without refreshing the page. Google maps is an excellent example.
Calling the serialize method on the form jQuery object does not return a JSON representation of its data. It returns a querystring representation of its data. As has been mentioned above, you will need to use a server side script to interpret (and manipulate) sent data and store it in a file as JSON.

Ajax Json : XML can't be the whole program.

I am trying to make a simple ajax request(cross-domain) using Json.
Here's my code :
$("#unsub").live('click', function() {
$.ajax({
url: urly ,
type:'GET',
dataType:"json", //type JSON
success: function(data) { //do something
}
});
});
However, the response I am getting from the server is a html Div
<div id="handler"></div>
On button click I get an error on success "XML can't be the whole program".
Please note : i have to USE json to make the call no matter what and the call will always return a div. using jquery 1.3.2
Any help would be highly appreciated.
Thanks for the time.
Most of the time you need to provide the remote server a "callback" in url for the jsonp to be wrapped in. If API is not set up for JSONP, you need to use other methods to egt the JSOn with javascript. First check that API will deliver jsonp, and if so what params to put in the url

Categories

Resources