AJAX request callback using jQuery - php

I am new to the use of jQuery for handling AJAX, and have written a basic script to get the basics down. Currently I am POSTing an AJAX request to the same file, and I wish to do some additional processing based on the results of that AJAX call.
Here is my code:
**/*convertNum.php*/**
$num = $_POST['json'];
if (isset($num))
echo $num['number'] * 2;
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style type="text/css">
td {border:none;}
</style>
</head>
<body>
<table width="800" border="1">
<tr>
<td align="center">Number To Send<br /><input type="text" id="numSend" size="40%" style="border:2px solid black;"></td>
<td align="center">Number Returned<br /><input type="text" id="numReturn" size="40%" readonly></td>
</tr>
<tr><td align="center" colspan="4"><input type="button" value="Get Number" id="getNum" /></td></tr>
</table>
<script>
$(document).ready(function () {
$('#getNum').click(function () {
var $numSent = $('#numSend').val();
var json = {"number":$numSent};
$.post("convertNum.php", {"json": json}).done(function (data)
{
alert(data);
}
);
});
});
</script>
</body>
</html>
Here is the response I get if I submit the number '2':
4
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style type="text/css">
td {border:none;}
</style>
</head>
<body>
<table width="800" border="1">
<tr>
<td align="center">Number To Send<br /><input type="text" id="numSend" size="40%" style="border:2px solid black;"></td>
<td align="center">Number Returned<br /><input type="text" id="numReturn" size="40%" readonly></td>
</tr>
<tr><td align="center" colspan="4"><input type="button" value="Get Number" id="getNum" /></td></tr>
</table>
<script>
$(document).ready(function () {
$('#getNum').click(function () {
var $numSent = $('#numSend').val();
var json = {"number":$numSent};
$.post("convertNum.php", {"json": json}).done(function (data)
{
alert(data);
}
);
});
});
</script>
</body>
</html>
Obviously I'm only interested in receiving and using the number '4', hence my question: What is the best way to specify exactly what data I want returned?
Some thoughts I've had:
wrapping all my HTML inside a if statement (i.e., if $num isset, do NOT output html; else output HTML) but then I'm echoing HTML, and I'd rather not do that.
Setting up a separate PHP script to receive my AJAX call: That was what I did originally, and it works just fine. However, I am interested in keeping everything inside one file, and wanted to explore possible ways of doing so.
I'm sure there is an elegant way to do this. Thanks for any suggestions!

The elegant way would be to have a separate(!) PHP file that will only output the number times 2 part of your current PHP. Then you generate an AJAX request from your current PHP to the new separate PHP.

I believe this post answers one aspect of what you are seeing - the echoing of the entire page in your alert box.
Next, here are some good posts for getting the basics of AJAX:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1

You could add die(); after you echo the number if you really want to keep it on the same page. This will terminate the execution of the script. Don't forget to add brackets around the if statement:
if (isset($num)) {
echo $num['number'] * 2;
die();
}
It is, however, not the most elegant solution.

NOTE *The better approach is to keep things like this in a separate file, makes it easier to read and easier to understand, especially if you use a good naming conversion.
It is a bad procedural approach but here I go :) :
<?php
$num = $_POST['json'];
if (isset($num))
echo ($num['number'] * 2);
die();
?>
or better yet:
<?php
$num = $_POST['json'];
if (isset($num))
die($num['number'] * 2); //In case of error you could put them in brackets
?>
PS
As alternative to die(); you could use exit();, they both do pretty much the same: terminating further execution

I don't know how efficient this is but you can do something like:
<?php
/*convertNum.php*/
$num = isset($_POST['json']) ? $_POST['json'] : NULL; //you have errors in this line
if (!is_null($num)){
echo $num['number'] * 2;
exit(); //exit from script
}
?>

Related

How to store a multiple row query in a session var and use it with foreach

