Clearing input text field on enter or search button? - php

I've got a form that lets my user search. I'm using jQuery to append the search results lower in the page without reloading the page. So, I've got this:
isbn.php:
<form method="post" action="ajax.php" name="searchISBN" id="searchForm">
<input type="text" name="isbn" placeholder="Search..." />
<input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" />
</form>
The problem is, I need that input text search field to clear when the user hits the Search button or hits enter. Both hitting enter and the Search button execute the search, so it must clear when either action happens.
But, I'm absolutely stumped.
Any help will be greatly appreciated!!
Edit:
I've tried what Treffynnon suggested. The problem there is, I've disabled the search button from actually loading ajax.php. So, when I use that code, it stops the page from staying on isbn.php and it loads ajax.php . This is the code that loads the search results.
isbn.php:
<script>
// attach a submit handler to the form
$("#searchForm").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get some values from elements on the page:
var $form = $( this ),
term = $form.find( 'input[name="isbn"]' ).val(),
//term = "isbn",
url = $form.attr( 'action' );
$.post( url, { doSearch: "Search", isbn: term } ,
function( data ) {
var content = $( data );
$( "#result" ).append( content );
}
);
});
</script>

$('#searchForm').submit(function(){
// do search loading code here and then
$('input[name="isbn"]').val('');
});
Try this based on your update:
// attach a submit handler to the form
$("#searchForm").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get some values from elements on the page:
var $form = $( this ),
$term_input = $form.find('input[name="isbn"]'),
term = $term_input.val(),
//term = "isbn",
url = $form.attr( 'action' );
$.post( url, { doSearch: "Search", isbn: term } ,
function( data ) {
var content = $( data );
$( "#result" ).append( content );
}
);
$term_input.val('');
});

Add a hidden variable to achieve this as follows:
<form method="post" action="ajax.php" name="searchISBN" id="searchForm">
<input type="text" name="isbn_holder" placeholder="Search..." />
<input type="hidden" name="isbn"/>
<input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" />
</form>
$('#searchForm').submit(function(){
$('input[name="isbn"]').val($('input[name="isbn_holder"]').val());
$('input[name="isbn_holder"]').val('');
});

Related

How do I send input to url using form without Php? (form action)

