Target an iframe with a HTML Post with jQuery - javascript

If I'm using jQuery or JavaScript to do a post, how can I make it target an iframe rather than the current page?
jQuery.post(
url,
[data],
[callback],
[type]
)
That is the format of the jQuery post, it doesn't seem as though there is anywhere to specify the target like there is in the <form> tag.
Any ideas?

You can do this via a regular form:
<form action="targetpage.php" method="post" target="iframename" id="formid">
<input type="hidden" name="foo" value="bar" />
</form>
You can then use jQuery to submit the form:
$("#formid").submit();

Maybe you are missing the point of an AJAX request - why are you trying to specify the "target" of an asynchronous request? This makes no sense as the whole point of AJAX is that the request from the server gets sent back to the Javascript, free of page reloads or HTML destinations.
If you wanted to load the result of the request onto an iframe, you might do:
$.post('myurl', function(data) {
$('#myframe').html(data);
}, 'html');

You can solve the no-form-allowed-within-a-form problem by dynamically creating the form and appending it to the body. So you'd do something like this:
$().ready(function() {
$('body').append('<form
action="url"
method="post"
target="iframename"
id="myspecialform">
<input type="hidden" name="parameter" value="value" />
</form>');
});
That creates your iframe-updating form outside of the main form that encompasses everything else on the page. Then just call it as Josh recommended: $('#myspecialform').submit();.

here is how I did it in javascript with plain html:
var form=$("<form/>").attr({
method: "post",
action: "iframe.php",
target: "list_frame"
});
form.append($("<input/>").attr({name:"field1",value:0}));
form.append($("<input/>").attr({name:"field2",value:1}));
form.append($("<input/>").attr({name:"field3",value:2}));
form.append($("<input/>").attr({name:"field4",value:3}));
form.append($("<input/>").attr({name:"field5",value:4}));
$("body").append(form);
form.submit();

I know this question is old, but here's how I did it on ASP.Net (C#) using jQuery.
//Create the form in a jQuery object
$("<form action='/FormPostTo.aspx' method='post' target='nameofframe'></form>")
//Get the value from the asp textbox with the ID txtBox1 and POST it as b1
.append($("<input type='hidden' name='b1' />").attr('value',$('#<%= txtBox1.ClientID %>').val()))
//Get the value from the asp textbox with the ID txtBox2 and POST it as b2
.append($("<input type='hidden' name='b2' />").attr('value',$('#<%= txtBox2.ClientID %>').val()))
//Add the form to the body tag
.appendTo('body')
//Submit the form which posts the variables into the iframe
.submit()
//Remove the form from the DOM (so subsequent requests won't keep expanding the DOM)
.remove();
Just a quick note: I did the input tags like that rather than concatenating them, in case the value of the textbox had a quote (') in it. If you concatenated it in, it would mess up the HTML and it wouldn't parse correctly.
Also, this removes the form from the DOM after it's been used so you don't fill up the DOM with form elements if you post to the iFrame multiple times.
One slight change that you could make, would be to create the form element if it doesn't exist and then just reference it by ID if it already exists and reuse it.

Here's what I did to get around the issue of having a form within a form on a asp.net page when I needed to submit data to a remote page via a form ideally using AJAX / jQuery.
I created variables to capture the asp.net form name, target,
action, method, etc.
I held that information from the form in
those variables and then changed the form itself using jQuery to do
what I needed it to do.
Then I posted the form via AJAX (because I needed a form to post to a seperate page dynamically so the other
page could GET the info).
Finally, I changed the asp.net form back
to the way it was so the rest of the page could work correctly.
This seems to have resolved my need for a similar solution.

You're missing the point of AJAX. If you want to post something to an iframe, you could do this by a simple form, posted by JavaScript or by the usual way: a submit button.

Related

Span variable not being read in php

I have a website that receives parameters in the URL address (www.xxx.html?name=David)
then I assign the value to the html text like this:
<span name="uname" id="uname"> </span>, I'd like to thank you
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var userName = getParameterByName('uname');
document.getElementById("uname").textContent = userName;
});
</script>
up to this point everything works well
now when I try to read again the value in uname in the PHP file in order to send it in the email I have two issues
the parameter is not received - emailText = $_POST['uname'];
when trying to debug I see the HTML file and js file being loaded and can be debugged but the PHP file doesn't exist in the file tree of the debug
BUT it is being loaded and read because other variables are being read and sent correctly to the email.
When submitting a form the user agent (browser) will build a form data set from
"Succesful controls".
A Control is one of the following:
buttons
checkboxes
radio buttons
menus
text input
file select
hidden controls
object controls
Only these fields will be submitted when you submit a form. A <span> is not part of that.
If you want to add a value with JavaScript to the form that is not inside of a text input, I suggest that you use a hidden input to do so.
<input name="uname" type="hidden" value="value">
When you edit the span, you should then also change this hidden field to the same value.
You cannot use span with name attribute.
Read this
https://www.w3schools.com/tags/tag_span.asp
If you want to post, use form + proper input element.
https://www.w3schools.com/html/html_form_input_types.asp
And still, it's not very clear you are really trying to do, show us the whole page ...
If I need to get value of span ill do something like this
<span data-name="someTextHere">...</span> # data-name will not visible in browser unless page source mode
and you can access it by using ($(this).data('name'))
Ex
var userName = ($(this).data('name'));
And this article Submit Form Using Ajax, PHP and jQuery will helps
you to pass data without Undefined Index Error.

