jquery append innerHTML by id in new window after load - javascript

I'm trying to use jquery to :
open a new window/tab (same domain, different page)
then add text to a text box (id = "BUpdates_SQL_Statement")
then click this button: <input type="submit" value="Apply Changes" name="BUpdates_Submit" id="BUpdates_Submit">
then close the window
here's the onclick element in the starting page (we'll call it www.mydomain.com/firstpage):
<li id="MainNav_Update"><span class="MainMenuText" onclick="runUpdateWindow();">Update</span></li>
and here's the area I want to edit in the new window (we'll call it www.mydomain.com/secondpage)
<textarea id="BUpdates_SQL_Statement"></textarea>
<input type="submit" value="Apply Changes" id="BUpdates_Submit">
<a onclick="v$('BUpdates_Submit').click();return false;" href="javascript:void(0);"><span>Apply Changes</span></a>
side note: v$('BUpdates_Submit').click();return false;" is for another external js file that has nothing to do with what I'm trying to do here.
and here's my jquery:
function runUpdateWindow() {
var updateWindow = window.open("www.mydomain.com/secondpage", "blank");
}
var updateSQL = 'UPDATE TABLE ...';
$(updateWindow).on("load", function (){
$("BUpdates_SQL_Statement", updateWindow.document).append(updateSQL);
$('BUpdates_Submit').trigger('click');
});
updateWindow.close();
The www.mydomain.com/secondpage is opening in a new tab, but the BUpdates_SQL_Statement should be:
<textarea id="BUpdates_SQL_Statement">
UPDATE TABLE...
</textarea>
but it's still blank.
I would sincerely appreciate any input. Thanks in advance!

From what I understand, what you're trying to do is automate filling out and submitting a form, and have selected a seemingly rather straightforward way of doing that. Whether or not that works, though, there's probably a simpler way.
Think about what happens when you open that other page, fill out the form, and press submit. If it's a normal HTML form with no JavaScript interfering with it, you'll probably just get a POST request. If I had this form, say:
<form action="run-sql" method="post">
<textarea name="sql"></textarea>
<input type="submit" value="Run query">
</form>
When I submitted it with some SQL, the browser would send a POST request to run-sql with one parameter, sql. Firing off a POST request is relatively simple to do from JavaScript, at least in comparison to automating another web page. Firing off an HTTP request from JavaScript is typically called AJAX, and fortunately, jQuery makes it easy with its $.post function.
So how would one use it? In that specific example, it would be as simple as this:
var mySQL = "select * from employees"; // e.g.
jQuery.post("run-sql", {sql: mySQL}, function() {
alert("Success!");
});
Now, some forms are not so simple as this, but it's worth a shot to see if your form is.

Went with doing an iframe rather than a new window:
function runUpdateWindow() {
var frame = document.createElement('iframe');
frame.src = "www.mydomain.com/secondpage";
document.body.appendChild(frame);
var frameWindow = frame.contentWindow
var updateSQL = 'UPDATE TABLE...';
frameWindow.onload = function (){
var textarea = frameWindow.document.getElementById("BUpdates_SQL_Statement");
var button = frameWindow.document.getElementById("BUpdates_Submit");
textarea.value = updateSQL;
frameWindow.v$('BUpdates_Submit').click();
};
}
a huge thank you to Dagg Nabbit for helping me figure this out!

Related

Multiple forms with one button for 2 different functions [duplicate]

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.

Dynamic form not submitting (jQuery)