*I'm trying to carry my SQL query from PHP Controller file to my PHP View file. I've been cudgeling my brain for hours and hours. I've discovered that my major problem is that I don't know to carry data from PHP to another document that didn't start the REQUEST petition. The PHP Controller code (request) comes from a submit of other document (votar1.php).
I know to do it only if I pressed a button (type button) with onclick, but no idea when the code is triggered by submit button. Embbeding javascript on php doesn't works for me in any way.*
↓↓↓↓↓↓↓↓↓ (Focus on this better). ↓↓↓↓↓↓↓↓↓↓↓↓
Buuut, I think I'm close to the solution now, I've been experimenting with storing a query in a SESSION, so I would prefer this solution. It seems simple when the query returns you only one row, but when it returns more than one row, I don't know how to deal with it. So I need to know:
How to store multiple row query in a SESSION
How to use it (↑) to show data in a table using foreach.
I would be very thankful if you guide me a bit about these 2 things mentioned above ↑ (please, don't forget about the second one, because I don't know how to deal with that).
Controller(controladorPartidos.php):
include 'conexionBBDD.php';
session_start();
----other code----
if (passwordMatch($nif, $password) && (!haVotado($nif))) { //si la contraseña es correcta y no ha votado...
$consulta = "SELECT LOGO, NOMBRE FROM partido";
$resultado = $conexion->query($consulta);
while ($rows = mysqli_fetch_assoc($resultado)) {
$query=array_push($_SESSION['query'], $rows);
}
header('Location: Vista/votar2.php');
}
PHP View (votar2.php):
<?php
include_once 'header.html';
session_start();
$query = $_SESSION['query'];
?>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="javascript.js"></script>
<title></title>
</head>
<body>
<div id="caja">
<form action="../controladorPartidos.php" name="formVotar2" id="formVotar2" method="post">
<table>
<?php foreach ($query as $partido) { ?>
<tr>
<td style="text-align: center"><img src="<?php echo $partido[0] ?>"/></td>
<td><input type="radio" name="partido" value="<?php echo $partido[1] ?>"><?php echo $partido[1] ?></td>
<?php }; ?>
</tr>
</table>
<div style="width:75px; margin-right:auto; margin-left:auto;">
<br/>
<input id="botonVotar" type="submit" name="submit" onClick="submitVoto()" value="Votar"/>
<br/>
</div>
</form>
</div>
</body>
</html>
I hope you can help me! Thank you in advance for your time :)

Refreshing a textbox every couple of seconds with mysql query?