Accessing AJAX added inputs with JQuery

I have a form that on document load, loads additional fields based on previous selected values on another page. This is all done with JQuery. Rather than posting all my code in here right now, here is a basic mockup on what I am doing...
<form>
<input>
<input>
<div id="loadedcontent">
<AJAX loaded inputs on document load>
</div>
<input submit button>
</form>
<script that posts to a PHP file and retrieves the form inputs. They all have ID's. The script also has a form submit listener to process it all.>
The problem is in the listener for the form submit, I cannot access the ID's of the previously loaded AJAX elements. Is there something I am missing?
You need to add your code. It may be that when you attempt to retrieve the Id's loaded by the ajax, the Id's do not exist in the DOM. Sometimes a delay needs to be added to ensure the content exists within the DOM before you actually access it.
var i = setInterval(function() {
//some ajax call on load
clearInterval(i);
}, 500)

Change search from /?s=searchterm to /searchterm without htaccess in js

I'm trying to use the below search form and js to search my site. However, whenever you type a word in the form and click submit the form them takes the users browser to http://example.com/?s=searchterm , but I want it to take them instead to http://example.com/searchterm and totally leave out the characters ?s=
<script type="text/javascript">
function submitform()
{
document.forms["searchsite"].submit();
}
</script>
<form id="searchsite" action="/">
<input type='text' name='s' placeholder='search'>
Submit
</form>
Any positive advice? Btw, no, I don't believe I can use htaccess and mod_rewrite since I already have rules set.
You could set an onsubmit handler to intercept the form’s submission and replace the default action with setting the location href. This relies on JavaScript being enabled in the client side:
<form id="searchsite" action="/" onsubmit="javascript:location.href=this.action + encodeURIComponent(this.elements.namedItem('s').value); return false;">
This escapes the search term so that if the user enters something with ? or / in it, the server will interpret that as part of the path instead of thinking that the client is trying to send a querystring or access some subdirectory. The return false; states that the browser should stop its normal form submission procedure since the onsubmit handler has already updated location.href, which will cause the browser to start navigating as soon as the onsubmit handler returns.
However, you really should supplement this with server-side code. For something this simple, the JavaScript can be there to make your URIs pretty while skipping an HTTP redirect (so that the browser goes directly to the requested page slightly faster than otherwise). But you should really have a server-side redirect that gets triggered whenever the GET s parameter is sent.
Extra note: you should really replace your submission script with a <button/>, like:
<button type="submit">Submit</button>
and just drop your <a/> and <script/> tags completely. You get all of the functionality you need by overriding the form submission handler itself, no need to try to intercept button clicks, etc. With this change, your form should now work when the user presses ENTER instead of requiring the user to TAB to the <a/>. Use the intended HTML elements for their intended purposes and hook into the right events ;-).
I assume that your question is only about the client-side of the code and that you already have figured how to get your server-side code to read the value from the URI path. Figuring out how to read the value, if it is submitted this way, would take me some time to research and would require more information about your server-side setup.
Instead of submitting the form, build the URL and then set the location. You can add an ID to the search term (s in this case) and then simply build the URL:
var searchTerm = document.getElementById("s").value;
document.location = "http://example.com/" + searchTerm;

