How to add text input variable to URL in javascript - javascript

I'm having the weirdest problem right now. I have this JS code:
function CreateChat() {
var chatName = document.getElementById("chatName").value;
window.location.href = "https://localhost:44321/CreateNewChat/CreateChat?ChatName=" + chatName;
}
Thing is, as it is, I can't make it work. It obviously should be calling a controller method, but it just won't work. If I hit that url with the project running and put anything at the end of it, like https://localhost:44321/CreateNewChat/CreateChat?ChatName=TestName, that test name variable will get to the controller without a problem. If I hardcode to the code the "TestName" instead of passing the chatName variable I define earlier, it will get to the controller, no problem. Hell, if I debug the script, the chatName variable gets loaded correctly with my input, and if I console.log the url it will show up correctly (in fact, I can copy/paste that url and it will hit the controller method correctly). But, as the code is presented above, it will never, by any means, hit the controller. It will reach that point, and cut the execution as if there was an error in the JS code. Do you guys have any ideas on this? It's driving me mad, really.
Just in case, this is how I define the text input in the HTML:
<input type="text" required class="form-control" id="chatName" aria-describedby="nameHelp" placeholder="Name your chat!">
Edit: encodeURIComponent on the chatName doesn't work either.

try using window.open with _self instead:
window.open ('https://localhost:44321/yadayada','_self',false);

You have a submit button (and I assume this button is inside a form)... when you click on the submit button the form is submitted to the submit action of the form, this is the default behavior for the submit action.
Now if you don't want your page to be submitted, you can change the button type to button:
<button type="button" onclick="CreateChat()" class="btn btn-primary">Create a New Chat!</button>
Alternatively if you actually need a submit button then you need to prevent the default behavior in order to change window.location:
function CreateChat(event) {
e.preventDefault(); // <-- don't submit the form
var chatName = document.getElementById("chatName").value;
window.location.href = "https://localhost:44321/CreateNewChat/CreateChat?ChatName=" + chatName;
}
You need to pass the event to CreateChat function:
<button type="submit" onclick="CreateChat(event)" class="btn btn-primary">Create a New Chat!</button>

Related

Firing JS function from another file from button in html file

This might be very basic but I couldnt really find a solution to this. I am creating my own website. I have written a javascript file, simply called "main.js".
I can call my entire script in my HTML file like so:
<script src="main.js">
</script>
And I see in the console that everything works as it should. However, this is not what I want. What I want is the code in the JS script to be fired upon a click on my button. This is what I tried:
<input class="button" onclick="main()" type="submit"
value="Submit" name="">
</div>
So I want the script that I have referenced somewhere else in the HTML file to fire the "main" function when my button is clicked. But what happens currently is that the click onto the button simply reloads the page.
So, to get this all into one question:
I want to click my html button and then fire a single function from another script that is called "main.js".
How can I achieve that?
Thank you
I think this might be because of your type: submit.
Try changing it to type="button".
Hope this helps!
You are trying to call a function called main, but you need to run a script that creates a function. The browser won't go looking in a JS file with the same name as the function automatically.
Edit main.js so the code appears inside a function.
function main () {
// Your code here
}
If you don't want the form to be submitted after the JS function is called, then don't use a submit button to trigger it. Use a type="button".
A submit button triggers a reload as it submits the formto the server, unless your main function returns false.
Adding
return false;
at the end of main should do the trick.

How would I save input from a text box and then move to the next page? (Javascript/HTML)

As part of my new job, I'm creating a small form where users answer a question and this is then saved and output at the end of the pages.
I started off with having a prompt where users were asked to explain their answers (which worked perfectly!), however I've been asked to change this to an input box.
Essentially the process I need to do is:
User enters in text box -> Clicks next button -> save input to session variable and move to next page
So far, I have the following HTML in the body:
<form name="next" action='#' method=post>
Explanation:<input type="text" id="xp" required><br>
<button class="nextButton" onclick="return explanation()">Next</button>
</form>
with the corresponding javascript:
function explanation() {
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
document.location.href = 'page2.html';
}
So far the result of this is:
The text box is cleared, but nothing is saved or displayed onscreen
The next page is not displayed.
Any help/advice would be appreciated. I'm relatively new to js so I'd be grateful! I'm well aware that there are similar questions around, I just can't seem to see where I'm going wrong.
#David is right. You can add event.preventDefault() function to prevent the form from its default behaviour, which is submitting. Otherwise your code seems to work.
function explanation() {
event.preventDefault(); // <-- add here
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
window.location.href = 'page2.html';
}
Also, don't use document.location.href, it's deprecated. It's better to use window.location.href instead.
When you click on nextButton, the browser run explanation() and then try to execute the action of your form. Because your action is action='#' it just try to reload the page, preventing document.location.href for working properly.
Actually, you can try to don't enter nothing on the box and click on the button. The redirect will work because the form is empty, so there is nothing to submit.

Javascript submit function working and not working