I have this textbox in my code that everytime this page is loaded/refreshed, its content is filled with a query result. But since refreshing manually is not an option in my case, how can I do this automatically (I only want to refresh the textbox)? I've read about using AJAX, and I've been reading about it, but to be honest I don't quite get how to make it work, could someone explain me and dumb it down? Isn't there any easier way to refresh the textbox with the query content?
EDIT: Okay, I think I understood the basics of AJAX, the function is now refreshing the textbox every second, but there's a small problem. It messed up my table big time. I've modified the HTML code in hope someone can tell me what I did wrong. I'm thinking I shouldn't be including a div inside a table?
Here's how my table looked like and how it looks like after this little update
<?php
include '../Login/db_login.php';
session_start();
$sql = "SELECT Contador FROM senhas2 WHERE ID=1";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$nome = $row['Contador']
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Página de administração - A</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
setInterval(function(){
$('#refreshtb').load('bt1admin.php');
}, 1000)
</script>
</head>
<body>
<form action="" id="atender" method="POST">
<table border="1">
<tr>
<td>Clientes em espera:</td>
<td><div id="refreshtb"><input id="refreshtb" type="text" value="<?php echo "$nome";?>"readonly></div></td>
</tr>
<tr>
<td>Selecionar posto de atendimento:</td>
<td><select name="posto"><option value="n1" selected>1</option><option value="n2">2</option><option value="n3">3</option><option value="n4">4</option><option value="n5">5</option><option value="n6">6</option></select>
</tr>
<tr>
<td colspan="2"><input type="submit" form="atender" name="atender" value="Atender Cliente Seguinte"></td>
</tr>
</table>
</form>
</body>
</html>
You cannot change the content of a page using PHP. You'll need to use a front-end language, such as Javascript. Javascript is able to change your page's content, even after it is loaded. In order to update your page's content every X seconds, you'll want to use Javascript's setInterval() function to run a function every X seconds. This function would use AJAX to send a request to your website and gather some more data, and then update your textbox to contain this new data. You might find this Stackoverflow question helpful: How does AJAX work?
EDIT: To clear up some confusion in our comment discussion and in response to your edits, I've modified your code a little bit. Try this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Página de administração - A</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
setInterval(function(){
$.ajax('bt1admin.php').done(function(data) {
$("#refreshtb").val(data);
})
}, 1000);
</script>
</head>
<body>
<form action="" id="atender" method="POST">
<table border="1">
<tr>
<td>Clientes em espera:</td>
<td><div><input id="refreshtb" type="text" value="<?php echo "$nome";?>"readonly></div></td>
</tr>
<tr>
<td>Selecionar posto de atendimento:</td>
<td><select name="posto"><option value="n1" selected>1</option><option value="n2">2</option><option value="n3">3</option><option value="n4">4</option><option value="n5">5</option><option value="n6">6</option></select>
</tr>
<tr>
<td colspan="2"><input type="submit" form="atender" name="atender" value="Atender Cliente Seguinte"></td>
</tr>
</table>
</form>
</body>
</html>
What I did:
First of all, you had duplicate #refreshtb elements, so I removed one of them.
You were also using the .load() method in JQuery. This does not update the value of an HTML input. Instead, it just replaces the child HTML, which is not what you want. I updated your script to now update the value of the #refreshtb input element.
Tested and it seems to work fine for me. If you're still getting that weird table issue after this or for some reason the field isn't being updated properly, I suspect it's an issue with your bt1admin.php page. Make sure that page isn't outputting the entire table, and instead just the value you want to go into the text box.

How to write a variable value in a text file with php