I want to send this query (EA452401760IN) to https://track.aftership.com/india-post/.
After a successful submission by Form the URL will be
https://track.aftership.com/india-post/EA452401760IN
Form
<form method="POST" action="https://track.aftership.com/india-post/" target="_blank"> <input type="text" value="EA452401760IN"></input><button type="submit"> submitc</button></form>
Do I need a PHP file for this?
If yes, how do I write a php file for this problem.
Pure Javascript approach with Jquery
<input type="text" id="trackingNumber" value="EA452401760IN"></input>
<button onclick="go()">Track</button>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script>
$( "button" ).on( "click", function( event ) {
window.location.href = "https://track.aftership.com/india-post/" + $('#trackingNumber').val();
});
</script>
JSBIN: https://jsbin.com/fuqovocoza/edit?html,console,output
<?php if(($_SERVER["REQUEST_METHOD"] == "POST")){
//Check that the form has been posted if it has been then redirect to the correct page
header ('Location: https://track.aftership.com/india-post/' . $_POST['query']);
}
else
{
if the form has not been submitted display the form
<form method="POST" action="https://track.aftership.com/india-post/" target="_blank"> <input type="text" name="query" value="EA452401760IN"></input><button type="submit"> submitc</button></form>
Note that I have changed the name of the input field to query.

sending form data to php using ajax

I Have an requirement to pass form data to php using ajax and implement it in php to calculate the sum , division and other arithmetic methods I am a new to ajax calls trying to learn but getting many doubts....
It would be great help if some one helps me out with this
index.html
<script type="text/javascript">
$(document).ready(function(){
$("#submit_btn").click(function() {
$.ajax({
url: 'count.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('data');
}
})
});
</script>
</head>
<form name="contact" id="form" method="post" action="">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
In count.php i want to implement
<?php
$FNO = ($_POST['FNO']);
$SNO=($_post['SNO']);
$output=$FNO+$SNO;
echo $output;
?>
(i want to display output in count.php page not in the first page index.html)
Thanks for your help in advance.
You can use a simple .post with AJAX. Take a look at the following code to be able to acheive this:
$('#form').submit(function() {
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("count.php",$(this).serialize(),function(data){
alert(data); //check to show that the calculation was successful
});
return false; // return false to stop the page submitting. You could have the form action set to the same PHP page so if people dont have JS on they can still use the form
});
This sends all of your form variables to count.php in a serialized array. This code works if you want to display your results on the index.html.
I saw at the very bottom of your question that you want to show the count on count.php. Well you probably know that you can simply put count.php into your form action page and this wouldn't require AJAX. If you really want to use jQuery to submit your form you can do the following but you'll need to specify a value in the action field of your form:
$("#submit_btn").click(function() {
$("#form").submit();
});
I have modified your PHP code as you made some mistakes there. For the javscript code, i have written completely new code for you.
Index.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<form name="contact" id="contactForm" method="post" action="count.php">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
<label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
<!-- The following div will use to display data from server -->
<div id="result"></div>
</body>
<script>
/* attach a submit handler to the form */
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
//Get the first value
value1 = $form.find( 'input[name="SNO"]' ).val(),
//get second value
value2 = $form.find( 'input[name="FNO"]' ).val(),
//get the url. action="count.php"
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { SNO: value1, FNO: value2 } );
/* Put the results in a div */
posting.done(function( data ) {
$( "#result" ).empty().append( data );
});
});
</script>
</html>
count.php
<?php
$FNO = $_POST['FNO'];
$SNO= $_POST['SNO'];
$output = $FNO + $SNO;
echo $output;
?>
There are a few things wrong with your code; from details to actual errors.
If we take a look at the Javascript then it just does not work. You use the variable data without ever setting it. You need to open the browser's Javascript console to see errors. Google it.
Also, the javascript is more complicated than is necessary. Ajax requests are kind-of special, whereas in this example you just need to set two POST variables. The jQuery.post() method will do that for you with less code:
<script type="text/javascript">
$(document).ready(function(){
$("#form").on("submit", function () {
$.post("/count.php", $(this).serialize(), function (data) {
alert(data);
}, "text");
return false;
});
});
</script>
As for the HTML, it is okay, but I would suggest that naming (i.e. name="") the input fields using actual and simple words, as opposed to abbreviations, will serve you better in the long run.
<form method="post" action="/count.php" id="form">
<label for="number1">Enter First no:</label>
<input type="number" name="number1" id="number1">
<label for="number2">Enter Second no:</label>
<input type="number" name="number2" id="number2">
<input type="submit" value="Calculate">
</form>
The PHP, as with the Javascript, just does not work. PHP, like most programming languages, are very picky about variables names. In other words, $_POST and $_post are not the same variable! In PHP you need to use $_POST to access POST variables.
Also, you should never trust data that you have no control over, which basically means anything that comes from the outside. Your PHP code, while it probably would not do much harm (aside from showing where the file is located on the file system, if errors are enabled), should sanitize and validate the POST variables. This can be done using the filter_input function.
<?php
$number1 = filter_input(INPUT_POST, 'number1', FILTER_SANITIZE_NUMBER_INT);
$number2 = filter_input(INPUT_POST, 'number2', FILTER_SANITIZE_NUMBER_INT);
if ( ! ctype_digit($number1) || ! ctype_digit($number2)) {
echo 'Error';
} else {
echo ($number1 + $number2);
}
Overall, I would say that you need to be more careful about how you write your code. Small errors, such as in your code, can cause everything to collapse. Figure out how to detect errors (in jQuery you need to use a console, in PHP you need to turn on error messages, and in HTML you need to use a validator).
You can do like below to pass form data in ajax call.
var formData = $('#client-form').serialize();
$.ajax({
url: 'www.xyz.com/index.php?' + formData,
type: 'POST',
data:{
},
success: function(data){},
error: function(data){},
})

JQuery Refresh DIV with new URL from form

