How to open a popup and send a JSON object to it - javascript

I want to send a JSON object to a PHP file while my script opens that PHP file in a new popup window. Is it possible to send it via POST method (by jQuery or without it)?
If not, how do I convert JSON to a URL encoded string? Is there any JavaScript function?

You may create a form (on the fly) with an input (where you fill the value with the JSON) and a target-attribute regarding to name of the popup (second parameter of window.open()).
Then send this form.

Open the popup: var popup = window.open(...)
Assign the json object to a new variable in the new window: popup.json = ...
Use the variable json in your popup (it will be accessible as window.json or just json from JavaScript code running in the popup).

There's a JSON encoder/decoder that looks like it would do the job. You could call this to encode your object before adding it to your querystring.
Example
alert(JSON.encode([0,1,false,true,null,[2,3],{"some":"value"}]));
// [0,1,false,true,null,[2,3],{"some":"value"}]
alert(JSON.decode('[0,1,false,true,null,[2,3],{"some":"value"}]'))
// 0,1,false,true,,2,3,[object Object]

You can use the Ajax API to do so... In the Ajax API, you can specify the data property and set it a JSON, and it will send the data to the server based on the type you have set, that is, GET or POST.
For example:
$.ajax(
{
url: url, // Your post URL
type:"POST", // or GET
data: {a:1} // In your case, your JSON object
success:function(response){}, // Function that will be called when your posted URL responds
crossDomain: true, // If it's a cross-domain request
dataType: "json" // Response datatype: JSON, text, HTML, XML, etc.
}
);
One thing to note is that if your response needs to be processed, you need to get around the same origin policy set by the browser. Please read about the same. You could use something called JSONP. It's part of the Ajax API.
I hope this is what you want.

Related

How to create an Ajax GET that behaves like window.location?

I've got a csv that I've been able to retreive using
window.location = "/path/to/mydata", which I understand creates a GET request to that location. Now I'd like to add header params, so I do something like this...
$.ajax(
url:"/path/to/mydata",
method: "GET",
headers: {"my-header": "..."})
.done((data){
// "data" is now a string of my csv data
console.log(data)
});
When I simply do window.location chrome somehow detects that I got a CSV file back and saves the contents locally to My Downloads. I'm not sure how to do that with the ajax done callback function, or if there is an ajax parameter that I could use that does it automatically.

Download the returned PDF from Ajax

I have the following action that returns a PDF:
[HttpPost]
public string GetPDF(string data, float scaleFactor)
{
var result = JArray.Parse(data);
using (var fs = new FileStream(#"c:\pdf\pdftest.pdf", FileMode.Create))
{
MemoryStream ms = (MemoryStream)PdfMaker.CreatePDF(scaleFactor, result, dt);
ms.WriteTo(fs);
return Convert.ToBase64String(ms.ToArray());
}
}
(Ignore the FileStream, that is just for testing)
The result is basically the PDF itself, but it's not getting downloaded, how do I download the output PDF? Should I return something else? I tried using a FileResult, but it's basically the same scenario.
This is the way I'm currently "reading" the file via Ajax:
$.ajax({
type: "POST",
url: "home/GetPDF",
data: { data: JSON.stringify(data), scaleFactor: $("#sf").val() },
success: function (data) {
window.location = "data:application/pdf;base64, " + data;
}
});
Thanks.
Edit:
Used the solution in this post provided by Stephen Muecke
Downloading files via ajax doesn't work because the data ends up in memory in a JS object, not on the user's device. Ultimately you need to use a normal HTTP request and return a FileResult.
However in your case you also need to upload some data first which needs to be added to the PDF before it's downloaded. This is awkward because the download will have to be a GET request triggered in a separate window (because you need the application to remain on the same page afterwards) and supplying that data on the querystring is unlikely to be practical.
A solution to work round this is to have a two-step process:
1) From the browser, upload your data via AJAX to a "EditPDF" action method. In the action method, edit the PDF using the new data, and save it. Then return some sort of unique ID to the client which identifies the correct PDF.
2) When the browser receives the response from the EditPDF method, it grabs the returned ID, and makes a new window.open call to the "GetPDF" action's URL. This action accepts the PDF ID as a querystring parameter, so it's easy to include it in the URL when making the request. This action locates the correct document on the server, and returns it in a FileResult. The browser will download the document, while not affecting the HTML page being browsed.

Need to get serialized data from a form

