I have a web app written in angularjs that I want to send respective values from individual pages to a server via a GET request but I'm having it done automatically when the page loads.
A snippet of my code is below:
<script language="javascript">
function loaded(){
document.getElementById("dataSubmit").submit();
}
</script>
<form id="dataSubmit" action="http://127.0.0.1" method="get" target="submission.frame">
<input name="data" type="hidden" value={{myData}}>
<input type="submit" id="subbut" value="submit">
<iframe name="submission.frame" hidden></iframe>
</form>
<script>
window.onload = loaded();
</script>
My code above automatically sends the input data named "data" with value {{myData}} which, depends on what page the user is on, to the ip 127.0.0.1 and a script runs at that end and writes the data to a text file.
The problem is that when I try to pass the Angularjs expression {{myData}}, instead of passing the data fetched automatically when the page is loaded, it sends a string literal "{{myData}}" and writes that to the file at the other end.
However, when I click the 'submit' button that I've added to the form, the data sends perfectly and the value that I wanted is written to the file.
I tried using an onload function so that the submission only occurs after the page has loaded so the expression has had time to evaluate but still no luck.
For those wondering, my iframe tag makes it so that the submission form is invisible so when the submission occurs it does not redirect the user to the IP that the data is being sent to.
To clarify the problem, the angular expression {{myData}} is not being evaluated when the form is submitted upon page load, but when the submit button is clicked, {{myData}} evaluates and the value is sent. I need the value of {{myData}} to be submitted in the form when the page loads.
Any help would be greatly appreciated.
What you are facing is a pretty normal behavior, of course the page is finished loading but Angular didn't have time to evaluate the template interpolations.
To be honest I'm not sure what you are trying to achieve with that automated form submition, you can just use the $http service to send the data to whatever end-point you want. This way you know exactly when you have the data attached to the variables.
Tho if for some REALLY weird reason you still want to do the normal javascript form submition you need to create a directive in which you will include the $window service and add scome code looking like:
var autoSubmit = function () {
$scope.$watch("myDataVariable", function (newVal) {
if (newVal) {form.submit()}
})
}
$window.bind("onload", autoSubmit);
The code is not tested, it's a sample of how I would do it ... well I won't do something like that but you know what I mean.
Related
Am a newbie, a hardcore one.
I am in a need of reloading page with passing variables; so when the page is reloaded it would already have those variables before initializing some of the elements (as u can guess, those variables will be used there).
I need this because I am working with an old videoplayer, which can't be reset on-the-fly, the whole page has to be reloaded to re-initialize it with new params.
Also these variables cannot be passed through url, because they are too long.
I would be glad to see any help and to answer clarifying questions as well.
Thanks!
UPD1: There's no real need to delve into specifics of my code thus not posting it; Just imagine a simple page with a textfield and a button, where user enters a string, presses the button, then the page reloads getting that string into a global variable.
UPD2: Found this code on a related page:
$.ajax({
type: "POST",
url: "packtypeAdd.php",
data: infoPO,
success: function() {
location.reload();
}
});
That is how I post the data and reload. But how do I get it after reload then? How is this data accessible?
What about making a simple HTML form with attributes action="" and method="post" like:
<form action="" method="post"> <!-- in action specify where you want the content to be sent, the method speaks about his self -->
<input type="[type]" name="[name]"> <!-- in the name attribute define the name with which you can call the data in PHP via $_POST[name] -->
...some input fields...
...submit btn probably...
</form
Note: clicking the submit button automatically send the information to the page and redirects you to it. If you leave action empty like above it will redirect you to the same page (refresh it) and receive the data from the form.
Also if you don't want to use a form you can simply set cookies with PHP. For example:
setcookie($name, $value, $expireDate, $path(e.g "/");
And then just take information from the cookie with:
$_COOKIE[$name]
Note: in order to make cookies work, you need to refresh the page, so they can be set!
<form action="/devilmaycry/register?action=addtocart" method="post">
<input type="hidden" name="user" value="<%=user%>"/>
<input type="hidden" name="pid" value="<%=pid%>"/>
<input type="submit" value="Add to cart" onclick="add();"/>
</form>
i am using the above code to submit a form and add a product to cart
the java code it calls is as follows:
else if(n.equals("addtocart"))
{
String user = req.getParameter("user");
int pid = Integer.parseInt(req.getParameter("pid"));
k=o.addintocart(user,pid);
if(k==1)
{
pw.println("<h3>Added to cart !!!<h3>");
}
else
{
pw.println("<h3>Errror , try again <h3><br>");
}
it does add the product to the table but it changes the jsp page ... i tried to use requestDispatcher but the URL has many parameters so i want something else through which i can retain the same page and update the table also
In order to stay on the same page you need to use AJAX rather than submit the form in the traditional way. HTTP works in a request-response fashion, so when the user submits the form, the browser expects to receive a new page in the response from the server, and will thus refresh the page and render the new HTML it receives.
You have two options here:
Stick with the traditional HTTP form submission request-response approach, and when you receive the request on the server to add an item to the card, after you add the item to the card, rebuild the URL of the page that is showing the information to the user. In this case it is important to use the 'Redirect-After-Post' approach (i.e. in the response to the form POST you put a redirect to the page). Otherwise if the user refreshes the page by pressing F5, the form data will be resubmitted again and the item added again to the cart.
Go for an AJAX approach. In the add() function, you need to submit the form using Javascript. If you are using JQuery it makes it very easy for you to do this. There are various questions / examples if you search around, such as the one here.
In the latter case you will need to change a bit how you process the information from your Servlet but its the only way to get the browser to stay on the same page (without reloading it). You also have the success and error handlers, which you can use to show a message on the screen to display the result.
I am writing code for a small webproject using js and jquery. In it, at some point, onclicking a button, i create a dialog. the dialog has a form within it with a name field and some number fields. I am supposed to check user inputs and send them to server, along with appending the name field to a list in the browser, to intimate user, one more item has been added. Two strange things are happening -
1) After posting the form, the dialog box closes on its own without me issuing a dialog('close') anywhere in the submit button handler.
2) The name entry doesn't get appended to the list. Its as if the whole page refreshes after the submit. With the original default entries of the list of names.
Anyone has any ideas on why this is happening? Would post some code for your aid.Please don't suggest to use Ajax instead. I think this reflects some fundamental flaw in my understanding of JS ways and would like to clear it first than just switching to some other technology.
<div id='dialog' title='Define New Matrix'>
<form name='form1' id='form1' method='post'>
<fieldset>
<label for="Name">Name</label>
<input type='text' name='nameofmatrix' id='Name' class='whitepanes'><br>
<label for="a11">a11</label>
<input type="text" name='a11' id='a11' class='whitepanes number-field'><br>
<label for="a22">a22</label>
<input type="text" name='a22' id='a22' class='whitepanes number-field'><br>
<button id='submit_button'>Submit</button>
<button id='cancel_button'>cancel</button>
</fieldset>
</form>
<p id='tip' style='color:red;'><i>All fields are required</i></p>
</div>
<script>
//#button_define is a button on whose clicking the dialog opens.
$('#button_define').click(function(){
$('#dialog').dialog('open');
$('#tip').html("<p style='color:red; font-size:small'>All fields are mandatory</p>");
});
$('#submit_button,#cancel_button').button();
$('#cancel_button').on('click',function(){
$('#dialog').dialog('close');
});
$('#submit_button').click(function(event){
event.preventDefault();
var name=$('input[name=nameofmatrix]').val();
//Validate is a function which returns a bool if validation proceeds correctly
var isCorrect = Validate();
if(isCorrect){
//if validated correctly then add to list
$('#form1').submit();
//$('#dialog').dialog('close');
$('#selectable').append("<li class='ui-widget-content'>",name,"</li>");
}
});
</script>
Its as if the whole page refreshes after the post. with the original entries.
That's precisely what happens. Though I'm not sure where you're submitting the POST request to since there's no action attribute on your form. But a standard non-AJAX request triggered by a form sends the request to the server and then renders the response from the server. If the response is this same page again, then this same page will be rendered again.
JavaScript isn't going to remember the state of the previous page when it loads this new response. Even if they're the same page, they're two separate responses from the server. So...
1) After posting the form, the dialog box closes on its own without me issuing a dialog('close') anywhere in the submit button handler.
The dialog isn't closing. After the page refreshes you're in an entirely new page context. It didn't close, it just hasn't been opened yet in this context.
2) The name entry doesn't get appended to the list.
There's nothing that would cause this to happen when the page loads, so in the new page context it doesn't happen. Your server-side code would need to include this content in the response to the POST request.
I think this reflects some fundamental flaw in my understanding of JS ways and would like to clear it first than just switching to some other technology.
Included in that misunderstanding is the fact that AJAX is part of JavaScript. (The "J" in "AJAX" stands for "JavaScript.") It's not "switching to some other technology." It's taking advantage of the capabilities of the technology you're already using. All AJAX does, really, is send requests and receive responses to/from the server without refreshing the page context.
You are not properly appending the name. The concatenation operator is not a comma, but a + in javascript:
$('#selectable').append("<li class='ui-widget-content'>" + name + "</li>");
Next, the form refreshes because you are submitting the form using $('#form1').submit();. If you do not want the page to refresh while submitting, use ajax.
I am attempting to create an HTML form, that of which uses the submit button, to email me the data that has been entered (have that part covered) but also send the data to another external page (that can handle this request).
I can have it working by doing:
<form name="contactform" method="post" action="http://somesite.com/page.php">
But, I also need it to submit to a local page (form.php) at the same time.
I have tried javascript, by doing this for the submit button:
<input type="submit" value="Submit" onclick="return doSubmit();">
With this code in the source:
function doSubmit()
{
document.contactform.action = "form.php";
document.contactform.submit();
document.contactform.action = "http://somewebsite.com/page.php";
document.contactform.submit();
return true;
}
But when I do this, the information is not sent to my email, and instead of displaying the result on form.php the page is refreshed.
Any ideas on how I can make this work in a simple way?
You can't submit to multiple actions at the same time as the browser can only load one request per window at a time by design. Some solutions include:
Just do the email handling with the same server script that does the form input handling
Send the form data to the email script via ajax and then submit the form normally on completion, e.g.
I would recommend adding/altering a function in your php script. Then you can do whatever you like with the posted data.
Obviously you cannot submit two forms. You can try either of these two things:
Make one of them an ajax request, and set it to be executed before submit.
Execute the second php file directly from the first one in the server
side.
I have an issue regarding sending form values to a script. I have a form set up, and upon the user pressing a button I want the values in the form to display on another part of the page. I can easily do this with php or another web scripting language, but all I know is how to do this by sending it to the script in a form of
http://www.example.com/myScript.pbp?value1=VALUE
is there a way to do this without loading a new page? Like just show a loading overlay on the page until the script completes and displays the value on the page?
I'm guessing this would be accomplished using Javascript or Ajax or something like that.
If anyone could help me out, or even just say where I should start to look, I'd really appreciate it!
Indeed. Just attach an onsubmit event listener to your form that always returns false to prevent actual sending of your form via the usual GET or POST request.
In your event listener you can send the form values using XMLHttpRequest and let the callback function update the relevant part(s) of your page.
But remember to always create a fallback option (with the usual GET or POST request of the form) to handle your form in case JavaScript is not available (e.g., turned off, blocked, etc.).
Yes AJAX would be exactly how you would do it. Have a look at the tutorial over at Tizag: http://www.tizag.com/ajaxTutorial/index.php
That will get you started in no time at all.
If you just want the values in the form to display on the page again without any interaction with the server then something like jQuery would be the best approach.
Jquery has a nice form plugin that you can do the following:
var form_values = $('#form_name').formHash();
the form_values will then be a hashed array of your form values in the system i.e.
<form id="test">
<input id="test1" name="test1" type="text" value="Test Text"/>
</form>
So form_values['test1'] would hold the value Test Text in it
Once you have the values you could then use some other jquery functions to display them on the page i.e.
<div id="displayDiv"></div>
then your javascript could be
for (key in form_values) {
$('div#displayDiv').append('<div>Key: ' + key + ' Value: ' + form_values[key] + '</div>');
}
This would put your values in the display div
Here is a simple javascript ajax object. You can use without loading any library.