javascript set location sending JSON data - javascript

What I'm trying to do is the functional equivalent of setting the "location" property in javascript, but I want to send along JSON encoded data to the server. I don't want to use AJAX, I want to completely replace my page contents with whatever the server sends back.
I think I might be able to do what I want by using form.submit by setting the form enctype attribute to application/json, but I don't know how to get my JSON into the form data set. Is it possible to do this?

You could send the JSON as the query component of the URL:
document.location.href = server_url + "?" + encodeURIComponent(json_string);

One way of doing it is with a form like this (not as clean as you would like it to be, but if you do not want to use AJAX your choices are quite limited):
<form action="json.php" method="post">
<input type="hidden" name="json" value="{'x':1}" />
</form>

you could set an input value to stringified JSON when submitting the form:
<form method="post" action="myscript.php" onsubmit="DoSubmit();">
<input type="hidden" id="myjsoninput" name="json" value="{'x':1}" />
<input type="submit" name="submit" />
</form>
function DoSubmit(){
document.getElementById("myjsoninput").value = JSON.stringify({a:'b'});
return true;
}

Related

Sending data with form and reading it from Request.Form

I have form like below in mvc view:
<form name="aspnetForm">
<input type="hidden" id="ORDER_ID" name="ORDER_ID">
<input type="hidden" id="STATUS" name="STATUS" value="SHOW">
</form>
I want to send it from js with below:
function send(orderKeyId, sUrl) {
document.aspnetForm.ORDER_ID.value = encodeURIComponent(orderKeyId);
document.aspnetForm.action = sUrl;
document.aspnetForm.submit();
}
Everything works, but I have to read it in aspx.cs from Request.QueryString, but I need to use Request.Form because of I need clear url without any queryString inside. I mean, it automatically add ORDER_ID to queryString instead of sending it in form.
You're missing a closing quote in Request.Form["ORDER_ID]

How to access form data from javascript