I hesitate to ask this as it is a bit complex, but I will try to make it simple.
I have a page with several form fields.
I submit the page via a submit script (note more is done in this submit script, but I am leaving it out for simplicity
function do_file_form_submit(gonext) {
var f = document.getElementById('file_form');
f.gonext.value = gonext;
alert(gonext);
f.submit();
}
Please note that there are other variables included in this function. gonext is not the only one, but I am leaving the others out in this case to keep it simple.
My HTML for simplicity sake looks like this:
<form name="file_form" id=file_form action="<?= $this->URL('#', 'UpdateUploadUser', array('mode'=>'upload', 'ID'=>$_GET['ID']));?>" method="post" enctype="multipart/form-data">
<input type="text" name="oneitem">
<button name="submit1" id="submit1" onclick="do_file_form_submit(2);"><img src="<?=$theme;?>/images/12addphoto32px.png">Save Settings Then Upload/Register Another</button>
On the backend side within the "UpdateUploadUser" function we have a checker which checks each submitted field to see if it is empty or not. If it is empty, it returns:
$this->chk = new mVal($event);
if(!$this->chk->Validate()) {
$this->mode = 'error_redisplay';
//$this->mode='Error';
return;
}
If all info is there, then the script continues and runs as expected. So, here is the issue.
If all information is there, and I click the button, then all works fine. The file_form submit JS ALERTS the gonext value and the script runs and updates as it should.
HOWEVER, if an item is missing, then the validation script runs and "RETURNS".
Once the page has been returned, if you THEN attempt to click the submit button, the page STILL submits as it should, but the file_form submit script seems as if it doesn't even run, so that the gonext value is not passed at all.
So, I am trying to figure out how the submission of the form is still happening apart from this do_file_form_submit script. Is there something having to do with "return" that I don't know about?
Hope that makes sense and thanks for any help!
Craig
Review your code
function do_file_form_submit(gonext) {
var f = document.getElementById('file_form');
f.gonext.value = gonext;//f.gonext. i can not find gonext in ur form. just oneitem try something like f.oneitem.value = gonext; i believe that is where the //problem occurs
alert(gonext);
f.submit();
}
in nutshell, replace the line:
f.gonext.value = gonext;
with
document.file_form.value = gonext;
and then submit like
document.file_form.submit();

javascript createElement/append child -- new text dissapears after click

I have a javascript method that creates a bunch of elements on click. When I call it from a button, it only stays on the screen for the duration of that click. when I enter the exact same code into the console, however, it stays on the page until I reload or navigate away (which is exactly what I want).
JavaScript code: (it's the only method in the js file)
function post() {
var postTitle = document.createElement('h3');
var nodeTitle = document.createTextNode('Immigration is good.');
postTitle.appendChild(nodeTitle);
etc....
Where I'm calling it in the html:
<input type="submit" id="post-button" value="Post" onclick="post()">
The script tag is in the header of the html page.
How do I get it to stay on the page past the duration of the click? Any ideas why it's being immediately obliterated?
You still need to cancel the form's submission. A return false; from post, if it exists, won't work because the onclick attribute is calling post() but not returning anything.
You could change it to onclick="return post();", but it would be better to attach the handler directly, and to the submit event of the form and not the click event of the button (people do use Enter sometimes!):
document.getElementById('some-form').onclick = post;
Look at what the button does. It is posting!
When you click the button it is redirecting you back to the page you are currently on! It seems like it is showing up and disappearing what is actually happening though is that the page is refreshing.
There are a couple of options to do what you want. Submitting via Ajax or having your server respond with a hashbang/cookie set to direct the page to do as you wish.

Submit two forms with one button

I have HTML two forms, one that submits data upon entry to a database using PHP, the other directs the user to a paypal payment page, my problem is that the user would have to submit both forms which of course I do not want them to have to do. Is there anyway to use one submit button for two forms?
(Javascript is welcome)
You should be able to do this with JavaScript:
<input type="button" value="Click Me!" onclick="submitForms()" />
If your forms have IDs:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
If your forms don't have IDs but have names:
submitForms = function(){
document.forms["form1"].submit();
document.forms["form2"].submit();
}
A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:
var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));
document.forms.payPal.submit();
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)
If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.
I recommend you use/generate a single request which you can transact server-side.
The currently chosen best answer is too fuzzy to be reliable.
This feels to me like a fairly safe way to do it:
(Javascript: using jQuery to write it simpler)
$('#form1').submit(doubleSubmit);
function doubleSubmit(e1) {
e1.preventDefault();
e1.stopPropagation();
var post_form1 = $.post($(this).action, $(this).serialize());
post_form1.done(function(result) {
// would be nice to show some feedback about the first result here
$('#form2').submit();
});
};
Post the first form without changing page, wait for the process to complete. Then post the second form.
The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).
I didn't test the code, though.
If you have a regular submit button, you could add an onclick event to it that does the follow:
document.getElementById('otherForm').submit();
if you want to submit two forms with one button you need to do this:
1- use setTimeout()
2- allow show pop up
<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);
}
</script>
<form target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>
javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.
edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.

Categories

Resources