I have a problem with a php code. It's a simple web page hosted on my computer with two buttons and a text box. When I click + or - button the number in text box increase or decrease. Everything works as is suppose to, except when I want to write the textBox.value into a text file using php code. The result is something like "value = textBox.value" when it should be something like "value = 0". Thank you.
The code is below:
<!DOCTYPE html>
<html>
<body>
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input id="textBox" type="text" value="0" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<script>
decreaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) -1
}
increaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) + 1
}
</script>
<?php
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
$txt = "value = ";
fwrite($myfile, $txt);
$v = textBox.value;
fwrite($myfile, $v);
fclose($myfile);
?>
</body>
</html>
Brief Explanation:
You are trying to combine two separate languages as if both were client-side "as needed" scripting languages.
Javascript is client-side, and as such, will run based on event listeners or any other defined parameters. PHP is server-side, and as such, will run when the file is parsed. This means that your PHP is already processed and out of the picture by the time the Javascript even comes into the picture.
What is happening in your script presently:
The file is parsed, PHP is identified, and runs first. Immediately upon running, the file gets written to. PHP defaults to the text-value of "textBox.value" as it is not an actual variable (which would be preceded with $ if it were). In all honesty, it should be returning an error that "textBox.value" means nothing, essentially (PHP is not strict, so it makes a lot of assumptions). It's not, however, because it's assuming you are referencing a Constant. After the PHP is processed, the DOM is processed and sent to the browser. The PHP does not even exist at this point and has been stripped away from the DOM (rightfully so - you'd NEVER want PHP to be visible to a client).
What to do:
You cannot run this PHP snippet every time you want to increment/decrement the value with the PHP being inside of the same file (at least not without a form submit, or something to "catch" the request -- my response will be based on the fact that you simply want it to write when clicking, instead of submitting a form every time). You must change your code. One thing I'd suggest is placing the PHP inside of its own file. Then, upon incrementing/decrementing the value, you use AJAX to actually hit that file (thus triggering a file write).
Example:
index.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input id="textBox" type="text" value="0" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<script>
$("#decreaseNumber").on("click", function() {
$("#textBox").val(parseInt($("#textBox").val()) -1);
writeToFile($("#textBox").val());
})
$("#increaseNumber").on("click", function() {
$("#textBox").val(parseInt($("#textBox").val()) +1);
writeToFile($("#textBox").val());
})
function writeToFile(value){
$.ajax({
url: 'write.php?v=' + value,
type: 'GET',
dataType: 'json',
success: function(ret){
alert('Success!');
},
error: function(ret){
alert('Error!');
}
});
}
</script>
</body>
</html>
write.php:
<?php
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
$txt = "value = " . $_GET['v'];
fwrite($myfile, $txt);
fclose($myfile);
?>
Note the Changes:
I am using JQuery in my example. I apologize if you wanted strictly native Javascript.
Also please note, I changed the PHP. You had two writes, which was unnecessary and would take more time. File Input/Output is costly, and should be used minimally. In fact, in this example, I'd personally have just written to a database. However, you did not ask for a separate solution, so I simply provided an example similar to what you had written.
Random Thoughts
You can use decrement/increment instead of what you're doing as well. Like so:
<script>
decreaseNumber.onclick = function() {
textBox.value--;
alert(textBox.value);
}
increaseNumber.onclick = function() {
textBox.value++;
alert(textBox.value);
}
</script>
Here, you are getting value in javascript easily and in php if you want to get values then you have to post the form or send through parameters in URL.Here are some ways to passing data in php :
- Passing PHP variables with $_POST
- Passing PHP variables in links with $_GET
- Passing PHP variables without POST or GET | $_SESSION
- Passing PHP variables arrays from one page to another
- Passing PHP COOKIE variables
<!DOCTYPE html>
<html>
<body>
<form action="" method="post">
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input id="textBox" type="text" value="0" name="textBox" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input type="submit" name="submit" value="Write To File">
</form>
<script>
decreaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) -1
}
increaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) + 1
}
</script>
<?php
if(isset($_POST['submit'])){
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
$txt = "value = ";
fwrite($myfile, $txt);
$v = $_POST['textBox'];
fwrite($myfile, $v);
fclose($myfile);
}
?>
</body>
</html>
To make php do this, you would need to submit the form. You can either do this via ajax or a normal post submit.
I've modified your code to work on a basic post submit.
Please read up on what a post method is.
I've had to make tiny changes in your HTML as well, and php.
I've commented them for ease.
You cannot combine two different languages to work together, not in this case at least. You could assign values from PHP to JAVASCRIPT variables, but not the other way around.
PHP has the ability to read values of input fields as long as they are submitted.
If you would like for PHP to write to the file every time the number is increased or decreased, you will have to do an ajax request to a php script on those particular events to get this done.(onClick)
<!DOCTYPE html>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$myfile = fopen("/home/pi/test/test.txt", "w") or die("Unable to open file!");
//You dont need to write twice, you can use both values in one single variable and write once
//added whitespce \r\n for line break
$v = $_POST['textbox'];
$txt = "value = $v";
fwrite($myfile, $txt);
fclose($myfile);
echo "written to file";
}
?>
<html>
<body>
<!--Made this a form so it can be submit to php-->
<!--Read about POST method-->
<form method="POST" action="">
<input id="increaseNumber" type="button" value="+" style="font-size:24pt; width: 50px; height: 50px;"><br>
<!-- Add the name attribute so php can read the value -->
<input name ='textbox' id="textBox" type="text" value="0" style="font-size:24pt; width: 40px; height: 40px;">
<label style="font-size:24pt;">℃</label><br>
<input id="decreaseNumber" type="button" value="-" style="font-size:24pt; width: 50px; height: 50px;"><br>
<input type='submit' value='Submit'/>
</form>
<script>
decreaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) -1
}
increaseNumber.onclick = function() {
textBox.value = parseInt(textBox.value) + 1
}
</script>
</body>
</html>
LINKS THAT WILL BE USEFUL TO YOU
$_POST - http://php.net/manual/en/reserved.variables.post.php
PHP FORM HANDLING - http://www.w3schools.com/php/php_forms.asp
AJAX REQUESTS - http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
You're mixing things up and it won't work like this.
First off, enclose your input boxes inside a <form> pointing to the PHP file that will handle the increase / decrease function, and write it to the test.txt file:
<form id="handler" method="post" action="handler.php">
<!-- Your input elements here -->
</form>
Also, you'll need to add the attribute name to your textBox element, you may call it nvalue, in example.
Second, your click event listeners are invalid. The correct to set them is:
document.getElementById("decreaseNumber").addEventListener("click", function() {
document.getElementById("textBox.value").value--;
document.getElementById("handler").submit();
});
The same goes for increaseeNumber
Third, put your php in your new handler.php file. Get the increase/decrease value with $_POST['nvalue']. Write this value to the file.
Note: You may also use AJAX for this, but it's a little more advanced and you'll also probably need a JS library like jQuery.
Note 2: You can redirect back from handler.php to your form page after updating test.txt file by using php header() function.
Note 3: You can make your <input id="textBox"> to show the current value in the file test.txt by loading it above and echoing value = "<?php echo $nvalue; ?>", of course, $nvalue is gotten using fread() or similar.

