Submit form and load iframe at same time
开发者_JAVA技巧I want to be able to submit a form and load an invisible iframe at the same time to essentially trigger two things - 1. perform a search using Bing's API and 2. Get the entered text in the input to be read out loud.
I've got both working independently but not at the same time.
I've read that you can't have 2 form actions so is it possible to do something with onclick on a submit button?
Here's my code, I have two forms at the moment, I want to some how combine them to perform both things when clicking one button. I'm completely open to other suggestions on how to do this!
<html>
<head>
<link href="styles.css" rel="stylesheet" type="text/css" />
<title>PHP Bing</title>
</head>
<body><form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Enter Search:<input type="text" id="searchText" name="searchText" value="<?php
if (isset($_POST['searchText'])){
echo($_POST['searchText']); }
else {
echo('');
} ?>"/>
<input type="submit" value="Search!" name="submit" id="searchButton" />
<?php
if (isset($_POST['submit'])) {
$request =
'http://api.bing.net/json.aspx?Appid=8CFD0925A6B1745AFE2F0F359DCD8D4D9DD6A5CE&sources=web&Web.Count=5&query=' . urlencode( $_POST["searchText"]);$response = file_get_contents($request);
$jsonobj = json_decode($response);
echo('<ul ID="resultList">');
foreach($jsonobj->SearchResponse->Web->Results as $value) {
echo('<li class="resultlistitem"><a href="' . $value->Url . '">'. $value->Title .'</a>');
echo('<p>'. $value->Description .'</p>');
echo('</li>');
}
echo("</ul>");
}
?>
</form>
<form method="post" action="http://vozme.com/text2voice.php" target="hiddeniframe">
<textarea id="text" cols="40" rows="1" name="text">
Enter Text
</textarea><br>
<button style="background-color:white;
background-image:
url(http://vozme.com/img/megaphone40x40w.gif);
background-position: top center;
background-repeat:no-repeat;
height: 48px; font-size:70%;
padding:4px 4px 4px 44px;">
</button>
</form>
<iframe height="1" width="1" name="hiddeniframe" style="display: none;"></iframe>
</body>
</html>
You need to register the button click event in JS, and make it 1) load the iframe, and 2) submit the form. (if you did it the other way around, the iframe load might be aborted when the top page is unloaded)
Simplified example (using jQuery for brevity):
<form id="someform" action="/foo/bar" method="POST">
<button id="yourbutton">should trigger two actions</button>
</form>
<iframe id="some_iframe"></iframe>
<script>
$(document).ready(function(){ // register to run this when page is ready
$('#yourbutton').click(function(){ // register to run this when #yourbutton clicked
$('#some_iframe').load(function(){ // register to run this when #some_iframe loads
$('#someform').submit();
});
// and *then* load the iframe
$('#some_iframe').setAttribute('src','http://example.com/some/URL');
});
});
</script>
精彩评论