I'm new to prototypejs. Can you guys tell me how to get serialized values from a posted form using Ajax in prototype?
http://www.prototypejs.org/api/ajax/request
Is this what you need?
http://prototypejs.org/api/form/serialize
Or you want to handle a form through ajax instead of page load? then
http://prototypejs.org/api/form/request
"how to get serialized values from a posted form using Ajax " Makes it sound like you're expecting the Ajax response to include the serialized data sent to the server, but what the response contains is entirely up to the server. Typically, once you make an Ajax request, the onComplete handler doesn't really care about the properties that it sent. The response argument to the onComplete (and any other Ajax callback) contains a request property, which contains parameters object. This would be useful if you did indeed need to see what your request sent to the server, like so:
$('customerdetails').request({
method: 'get',
onComplete: function(response) {
console.log(response.request.parameters); // What you sent to the server
console.log(response.responseText); // What the server sent back to you
console.log(response.responseJSON); // JSON-ified version of what the server sent back
}
});
It's possible for response.responseJSON to be null if Prototype isn't sure that the response actually contains JSON (if, for instance, the response headers were improperly set). If you can bank on the response being JSON, you could do something like this:
onComplete: function(response) {
var jsonObj = response.responseJSON || response.responseText.evalJSON();
// now you can work with jsonObj
}
Hope this helps and I didn't just completely misunderstand your question.
new Ajax.Request('your_ajax_url',{
method:'POST',
parameters:Form.serialize($('your_form_id'))
});

I dont get any data from the getJSON function

I am trying to get a JSON object from a .jsp page. But I dont know what to do with it. I've googeled this for some time now, but I can't find out what this getJSON functions does.
Does it return a string representation of a JSON object?
Or is the parameter 'json' that is passed into the function the JSON Object?
Is the function (the second parameter) equivalent to the function that one write when using XMLHttpRequests? In other words; is this function the asynchronous part?
The alert with "JSON stuff" doesnt print.
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var jso = $.getJSON(URL, function(json) {
alert("JSON stuff " + json.name);
});
alert(jso);
//alert(jso.name);
}
A few things to check:
Is the webapp also running at localhost:8080? If not, you might be running afoul of the same origin policy, in which case you would need to encode to jsonp.
You should also check in firebug/inspect element/whatever to make sure you are actually getting something returned from your request. You can do this in the network or resources tab depending on which browser you are using. Also stick a breakpoint in your script before the alert and inspect the json object to see if anything was returned.
The second alert isn't firing because the json object doesn't exist yet when you call it.
The relevant docs for getJSON is here. The callback parameter (that you named json) is the already decoded data (i.e. it's a JavaScript object, not a string).
As for why your alert isn't doing anything, see Charles Bandes's answer. To better debug your code you can also use console.log (will work on Firebug or on Chrome), and/or set a handler to ajaxError - so if the problem is with your request you can be notified of the error (instead of the browser ignoring it by default).
Does it return a string representation of a JSON object?
The respone will come as JSON format. getJSON method is a short form of jQuery ajax with datatype as json . The datatype decides what is the format to receive the result from the ajax call.
is the parameter 'json' that is passed into the function the JSON
Object?
The variable json in your callback function will get the response from your ajax call. The data should in a valid JSON Document( if your server pages returns like that properly)
is this function the asynchronous part?
As i told you earlier, getJSON is a shortform of jquery ajax with datatype as Json. It is asynchronous.

How to avoid values not to display with the url while using window.location.href to pass values from one page to other?

In my localhost url, am getting all the values which is being passed to the other page are getting displayed in the url.
I dont want it to display the values which are passing,
for example
http://localhost/accounting/credit/credit.php?prod=sdfsdfsd-12&prodId=6&batch=567567
am using window.location.href to pass the values to other page, i think that is the reason its getting added to the url. Is there any other way to pass the values other than window.location.href ? or is there any other way to pass.
Is it possible to make the url not to display the values ?
I just want the url to display as below
http://localhost/accounting/medismo/credit_note/credit.php
How can i do this ?
You can do this pretty simply using jQuery and an HTTP request:
$.ajax({
url: 'credit.php',
type: 'POST',
data: { prod: 'sdfsdf-12', prodID: 6 },
success: function (data, status) {
// Handle successful request
},
error: function (xhr, status, err) {
// Handle request failure
}
});
In this case, data is an object containing all the information you want to pass over to the given url. In your .php file you can access this information using:
$_POST["prod"], $_POST["prodID"], etc.
The tool you are using is called the GET-method to pass variables trough a URI! Another method you can use is the POST-method, which uses html forms (still visible in the source code).
For information about those two HTTP request methods, look here or use Google!
The next best method would be using a php session, where (when used properly) users won't be able to see the variables directly!

Categories