Send json data as url parameters - javascript

I m trying to pass json data
var data = JSON.parse("[" + detail + "]"))
or the results of var detail = $('#grid-table').getCell(rowid, '11')
results as parameters of the url vers another jsp (a modal).
In the same page, all is good (the jqgrid table is full normally).
Now I want to fill by the same data another jqgrid but in another jsp (in my case is a bootstrap modal) but it displays anything.
var iframeSrc = '<%=request.getContextPath()%>/subgridtable_Device_Modal.html?'+ data + '&' + detail ;)
I saw the below sample of data when I receive the detail variable in the second page :
{%22A%22:%223%22,%22B%22:%222SC2I%22,%22C%22:%223%22,%22D%22:%222SC2I%22,%22E%22:%2245%22,%22F%22:%22PTS3S40510009246%22,%22G
Also I tried to parse the detail to json data in the second page but no results .
Any one have any idea please.

When you pass a variable as a part of a URL it will always be URL-encoded. When receiving such a parameter most server side programming languages will automatically decode it again for you. When that's not the case, you have to manually decode it. I don't know which server side language you're using though. Or if you use JavaScript to receive that parameter, use decodeURI().

Related

php dynamic page content based on url

So, there are 3 urls:
example.com/first
example.com/middle
example.com/last
In my sql db, there is table with each terms that correspond to related posts:
ID NAME POSTS
1 first 12,3,343
2 middle 23,1,432
3 last 21,43,99
So if an user visits example.com/first, then I want to show posts of "12,3,343" and other posts based on what url they are visiting.
Now, this is the sequence how it would work in my head:
User types "example.com/first"
js (ajax) or something detects the url (in this case, detects "first").
the term is sent to php query.
Gets appropriate info then sends it out (either by ajax or something else).
Am I approaching this right?
How does the server detects what url was requested? I supposed I can skip the first two steps if I know how the server detects the url and I can query the correct info directly instead of relying on js to detect it.
Thanks!
When you mention ajax, I assume you are not navigating away from the page your are on. Am I correct?
If so, you have to create another php file to respond to the requests:
A request is sent to file.php with the url as a query string
In file.php, let it query the DB and json_encode the data.
Retrieve the data and update the fields without navigating away.
PHP is only executed once (Server-side). if you want to execute another query you have to either navigate to other URL or just send your request to a php file via ajax.
You can get the segments of a url request using below statements
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $url);
Now you have all the segments in an array ($segments)
print_r($segments) to get the index of the segment you require.
Now compare that segment with your value
For Eg :
if( $segments[2] == 'first')
{
//Your Piece of code
}

Passing JSON to the server like GET/POST to get a file instead of ajax reply

I've an object created in javacript with a lot of data and I serialize it to JSON to send it to the server. After this, the server must do somework and create a dynamic file, so it can be downloaded.
For the last routine I created an ASHX but can be modified. Already I'm getting a "httpcontext" that I found in another question how to work with it to get the data from the JSON, so my question is not related about this.
The problem (more oriented to JS) is this one:
How can I sent the JSON to the ASHX as a URL/GET/POST to the generic handler to avoid the "ajax reply" and be the user open a new window with the link dinamically generated?
Thanks, sorry for my english (please edit) and kind regards!
Note 1: I can't use third-part code
Note 2: I can't use JSON.NET
Note 3: I can't save the report on the server so the response must be a generated file to download, even more, the download itself is the response of the server.
---UPDATE----
I've been read this question:
Can I post JSON without using AJAX?
The only thing I don't understand from that question is how to make it work, thinking in that I've a "link" to download
I assume you do not want to refresh the whole page so there is a workaround.
1) Ajax-load an iframe which is a separate aspx file for example.
2) In the codebehind of that separate aspx file, generate the file in memory and convert it to an array of bytes.
3) Then use Response to stream the bytes to the user.
Finally I resolved the issue with this (in the right way).
I just take my json object and send it trough POST with a dynamic form generated with javfascript
var dataToPostInExport = JSON.stringify(queryToVerify);
//Convert To POST and send
var VerifyForm = document.createElement("form");
VerifyForm.target = "_blank";
VerifyForm.method = "POST";
VerifyForm.action = "file.ashx";
var dataInput = document.createElement("input");
dataInput.type = "hidden";
dataInput.name = "mydata";
dataInput.value = dataToPostInExport;
VerifyForm.appendChild(dataInput);
document.body.appendChild(VerifyForm);
VerifyForm.submit();
Then in the ashx file:
Dim DataToParse As String
DataToParse = HttpContext.Current.Request.Form("mydata")
Dim JSSerializer As New JavaScriptSerializer
Dim QueryToExport as my very own type!
QueryToExport = JSSerializer.Deserialize(Of My Own Type)(dataToParse)

Servlet calling from window.showModalDialog(...)

I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks

Django : provide dynamically generated data as attachment on button press