I'm creating a simple task manager app with PHP, MySQL, & jQuery. I'm adding a feature that will allow users to add a task by clicking a "new task" button, typing into a text field and hitting enter. This is the jQuery I have:
function add_task() {
// Add the "add new task" button
$("<span class='add-new'>Add new item</span>").appendTo(".sub-phase");
// String for the input form
var task_form = '<form class="add-new-task" autocomplete="off"><input type="text" name="new-task" placeholder="Add a new item..." /></form>';
// Display form on button click
$('.add-new').click(function() {
$(task_form).appendTo($(this).parent());
});
// Post results
$('.add-new-task').submit(function(){
var new_task = $('.add-new-task input[name=new-task]').val();
if(new_task != ''){
$.post('includes/add-tasks.php', { task: new_task }, function( data ) {
$('.add-new-task input[name=new-task]').val('');
$(data).appendTo('.task-list').hide().fadeIn();
});
}
return false;
});
}
If I have the form hardcoded in the index.php file, this functionality works as expected. But if the form is created in jQuery like I have it here, then nothing happens on submit. I've searched around but haven't been able to find a solution that works.
Any advice is much appreciated! Thank you.
The issue is that you're not delegating the event. You've setup a submit handler on page load, but not for dynamically created elements.
Change:
$('.add-new-task').submit(function(){
To:
$(document).on('submit', '.add-new-task', function(){
Now the event handler is bound to the document and will trigger for any element on the page with .add-new-task regardless of whether or not it was dynamically created.
Also, of note, you should avoid binding to document where possible, and instead, should bind to the closest static parent element.
Please check the fiddle here - http://jsfiddle.net/kunaldethe/TQa97/
Here jQuery 1.7.2 is used and as answered by Ohgodwhy,
$(document).on('submit', '.add-new-task', function(){
is used instead of
$('.add-new-task').submit(function(){
In the Javascript Console (F12), you can see the request is sent. (Obviously we don't have the next page, so the request is not completed.)
If you use the jQuery with version less then 1.7.2, the code breaks.
Let us know, the environment you are using.

Display Results of Form Submission on New Tab or Window

There are several variations of this question already out there but I don't see the solution to this one specifically. Although I don't actually need this functionality it is killing me that I CAN'T make it work!
I have a field that allows the visitor to type in a URL and it will take them there.
<form name="urlField" onsubmit="return submitURLFieldForm();">
<input type="text" name="address" id="addressfield" />
</form>
The JS that handles this so that the necessary protocol is not left off is (special thanks to #h2ooooooo ):
function submitURLFieldForm() {
var url = document.getElementById('addressfield').value;
if (!url.match(/^[a-zA-Z]+:\/\//)) {
url = 'http://' + url;
}
window.location.href = url;
return false;
}
If I add a target="_blank" to my opening form tag it doesn't work. Why? And where should I add it?
You are never submitting the form.
You have an event handler that, when the form starts to submit, sets location and prevents the normal form submission.
Use window.open(url) instead of that if you want to open a new window.
var win=window.open(url, '_blank');
win.focus();
You can try this :)
happy coding :)

launch two actions in one button ASP.NET

I'm developing a comment page in asp.net, this my page :
<form action="#">
<p><textarea id="textArea" rows="5" cols="30"></textarea></p>
<input type="submit" value="Submit" />
</form>
<p>Add some comments to the page</p>
And this is my javascript code :
window.onload = initAll;
function initAll() {
document.getElementsByTagName("form")[0].onsubmit = addNode;
}
function addNode() {
var inText = document.getElementById("textArea").value;
var newText = document.createTextNode(inText);
var newGraf = document.createElement("p");
newGraf.appendChild(newText);
var docBody = document.getElementsByTagName("body")[0];
docBody.appendChild(newGraf);
return false;
}
Until then, everything is fine, but I want when the user clicks the submit button, the button will trigger another action that will save the comment in the database.
How can I do this thing ?
Why don't you have a wrapper and still make it one function?
The addNode could have code to do both maybe based on something in the form?
You could have a submit function that wraps the addNode and addComment.
eg:
function handleSubmit()
{
addNode();
addComment();
return false;
}
EDIT: Since you want to call server code you have a couple of options. You can do it all via ajax and you would just need to implement the addComment function to call a server side event. See this article if you need help doing so:
http://www.dexign.net/post/2008/07/16/jQuery-To-Call-ASPNET-Page-Methods-and-Web-Services.aspx
The easiest way would be to change your button to an ASP.NET button and then implement the button click event which would call your server side method although this would cause a full page refresh.
A hybrid of the two, which is very easy to implement, would be to use an UpdatePanel. When you clicked your button you would get the look and feel of the AJAX solution but only need to know how to do all the server side code and let the UpdatePanel handle all the AJAX work. This method is a little heavier than just doing a raw ajax call but it is significantly more simple to do.
You can read up on UpdatePanels at: http://msdn.microsoft.com/en-us/library/bb399001.aspx
Instead of using an HTML input tag, use asp:Button, like so:
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" />
What this says is, use a Button that calls the "btnSubmit_Click" method whenever it is clicked on, and run this on the server (not on the client machine).
Then in your code-behind (you do have a code-behind, right? e.g., nameOfPage.aspx.cs), you can add the aforementioned btnSubmit_Click method:
protected void btnSubmit_Click(object sender, System.EventArgs e) {
// interact with database here.
}

jQuery onclick pass post variables and reload page

Can I pass post variables and reload a page on clicking an hyperlink?
To be clear I have something like this.
Click
If javascript is enabled,
I think I can use "event.preventDefault()" to suppress passing as GET variable.
So now onclick, name should be passed as post variable instead of get.
If javascript is disabled,
Then the above should work.
You could do it, by creating a new form element, pointing it at the href and calling .submit() on it.
<a class="postlink" href="test.php?name=test">Click</a>
<script type="text/javascript">
$('.postlink').click(function() {
var form= document.createElement('form');
form.method= 'post';
form.action= this.protocol+'//'+this.hostname+this.pathname;
$.each(this.search.slice(1).split(/[&;]/g), function() {
var ix= this.indexOf('=');
if (ix===-1) return;
var input= document.createElement('input');
input.type= 'hidden';
input.name= decodeURIComponent(this.slice(0, ix));
input.value= decodeURIComponent(this.slice(ix+1));
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
return false;
});
</script>
Or you could just do an AJAX request instead and reload() the page afterwards if you prefer.
However, I'm not sure why you'd want to do this. What use is a link that's usually POSTed, except when it's not? (Not just when JS is disabled/unavailable or when it's a search engine, but also when the user middle-clicks the link or tries to right-click-bookmark it or whatever.)
If all you want is something that behaves like a button to submit a POST form, better to actually use a real form and submit button, and then use CSS to restyle it to look like a link if that's what you want it to look like.
Very good hint....
I was first trying to send the form data via an Ajax Post call and reloading the page afterwards, but it was not working properly:
var biq_select_val = jQuery('#biq_search_select').val();
jQuery.post(window.location.href,
{ biq_amazon_item_list_search: biq_select_val},
function() {window.location.reload();}
);
Now I am using just a:
jQuery('#biq_amazon_item_list_search_form').submit();
and it is working fine.
I have some 10 links on a page. When user clicks on those links ajax-reload must take place.
To be clear I have something like this.
one
Two
If javascript is enabled,
Onclick, ajax load must take place.
If javascript is disabled, Then the above should work.
Basically I am using name to limit some values of my search page.

Categories