How do I access form data submitted by a user in Javascript?

I'm relatively new to programming, but understand the basics of HTML, CSS, and Javascript (including jQuery). Due to my greenness, I'd appreciate it if answers contained both a simple solution and a reason as to why the solution works. Thanks!
So I've got a form, with a text input and a submit button:
<form>
<input type="text">
<button type="submit">Submit</button>
</form>
When the user types data into the text field and clicks submit, how do I gain access to this data? If a user inputs their name, how do I grab that information? I don't intend to store it or write it anywhere, just to hold onto it as a variable in javascript, which I'll assign to a jQuery cookie.
So how do I access the data that the user has submitted, preferably using only Javascript (with jQuery)? Thanks for the help!
You access the data on the server side (in PHP via $_POST['username'] for example). The form sends data to your sever for any named input, so you would probably have to change the input to:
<input type=text name=username>
If you want to access it on the client side (with JavaScript), you can do that too, but you have to prevent the form from submitting:
$("form").on('submit', function (e) {
$.cookie('username', $(this).find('[name=username]').val());
//stop form from submitting
e.preventDefault();
});
say you had an html input tag such as:
<input id="textfield" type="text">
using javascript, you can store the value of that field in a variable like this:
var inputvalue = $('#textfield').val();
of course, you'll need something to run the script.
the reason this works is that the the textfield is an object. you might think of it as a tree trunk with different branches coming out. one of these "branches" is the value contained inside of it. since you know jquery, you know that $('#textfield') gets the element by a selector. the period says we're getting one of the branches, and "value" says we want the branch that tells what's in the textfield.
hope this helps.

post non form values?

I am wondering if it is possible to somehow get the value of a div and attach it to the form post on submit?
Using JavaScript, you can get the DIV contents and insert them into a hidden form field.
An example - a page snippet (jQuery used for simplicity, plain JS would work too):
<form id="yourform" action="/some/uri">
<input type="hidden" name="your_div_content" id="hidden_element" />
<input type="submit" />
</form>
<div id="yourdiv">
This text will be copied into the form using JS
</div>
<script>
$('#yourform').submit(function(){ /* On #yourform submit ... */
$('#hidden_element').val( /* ... set #hidden_element's value ... */
$('#yourdiv').html() /* ... to whatever is in #yourdiv . */
);
});
</script>
Of course, this will only work when JS is enabled in the browser.
You may want to use a hidden field <input type="hidden"> in your form, and then set the value of your hidden field on form submit with the innerHTML of your div.
You could use ajax. That way you could send whatever data you wanted however you wanted.
For instance (this is using mootools):
var req = new Request({url: 'somepage.php', data: 'queryStringDate'});
req.send();
There you go :)
This of cause can be done without any framework, I just don't remember the code in my head :-P
It depends what you mean by the "value of a div".
For example, you can retrieve all HTML inside the div by using document.getElementById(your_div_id_here).innerHTML
Alternatively, you can access values of the div attributes by using e.g. document.getElementById(your_div_id_here).title to access the div's title attribute.
If you intercept the submit event of your form (maybe by intercepting the click event on the form’s submit button), then you certainly can GET or POST with anything including content of an element. With vanilla HTML, however, I’m afraid it’s not possible.
Tucking values into hidden fields might also work, depends on preference. ;)
You could have a hidden input and populate it with the contents of the div before doing your submit, then it would be included.

Categories

Resources