Get Image file tag values with Ajax (jquery version) and show the result as the real-time previewer

I believed it is possible for me to simplify me previous project Click here!
to build an upload previewer so the editor can use it to see what he puts before upload to the server. (just a simple previewer without loading or saving to the databse with php script).
I use the same short Ajax and html form scripts and revise the jquery selector a little bit.
Now it is fine for me to see the text input. Everytime I insert new word the text area will show exactly what I do. However, something seemes to go astray with the image part. I try to use image selector (attr"src") to get the path and hope it could get the photo and show in the tag I build. However I could only get the values as path root such as (C:/images/img1.png) insead the whole picture. The following are scripts with mentioned issues:
<script language="JavaScript">
$(document).ready(function() {
$("form").keyup( function() {
var qtyVal = $('.qty').val();
var contentVal = $('.content').val();
var imageVal = $('input:file').val();
// get
$.ajax({
type: 'POST',
url: 'result1.php',
data: { qty : qtyVal,
content : contentVal,
image : imageVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('total').text());
$('#result1').html($(data).find('content').text());
//I bleieved something goes wrong with the following script!
$('#test').attr("src").html($(data).find('upload').text());
}
});
return false;
});
});
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#news").hide();
$("#flip").click(function(){
$("#news").slideToggle("slow");
});
});
</script>
</head>
<body>
<div id="flip">previewer</div>
<div id="news" class="news">
<form method="post" enctype="multipart/form-data">
<table cellspacing="4" cellpadding="2">
<tr><th>title</th><th>content</th></tr>
<tr>
<td>
<div id="result2" class="box" style="width:300px; height:350px;">
//image block where I want to show the image by creating an imge tag>
<img src="#" class="test" /></div></td>
<td><div id="result" class="box" style="height:100px;"></div>
<div id="result1" class="box" style="height:250px; overflow:hidden;"></div>
</td></tr>
</div>
<td bgcolor="#CCCCCC"><input type="text" class="qty" name="qty" ></td>
<td bgcolor="#CCCCCC"><textarea type="text" class="content" name="content" ></textarea></td>
<td><input type="file" class="image" name="image"/></td>
<td bgcolor="#CCCCCC"><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr><br />
<tr><td colspan="5" align="center">div></td></tr>
</form>
</table>
I also include my short php script as the XML file for above Ajax:
<?php
// XML
header("Content-Type:text/html; charset=utf-8");
// GET the text and image values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
$content = (isset($_POST["content"]) ) ? $_POST["content"] : $_GET["content"];
$image = (isset($_POST["image"]) ) ? $_POST["image"] : $_GET["image"];
echo "<?xml version=\"1.0\" ?>";
echo "<caculation>";
echo "<total>" . "$qty" . "</total>";
// right now I can get the path back to the html page.
echo "<upload>"."$image"."</upload>";
echo "<content>"."$content"."</content>";
echo "</caculation>";
?>
I understand experts on SO had built powerful and professional Ajax previewer with multiple function. However, as an beginner and learner I am quite satisfied with my rookie and backward script. Hope someone can help with the bugs. Any possible advice or suggestion is welcome!
If you are using attr('src') then it will return the path only. If you want the whole image then set the response as image in the server for the get request or use an base64 string image and use data uri scheme to show the image