Problem Overview:
I am creating a Django-based client with the intent of returning data from a web service. The goal of this project is to return data to the user from the web service based on the values selected by the user in a form. Upon the form submit, a query string is generated, sent to the web service and the page data is returned as a string. Currently, that data is displayed to the user in the browser. I want to provide the functionality that would allow the user to click a button and download the data.
Question:
How could I return the data to the user when they click a button in their browser for download? How do I make different options of the same data available (i.e. application/json, or text/csv)?
Current (not-working) Implementation:
I am attempting, and failing, to do the following:
views.py
Returning a render_to_response object of my template. To the template I pass the form, and the data in it's various forms.
def view(request):
#Do stuff, get data as string
#Get data into needed formats (see utils.py)
jsonData = jsonToJsonFile(dataString, fileName)
return render_to_response('template.html', {'someForm' : aForm,
'regularData' : stringData,
'jsonData' : jsonData...})
utils.py
Contains functions to take the data as a string and return response objects. This part I am unsure if I am doing correctly. I call these functions in the view to get jsonData (and csvData) into their proper formats from the original data string.
def jsonToJsonFile(dataString, fileName):
#Get the data as json
theData = json.dumps(dataString)
#Prepare to return a json file
response = HttpResponse(theData, mimetype = 'application/json')
response['Content-Disposition'] = 'attachment; filename=' + str(fileName) + '.json'
#return the response
return response
template.html
I am currently passing the responses into the template. This is where I am really lost, and have not yet begun to find a good solution. I expect I will need to use javascript to return the variables (jsonData and csvData) to the user when the button is clicked. I have attempted the use of the onclick action of the anchor class, and then using javascript to return the django variable of the response - but this really isn't working.
<li class = 'button'>
<a href = "#dataButtons" onclick = "javaScript:alert('test');">
TEST
</a>
</li>
<li class = 'button'>
<a href = "#dataButtons" onclick = "javaScript: var a = '{{ jsonData }}'; return a;">
JSON
</a>
</li>
I put the test part in there to, well, test whether or no the alert would work. It does. However, when I click the button for the json data, nothing happens.
Am I approaching this completely wrong? Or is there something small that I am missing?
Solution:
After looking at the problem a little further and talking to a colleague about it, it seems as though my problem lies in trying to pass the response object to the javascript. For those interested, I solved the problem with a little careful re-routing of the data.
views.py
In my views.py I added a couple lines of code in my main view that would set variables of two extra views (one for csv one for json) to the response objects holding the data. These two extra views would then be called when their respective buttons were pressed, returning the httpresponse and prompting the user for download.
#MAIN VIEW FUNCTION
def view(request):
#Do stuff, get data as string
#Get data into needed formats
jsonData = jsonToJsonFile(dataString, fileName)
#Set values to external view ****NEW PART****
returnJSON.jsonData = jsonData
#Render main template
return render_to_response('mainTemplate.html', {'someForm' : aForm,
'regularData' : dataString})
#SECONDARY VIEW TO RETURN JSON DATA TO USER ****NEW PART****
def returnJSON(request):
#Simply return the response
return returnJSON.jsonData
template.html
Then, when the button is pressed by the user, the anchor is linked via the url to the secondary django view that will present the download option to the user.
<li class = 'button'>
<a href = "{% url client.views.returnJSON %}">
JSON
</a>
</li>
urls.py
Lastly, I just pointed my url patterns to the view.
urlpatterns = patterns('',
(r'^somesite/$', views.view),
(r'^somesite/json$', views.returnJSON),
)
So far, this method has worked great for me! If anyone has any other suggestions, or a better method, I would certainly be open to hear it.
I think you need to change your javascript to make it start a file download - see this question & answer:
starting file download with JavaScript

Make an ajax request to get some data, then redirect to a new page, passing the returned data

I want to redirect after a successful ajax request (which I know how to do) but I want to pass along the returned data which will be used to load an iframe on the page I just redirected to.
What's the best way to pass such data along and use it to open and populate an iframe in the page I just redirected to?
EDIT:
I am passing a GET variable but am having to use the following to access it for use in my iframe src attribute:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
var d = $_GET('thedata');
I assume there isn't really a more straightforward way to access the GET vars?
If it's not too much data, you could pass it as a get parameter in the redirect:
document.location = "/otherpage?somevar=" + urlescape(var)
Remember that urls are limited to 1024 chars, and that special chars must be escaped.
If it is beyond that limit your best move is to use server side sessions. You will use a database on the server to store the necessary information and pass a unique identifier in the url, or as a cookie on the users computer. When the new page loads, it can then pull the information out of the database using the identifier. Sessions are supported in virtually every web framework out of the box.
Another alternative may be to place the data as a hidden attribute in a form which uses the post method (to get around the 1024 char limit), and simulating a submission of the form in javascript to accomplish the redirect, including the data.

Categories