I have a form with one text box that is part of a div tag. I want it to change the contents of that div tag to another page based on the contents of a textbox in a php GET request.
for example if you type hell into the textbox it will load goto.php?location=hell into the div.
so far this is the code i have below, and due to it being my first time with jquery sucks more than a hoover vacuum cleaner.
<div id="city"></div>
<form name="goto" action="/">
<input type="text" id="city">
<input type="submit" name="submit" class="button" id="submit_btn" value="New City" />
</form>
<script>
/* attach a submit handler to the form */
$("#goto").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
city = $form.find( 'input[name="city"]' ).val(),
/* Send the data using post and put the results in a div */
$('currentwxdiv').load('http://www.jquerynoob.bomb/hell.php?location=' + city);
});
</script>
Currently instead up updating the contents of the div it reloads the entire page in the browser and then appends it with ?submit=New+City
UPDATE This is what I have now and its still doing the full page refresh with the appended ?submit=New+City
<script>
/* attach a submit handler to the form */
$$('form[name="changewx"]').submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
city = $('#city').val()
/* Send the data using post and put the results in a div */
$('#currentwxdiv').load('http://api.mesodiscussion.com/?location=' + city);
});
</script>
You have created your form like this:
<form name="goto" action="/">
But the selector only matches the element with an id goto. So it should be:
$('form[name="goto"]').submit(function(event) {
You also made a mistake the other way around:
$form.find( 'input[name="city"]' ).val()
Should be:
$('#city').val()
Another thing:
$('currentwxdiv') // this matches a tag called currentwxdiv
Should be:
$('.currentwxdiv') // for element with class currentwxdiv, or $('#currentwxdiv') to match based on id
And instead of doing e.stopPropagation(); you should do return false; at the end of the function.

jQuery / AJAX Appending search results - how do I clear only one?

I've coded some jquery & AJAX to call a PHP function I made that goes and gets some API data and brings it without refreshing the page. It appends, so you can have multiple searches without losing results.
What I need to do now is, I want to give the user the ability to change his mind on any one of the results. Maybe a little "X" at the end of each row. They click the "X" and that particular result is gone.
I've googled this, but I don't know what I'm looking for. Send me in the right direction, please?
Here's what I've got, so you know what I'm looking for:
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<form method="post" action="ajax.php" id="searchForm">
<input type="text" name="isbn" placeholder="Search..." />
<input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" />
</form>
<form name="buyback" method="post" action="isbn.php">
<table id="result" class="myaccount" border=0 cellspacing=5 cellpadding=4>
<tr><td>
<strong>ISBN:</strong>
</td><td>
<strong>Price:</strong>
</td>{if $userlevel == 5}<td>
<strong>Full FCB Price</strong>
</td>{/if}
</tr>
</table>
<input name="doBuy" type="submit" value="Buy"><br>
</form>
<script>
// attach a submit handler to the form
$("#searchForm").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get some values from elements on the page:
var $form = $( this ),
term = $form.find( 'input[name="isbn"]' ).val(),
//term = "isbn",
url = $form.attr( 'action' );
$.post( url, { doSearch: "Search", isbn: term } ,
function( data ) {
var content = $( data );
$( "#result" ).append( content );
}
);
});
</script>
EDIT:
Yes, it just returns data in this format:
<tr><td>
{$isbn}
<INPUT TYPE=hidden NAME="buy_isbn" VALUE="{$isbn}">
</td><td>
{$userPrice}
<INPUT TYPE=hidden NAME="buy_price" VALUE="{$userPrice}">
</td></tr>
This really depends on what type of html is returned by the ajax call. But you could wire up a .live() event that removes whatever you need to get rid of.
$('.removeItem').live('click', function(e) {
// remove whatever you want. maybe the previous element?
$(this).closest('tr').remove();
});
// clicking that link will remove everything returned by the ajax.php call
var content = $(data);
content.append("<a class='removeItem'>X</a>");
$("#result").append(content);
or you could just add the anchor into the results that are generated by your ajax.php file.
EDIT:
You could just use the live event and modify your html like this:
<tr><td>
{$isbn}
<INPUT TYPE=hidden NAME="buy_isbn" VALUE="{$isbn}">
</td><td>
{$userPrice}
<INPUT TYPE=hidden NAME="buy_price" VALUE="{$userPrice}">
</td><td>
X
</td></tr>

jQuery & AJAX -- populating a list?

I've made jQuery & AJAX script that uses a PHP function to bring back results from an API. That part works great, but everytime I search for a new book, it removes the previous search results.
I want to give it a book ID, search, get results, and continue doing that. Every time I click "search", I want to populate a list with more books.
This code keeps removing my previous book and replacing it with the new book I've searched for.
Any ideas?
isbn.php:
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<form method="post" action="ajax.php" id="searchForm">
<input type="text" name="isbn" placeholder="Search..." />
<input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" />
</form>
<div id="result"></div>
{literal}
<script>
// attach a submit handler to the form
$("#searchForm").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get some values from elements on the page:
var $form = $( this ),
term = $form.find( 'input[name="isbn"]' ).val(),
//term = "isbn",
url = $form.attr( 'action' );
$.post( url, { doSearch: "Search", isbn: term } ,
function( data ) {
var content = $( data );
$( "#result" ).html( content );
}
);
});
</script>
ajax.php does the API call and prints the results inside of isbn.php.
if you are just trying to append the content then:
$( "#result" ).append( content );
if you want the new results to go to the top of the results div then
$( "#result" ).prepend( content );
using $( "#result" ).html( content ); tells jQuery to replace the entirety of any HTML inside #result with the new content
The problem is in your ajax success function you are rewriting the entire content of the #result block. If you changed .html to .append this should just make it additive rather than replacing.

Categories