Assistance with FORM-SUBMIT & "?" removal from URL

I was wondering how one would go about sending whatever the user types in text box; to the end of the <form action=. If one does not have access to the websites code source, how would one go about this?
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
a:link {color:#687BC6;}
a:visited {color:#0F0;}
a:hover {color:#000;}
a:active {color:#0A0;}
</style>
</head>
<body>
<form name="form1" method="get" action="http://www.blah.com/right-now/" target="_blank">
<table border="0" cellpadding="2" cellspacing="0">
<tr><td>ZC:</td>
<td><input name="fld-zip" type="text" maxlength="7" size="15"></td></tr>
<tr><td> </td>
<td><input type="submit" name=Submit value="Submit this"></td></tr>
</table>
</form>
</body>
</html>
Pretty much asking how you can add what you put in text box to the end of URL /??? when you click the submit button.
So it shows:
Textbox - "11722"
URL = http://www.blah.com/right-now/11722
Is there a way to do this via css/html/php/js?
Every time I click the SUBMIT button, it just adds a '?' at the end and it gets cut off.
Well,m just giving it a try...i dunno whether it'll work or not.. do one thing,use two files..one to get the zip code..
=>in file 1,use a form.. after submitting,send the zip code to a dummy file(second file) i.e.,action="dummy.php"
=>in dummy file assign the zip code to a variable '$a'
$a=$_GET['zip'];
now use javascript
<script>
function a()
{
newwindow=open("http://www.blah.com/rightnow/'$a'",window,"height=900,width=1100");
}
</script>
I would do something like this at the top of the page.
<?php
if (!(empty($_GET['fld-zip']))){ //check if the var is empty
$url = "http://www.blah.com/right-now/";
$page = $_GET['fld-zip'];
header("location:$url . $page"); //if its all good then redirect to the correct page
}
?>
This could probably be done a bunch of different ways but should work.
The ? is there because the form is submitted using get it wont go away and shouldnt. Do some reading on GET and POST in HTML forms.
if you use GET, the link should look something like "http://www.blah.com/right-now?variable1=11722&variable2=11733. The question mark is at the beginning of the variables. How does it get cut off?
If you're using http://www.blah.com/right-now/ as the action, make sure that http://www.blah.com/right-now/index.php has the logic.
As your basically wanting to just open a new window with the value of what's entered in the text box concatenated on to a url;
Change your form slightly, use a button instead of a submit, and with the use of jquery(cleaner imo) and a simple js function to put it altogether & trigger it from the forms onClick="doForm()".
<script>
function doForm(){
var param = $("#fld-zip").val();
window.open ("http://www.blah.com/right-now/" + param,"openwindow");
}
</script>
<form name="form1" method="get" action="" target="_blank">
ZC:<input name="fld-zip" id="fld-zip" type="text" maxlength="7" size="15">
<input type="button" name="Submit" onClick="doForm()" value="Submit this">
</form>
Add a script like this
function formSubmit(){
document.getElementById('frm1').setAttribute('action', "http://www.google.com/right-now/" + document.form1["fld-zip"].value)
document.form1["fld-zip"].value = '';
return true;
}
then add onsubmit event to your form
<form id="frm1" name="form1" method="get" action="http://www.blah.com/right-now/" target="_blank" onsubmit="return formSubmit()">
Working example http://jsfiddle.net/FtRKp/4/

Categories