I am a javascript newb so any help on this matter would be appreciated!
I am trying to get the user submitted data back after submission.
I have a javascript function that replaces one form with another. A kind stackoverflow user helped me create this function.
function Vanish(event) {
event.preventDefault();
// Specify the id of the form.
var IDofForm = "quest";
// Specify the id of the div containing the form.
var IDofDivWithForm = "question";
// Specify the id of the div with the content to replace the form with.
var IDforReplacement = "entryform";
if(document.getElementById(IDofDivWithForm).innerHTML = document.getElementById(IDforReplacement).innerHTML){
return true;
}
else{
return false;
}
}
Then I have my forms :
<div id="question">
<form action="" method="POST" name="quest" id="quest" onsubmit="Vanish(event)">
<textarea name="question" class="question-field" placeholder="Ask your question..."></textarea><br><br>
<input type="submit" name="qsubmit" onclick=" Change();">
<!-- Change() only swaps images on the screen-->
</form>
</div>
<!-- Vanishing Form -->
<div id="entryform" style="display:none;">
<form action="" method="POST" id="email">
<input type="text" name="fName" placeholder="First Name" class="forms" value="<?echo $_POST['question'];?>">
</br>
<input type="text" name="sName" placeholder="Second Name" class="forms">
</br>
<input type="text" name="email" placeholder="Email" class="forms">
</br>
<input type="image" src="images/submit.png" name="esubmit" onclick="submitForm()">
</br>
</div>
As you can see from above I have two forms. the entry form replaces the question form after it has been submitted.
My question today is how do I get the entered data?
I prefer php as I understand it more so if there was a php method to this that would be great however all solutions will be helpful!.
For PHP I have tried using the $_REQUEST and $_POST methods to try and get back the data but it does not work.
My forms all submit to the page they are on.
First of all JavaScript is client side programming language so to get data to server you need to make a http/https request to server and send/receive data
Good read What is the difference between client-side and server-side programming?
and to do that you can either use html Form or ajax
Form
In form you simply send data to url in action ( if no url specified it will make request to current page else specified action url)
Ajax
you can send data using ajax for that you just need to make ajax request like below (i highly recommended to use JavaScript ( but if you are good at JavaScript that you can use Jquery framework too )
var yourFormId = document.getElementById("email");
email.onsumbit = function(e){
e.preventDefault();
var formData = new FormData(yourFormId );
var request = new XMLHttpRequest();
request.open("POST", "your-url");
request.send(formData);
}
// here by formData object you can get all data in single code of line
and to do with jquery see this post it has very simple example jQuery Ajax POST example with PHP
Now couple of good Reads
FormData Objects
Ajax : MDN its really good source

Echoing data from an iframe to the parent page

I have a hidden iframe where the submission of a form is handled. It goes like this:
<iframe name="foo" style="display:none;"></iframe>
So, I was wondering, if it is possible that after the stuff has happened that needs to be within the iframe, I can use javascript or something to print out data on the parent page? Thanks
EDIT: here is my form code.
<form id="bar" name="bar" method="post" target="foo" action="include/database.php">
<input type="text" name="betamount">
<input type='text' name="multipler">
<input type="checkbox" name="hilo" value="High" checked>
<input type="submit" name="submit" value="Bet">
</form>
<iframe name="foo" style="display:none;"></iframe>
Database.php handles these POST requests inside the iframe. Now, there is this one thing inside database.php which goes like this
$betamount = $_POST['betamount'];
$multiplier = $_POST['multiplier'];
$payout = (int)$betamount*(int)$multiplier;
What I want to do is, I want to use AJAX or something to echo out the 'payout' variables inside a div present on index.php
For the purposes of my answer, I'm assuming that the actions you are doing in server side cannot be replaced by a simple client-side one (using javascript).
If you are expecting a return, why don't you use AJAX directly, without iframes? Simply post the data to your php page, and return it asynchronously.
JsFiddle: http://jsfiddle.net/ericwu91/28U8n/
HTML Code:
<input type="text" id="amount" name="betamount">
<input type='text' id="multiplier" name="multipler">
<input type="checkbox" name="hilo" value="High" checked>
<button onclick="submit();return false;">Submit</button>
JS Code:
var yourData = {multiplier:$("#multiplier").val(),betamount:$("#amount").val()};
$.post("yourUrl.php",yourData,function(result){
//Success: Use the "result" parameter to retrieve the data returned from server
alert(result);
});
I'm using jQuery's ajax post method. Documentation here: http://api.jquery.com/jquery.post/
The perks of doing it this way is that it does exactly what you wanted to, but simplifies it by using an almost-native javascript property (asynchronous responses).
EDIT: I forgot to put the real jsfiddle link... And after I pasted all the HTML and JS code, I realized how useless the fiddle is, as it won't return any respose at all... xD

How does this site's url load input values?

I stumbled on this site and want to know how the url is able to update the input values and also update the src of the divs which the gif and iframe which video are in.
http://gifsound.com/?gif=img836.imageshack.us/img836/7826/tumblrlfihla6zaq1qb0ebk.gif&v=DR91Rj1ZN1M
How would this be done with javascript?
It looks like "v" is a variable set to "http://www.youtube.com/watch?"
and the gif is similar and equal to "gif"
I think this thread has some basis, is it the right direction?
Is it possible to update a url link based on user text input?
It isn't done by Javascript. The querystring parameters are interpreted by a server-side process. The <form> which has the textbox submits them via the querystring because it has <form method="get"> instead of post.
Explanation in detail
HTTP has two main request methods: GET and POST.
When you make a straightforward request for a webpage, such as by clicking a link or typing an address into the address bar, the browser will make a GET request, which consists of the path to the resource to get and some headers, that's it. There is no "request body".
A resource path looks like this: /foo/bar?name1=value1&name2=value2
POST requests are different and can only be triggered by a submission of a <form method="post"> (note that method="post" is implied if the method attribute is missing) or AJAX request. They also have a request-body, which is a block of data sent along with the request. This block of data consists of key/value pairs corresponding to each <input> element contained within the <form> element that was posted.
When you have a <form method="get"> (rather than post) each <input> in the <form> is instead converted into a querystring parameter rather than being sent in a request-body, also the method used is GET instead of POST.
In example, this...
<form method="post" action="Page.php">
<input type="text" name="Foo" value="bar" />
<input type="text" name="Baz" value="qux" />
</form>
...results in this being sent from the browser to the client:
POST Page.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
Foo=bar&Baz=qux
(the "Foo=bar..." bit is the request body)
However, this...
<form method="get" action="Page.php">
<input type="text" name="Foo" value="bar" />
<input type="text" name="Baz" value="qux" />
</form>
...results in this being sent from the browser to the client:
GET Page.php?Foo=bar&Baz=qux
(note the lack of a request body)

Making sticky javascript

I have a javascript form where I am using innerHTML to set some text.
When the form submits that information is lost.Is there anyway I can make it "sticky".I was thinking a cookie but that's about all I know.
Thanks
<form "action="" name="myform">
<input type="text" name='name">
<div id="theName"></div>
</form>
Quick example I am capturing the name and need the div to show the name after the form submits.
You will need to persist the data somehow. There are several options:
Store it on the server. When the form is submitted, your server-side script will receive the data; it can persist it in a database, session variable, or some other form of storage that's appropriate for your application. Whenever the client re-visits the page with the form, have the server generate the form's HTML with the persisted data.
Use HTML5's local storage. While not supported in legacy browsers, all modern ones provide the local storage API. When the user submits the form (attach an event listener to the form's "submit" event), you can store the form data by making calls to localStorage[key] = value and retrieving it with localStorage[key].
Store it in a cookie. Although I don't recommend this approach, you can create a cookie with the form data. The only restriction is that the data needs to be represented as a string, but I recommend JSON. However, you probably should not use this approach since cookies are sent to the server for each request; if the form fields contain a lot of data, then you're also unnecessarily sending a lot of data to the server.
Using HTML5's local storage gives you a self-encapsulated approach that requires no server-side configuration:
<form action="" name="myform">
<input type="text" name="name">
<div id="theName"></div>
</form>
<script type="text/javascript">
(function() {
var form = document.getElementsByName('myform')[0];
if (localStorage['name'] !== undefined) {
var displayArea = document.getElementById('theName');
displayArea.textContent = localStorage['name'];
}
form.addEventListener('submit', function() {
var nameField = document.getElementsByName('name')[0];
localStorage['name'] = nameField.value;
}, false);
})();
</script>
Are you setting the "value" attribute of the input tags to something or blank? you can just remove (remove the attribute itself) that so that the last value set will be used (true only for non-password type inputs. also, haven't tried it in all browsers.).
Or better yet, you can use serverside script like (PHP, ASP, RUBY, etc) to set the attribute value to the previously submitted.
<form method="post">
<input type="text" name="txtinput" id="txtinput" value="<?php echo $_POST['txtinput']?>"/>
<input type="submit" value="submit">
</form>
doing it in js only is much more complicated and unreliable since your going to use cookies.
PS: I'm assuming your not using XHR(AJAX) to submit your forms since XHR's don't refresh pages or re-initializes inputs unless you told them to.
This should be happening server-side. Javascript is for enhancing a page, it's not to be depended on for data manipulation.
Your script, converted to PHP, would look like
<form action="" method="post" name="myform">
<input type="text" name='name">
<div id="theName"><?php
if(isset($_POST['name'])) { echo $_POST['name']; }
?></div>
</form>
...and it would work every time, without having to call any JS.
You'll have to handle the form data somehow anyway - how were you intending to retrieve the data without a server-side script?

Categories

Resources