Multi Scenario Form Action (Background, Multiple Actions, Timer) - javascript

I have tried using methods that may work for one scenario or another in AJAX, Javascript, JQuery and PHP, but I have not found a way to achieve the correct results for my scenarios.
I have a search box text input field as :
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
There are three scenarios in which different actions need to occur:
On page load, send the input to search-api.php as POST every 5 seconds in the background, and get results back from the action and set the response equal to $url. (Must not only show response for first submit, but also for all changes in input when updated every 5 seconds).
When enter button is pressed, send the input as GET to https://externalaction.com/search in foreground.
When button <input class="button default" name="BtnX" type="submit" value="Search"> is pressed, send the input as GET to https://externalaction.com/search in foreground.
I know this is complicated but I have yet to find a solution that works for all three scenarios without interfering with each other, and no one online seems to have any information or questions quite like this situation.
Thank you to anyone who has any help, tips, or answers / code!

This doesn't seem too complicated, although I'm not sure why you'd want to send search queries every 5 seconds instead of on keypress? In any case it should just be using $.post() and setTimeout.
<form action="https://externalaction.com/search" method="get">
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input class="button default" name="BtnX" type="submit" value="Search">
</form>
<div id="results"></div>
<script>
$(function() {
search();
});
function search() {
$.post(
"search-api.php",
{ field: $('#field').val() },
function (data) {
$('#results').html(data); // or whatever format you want data in
}
);
setTimeout(search, 5000);
}
</script>
If you're interested in using keypress instead of every 5 seconds, it would be something like this for the JS:
<script>
$(function() {
$('#field').on('keyup change', 'search');
});
function search() {
$.post(
"search-api.php",
{ field: $('#field').val() },
function (data) {
$('#results').html(data); // or whatever format you want data in
}
);
}
</script>
Although in this case you don't need a named function, you could just make the search() function the keypress callback.
You also mentioned wanting to set the AJAX response to $url, however that looks like a PHP variable, so you wouldn't be able to modify that if it's in the page with the form unless you reloaded it. That's easy enough to do if you wanted to programmatically do a redirect, but would get pretty tricky and into weird loops. So it would be better to know what $url is being used for in the page, and then use JS to replace it with the value from the callback the same way I'm replacing the HTML of the results div in my current example.
The search form field will submit automatically on an 'enter' keypress as long as it has focus (i.e. after someone is finished typing in it and hits 'enter'), but if you want to send results whenever enter is pressed regardless of which input has focus this answer will help.
As an aside, typically you don't want to recursively keep searching with a timeout without some kind of end condition which clears the timeout, as in some cases it can lead to memory issues.

first of all you should search input is a form and need form tag even if it's only one input. lets consider it like this:
as you set set button type to submit. the 2 and 3 options would work.
<form id="search-form" action="https://externalaction.com/search" method="GET">
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input class="button default" name="BtnX" type="submit" value="Search">
</form>
second of all in case if in some situations (really rare) some browsers didn't work properly with type="submit" for enter button you should use jQuery like this one:
$(function() {
$("#search-form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('#search-form button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
for autocomplete search you can use many exist libraries or write it yourself I recommend to read this article for an example:
http://ianlunn.co.uk/articles/ajax-search-suggest-wearehunted/
actually if you use a standard form element the only thing you are looking for is just a autocomplete search input which i believe users used to see result by typing each word instead every 5 second. but its up to you.
Edited according to your last comment:
if you have a single action for search you should at least use two different view.
to use autocomplete feature you should use ajax and if you want to have only one action or page just send an extra parameter and make a partial-view which echo result back in Json instead of a complete view which contains header and footer and ...

Function searchData() handle the AJAX request. setInterval(function(){searchData()}, 5000) section handle request search content every 5 second. If click on Enter key, then that request handle on keydown event, finally click function handle the request come through the search button.
search.php
<!--- Search field and button -->
<input id="field" name="q" maxlength="2048" autocomplete="off" title="Search" type="text" value="" spellcheck="false" autofocus>
<input type="button" name="search" id="search" value="Search"/>
<!--- Display result -->
<span id="res"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
// function used for AJAX call
function searchData(){
var txt = $("#field").val();
$.get("searchData.php", {search: txt}, function(result){
$("#res").html(result);
});
}
// search every 5 second
setInterval(function(){searchData()}, 5000);
// if press enter button search
$('#field').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
searchData();
}
});
// if search button press
$("#search").click(function(){
searchData();
});
});
</script>
searchData.php - Page used to handle the request
<?php
// testing purpose
echo $_GET['search'];
?>

Related

how do i trigger a button with the enter key in java script?/ how to give text box and search button an ID?

Sorry i know this question has been asked and answered before but i can't seem to implement it into my code. very new to programming and struggling quite a bit.
Pretty simple stuff here i have a search bar and a search button. What i am trying to do is instead of having to physically click the search button to search for what i want, i would like to have the ability to be able to click the enter key which could search as well. Here is the code for the search bar and button.
Easy stuff.
<div class="ui-widget"> <!-- only for css purposes-->
<input id="search"> <!-- for the search box-->
<button type="button" onclick="searchresult()">Search</button> <!-- search button-->
</div>
So at the moment when you click the search button it will activate the javascript function i have which is:
function searchresult() {
//find the result
}
which in turn will find the result you want. deadly stuff.
I haven't included the code which is inside the javascript function as we don't need it for this question and its quite lengthy.
so basically i want the enter key to be able to activate the searchresult javascript function the same way the search button does.
I am aware that you can use jQuery keypress() Method to do this. and here is the code which can be used to do what i am wondering but i just don't know how to implement it into what i have:
$("#id_of_textbox").keyup(function(event){
if(event.keyCode == 13){
$("#id_of_button").click();
}
});
I am aware of the id attribute which is used in HTML coding as well but i don't know how i would go about correctly assigning the search button and text box an id each which then i could use in the code i have just above which then in turn would allow me to use the enter key as search as well.
So if anyone could just show me how i could use the jQuery code i found to solve my question that would be brilliant. Completely open to any other suggestions about how i would go about it either.
Thank you everyone for your time and attention!
Use the following code (explanation below):
function searchresult() {
console.log('searching');
//find the result
}
$("#search").keyup(function(event) {
if (event.keyCode == 13) {
$("#searchButton").click();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui-widget">
<input id="search">
<button type="button" id="searchButton" onclick="searchresult()">Search</button>
</div>
What this does is it will hook up an event to the input box with the id search and whenver it receives a keyup (key release) event, it will check if it is the Enter key and, if so, fire the click event of the button with id searchButton (I added that id as an example). Your search button's click event is hooked up to the searchResult() function, which is in turn called from that.
If you need more information on how event handling works in jQuery, check out jQuery's Handling Events page.
You really should consider using a form.
function search_function(search_terms){
// Do your search action here
alert(search_terms);
};
$(function(){
$("#search").on("submit", function(e){
search_function($("#search_terms").val());
e.preventDefault(); // Prevents submitting in most browsers
return false; // Prevents submitting in some other browsers
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='search'>
<input type='text' id='search_terms' placeholder='Search' />
<button>Search</button>
</form>
Or here is an example in pure JS
function search_function(search_terms){
// Do your search action here
alert(search_terms);
};
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("search")
.addEventListener("submit", function(e){
search_function(document.getElementById("search_terms").value);
e.preventDefault(); // Prevents submitting in most browsers
return false; // Prevents submitting in some other browsers
});
}, false);
<form id='search'>
<input type='text' id='search_terms' placeholder='Search' />
<button>Search</button>
</form>
You can assign the id to your search button :
<button type="button" onclick="searchresult()" id="search_key">Search</button>
Then you can trigger the click action on button using jQuery#trigger
JS :
$("#id_of_textbox").keyup(function(event) {
if (event.keyCode == 13) {
$("#search_key").trigger('click');
}
})
$('#search").change(function() {
searchResult();
});
Don't even bother with looking for the "enter" key; just watch for the input value to change (which would happen upon pressing enter, or blurring the field).
You can use a form and it's onsubmit event since you want enter key and submit click to do the same thing.
<form action="" method="" onsubmit="searchresult(this);">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
But don't forget to use event.preventDefault() or return false.

Pressing Enter reloads page instead of submitting form

I have a form that takes a ZIP Code input and forwards the user to one of two URLs depending on the input. Everything works great when you click the submit button, however, pressing enter reloads the page, I have gone through about 30 similar forums to no avail. I have tried multiple things including changing the submit button type from button to submit. I have tried several snippets to force the enter key to do what I want but none of them have worked. It just keeps reloading the page. Here is the code that I currently have on the site:
<div align="center">
<script type="text/javascript">
//<![CDATA[
function zipValidate() {
val = document.zipForm.zip.value;
switch (val) {
case '94005':
document.location = 'http://www.crossborderscheduling.com/home/calendar/';
break;
default:
document.location = 'http://crossborder.fedex.com/us/';
break;
}
}
//]]>
</script>
<form name="zipForm" id="zipForm" method="post">
<input name="zip" type="text" id="zip" maxlength="5" size="10%" placeholder="Zip Code" />
<input name="zipButton" type="button" id="zipButton" value="Submit" onclick="zipValidate()" />
</form>
</div>
<form> has a default [action] of "" which means that when the form is submitted, the data will be posted to the current page.
Your <input name="zipButton"...> element uses type="button" instead of type="submit" and you've bound an onclick event handler to it.
Clicking the #zipButton element doesn't actually submit the form, which is why your zipValidate callback works.
Pressing Enter while focused on the #zip field will trigger the implicit submission behavior for the form, which triggers the submit event on the form element, and completely ignores the #zipButton click callback.
So how do you fix it?
Let's start by fixing the HTML:
<form name="zipForm" id="zipForm" method="post">
<input name="zip" type="text" id="zip" maxlength="5" size="10" placeholder="Zip Code" aria-label="Zip Code" />
1: ^^^^^^^^^ 2: ^^^^^^^^^^^^^^^^^^^^^
<input name="zipButton" type="submit" id="zipButton" value="Submit" />
3: ^^^^^^^^^^^^^ 4: ^
</form>
the [size] attribute should have a value that is a non-negative integer
as you're not using a <label> element, it's important to provide a label for accessibility. The [placeholder] attribute is not an adequate substitute.
the button should use the submit type
keep your JavaScript out of your HTML
Now that the HTML has been cleaned up, let's look at the JavaScript:
<script>
// 1 ^^^,
// 2
function zipValidate() {
// 3
var val,
action;
// 4
val = document.getElementById('zip').value;
switch (val) {
case '94005':
// 5
action = 'http://www.crossborderscheduling.com/home/calendar/';
break;
default:
action = 'http://crossborder.fedex.com/us/';
break;
}
// 6
this.setAttribute('action', action);
}
// 7
document.getElementById('zipForm').addEventListener('submit', zipValidate, false);
</script>
don't use [type="text/javascript"], it hasn't been necessary for a very long time
don't use CDATA, it too hasn't been necessary for a very long time
declare your variables
don't use implicit global references by ID, instead query the DOM using one of the DOM searching methods: getElementById, getElementsByTagName, getElementsByClassName, querySelector, or querySelectorAll
store the URL you want to submit the form to. An if statement or ternary operator would have sufficed, but I left the switch because it hardly matters for this case.
set the [action] attribute for the form to tell the form where it's about to submit to. You don't need to call preventDefault on the event, because the submission behavior will take care of the redirect that you're after.
bind the event handler to the form from JavaScript. You may need to rearrange where the script is executed in the DOM, or wait for document.onreadystatechange so that the #zipForm element exists when you attempt to bind an event to it.
To prevent the form from submitting you need to return false in your onclick code. To do that you might change it to:
onclick="zipValidate() && return false;"
Alternatively you could modify your function to return false and then change onclick to:
onclick="return zipValidate();"

Sending form text input to console.log for testing

I have a simple form with one text field for testing. I need to have the info the user types in sent to console.log for now. Is this possible and if so what would I write?
<form class="pure-form">
<input id="name" type="text" placeholder="Enter Name" />
<button type="submit"><i class="fa fa-chevron-circle-right"></i></button>
</form>
var nameInput = document.getElementById('name');
document.querySelector('form.pure-form').addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
console.log(nameInput.value);
});
Not sure why this question was down-voted. It's basic, but it's still a perfectly valid question.
The simplest way would be to grab the input by the ID then grab it's value and console.log it.
So, in a separate JavaScript file which you are included, or in a block, you would use:
console.log(document.getElementById('name').value);
You'll probably want to hook that to some event as well, so it prints each time they do something. The "change" event is probably the most appropriate. It fires every time the user types something and then changes focus (sometimes it'll also trigger when they stop typing, but not usually). If you want it to print every time a letter changes, you would want to use (one of) the "keydown", "keyup" or "keypress" events instead.
document.getElementById('name').addEventListener('input', function() {
console.log(this.value);
});
Sure
var input = document.getElementById('name');
console.log(input.value);
Here it is with an on change event as well as a keyup (in case you need to see it somewhat 'live').
<form class="pure-form">
<input id="name" type="text" placeholder="Enter Name" onChange="inputChange(event)" onKeyUp="inputChange(event)" />
<button type="submit"><i class="fa fa-chevron-circle-right"></i></button>
</form>
<script type="text/javascript">
function inputChange(e) {
console.log(document.getElementById("name").value);
}
</script>
you can create a function like this and get the value of text box by its id.
function getData() {enter code here
let search = document.getElementById("search").value;
console.log(search);
}

jQuery/JavaScript - Displaying value from text-input in <span>-placeholders

I FORMULATED MY SELF VERY BADLY!
I will start over :) I appreciate your good answers, and if you can, try answering this: ( I will try to be more specific this time)
What I want is, that a <form>element onsubmit, onclick of a button or whatever takes the value of an <input type="text" value="Default value"> and inserts it in a couple of <span>elements, I like to call "placeholders". This sample might explain it a little better:
<head>
<script type="text/javascript">
$(document).ready(function()
{
$("input[type=button]").click(function //click the button
{ do_the_magic_thing() //make the value from id="txt_inp" appear in class="placeholder"
});
});
</script>
</head>
<body>
<form method="POST" action="" id="theForm"> //could also be get, I don't care
<input type="text" id="txt_inp" value="Default Value" onfocus="if (this.value == Default Value) this.value=''"> //this SHOULD make the Default Value dissapear on focus
<input type="button"> //could also be a submit
<span class="placeholder"></span> //$("#txt_inp").value; goes here
<span class="placeholder"></span> //$("#txt_inp").value; goes here
</body>
Now, is it really as simple as this?:
var do_the_magic_thing = function() {
$(".placeholder").html = $("#txt_inp").value;
};
I'm going to bed now - it's late in Denmark :) I will answer your comments tomorrow :)
OLD POST:
I am very new to this jQuery thing, but I do understand the basics and all. Let's simplify and say I have a form which looks like this:
<form method="POST" action="">
<input type="text" value="Default value">
<input type="submit" value="Click me">
<input type="hidden"> //hidden is for being able to submit by hitting enter
</form>
I've tried with $.post, but I just cannot get it right; it's not working for me.
Now, I would like to cancel the submit (can't that be done by just adding a return false; in the function returning the value, if a such is present?), but this is not crucial.
I think I typed in something like
$.post("test.php", function(data) {
alert("This is the data submitted (and cancelled):" + data);
}); //I have also tried without the "test.php", that's not it
Can you tell me, what I'm doing wrong please? :)
NOTE
It is not necessary, that the submit is cancelled, but I would like that
Nor is it necessary, that POST is the method used, but once again, this is what I prefer
Change the id of your form to "myform" or whatever and the name of your text input to "myinput", and try something like this...
$(document).ready(function() {
$('#myform').submit(submitMyForm);
})
function submitMyForm(e) {
var data = new Object();
data.whatever = $('#myinput').val();
var post = new Object();
//here I use a jquery json extension...you can use anything you like
post.data = $.toJSON(data);
$.post("test.php", post, function(returnval) {
alert(returnval);
}, "text");
//this is to stop the normal form submit action
return false;
}
Then in your test.php you can access it by calling $_POST['data'] (we specified this when we created the property of the "post" object called "data" like this: post.data = 'whatever'.
To answer the revised version of your question, yes, it really is that simple, although the correct syntax for your "do the magic thing" function is the following:
var do_the_magic_thing = function() {
$('.placeholder').html($('#txt_inp').val());
};
P.S. Don't worry too much about not expressing yourself, your English is much better than my Danish.
I think what you want to do is something like this:
<fieldset id="myData">
<legend>My Data</legend>
</fieldset>
<form id="myForm" method="POST" action="">
<input type="text" value="Default value">
<input type="submit" value="Click me">
<input type="hidden"> //hidden is for being able to submit by hitting enter
</form>
$(function() {
$('#myForm').submit(function() {
//do whatever you want here.
//this will take place after the form is submitted, but before your ajax request
$('input[type=text]').each(function() {
$('#myData').append('<div class="placeholder">' + $(this).val() + '</div>');
});
//serialize your form data
var toSubmit = $('input[type=text]').serialize();
//do ajax here
$.post('test.php', toSubmit, function(data) {
alert('Your AJAX POST request returned: ' + data);
}, 'text');
//this will prevent the form from submitting normally
return false;
});
});
Here's a demo of this in action: http://jsfiddle.net/SA3XY/
Also see my comment on your question.
Well for the form submit you need to add the following to the form to cancel the default submit event:
<form onsubmit="return functioncall();">
Then when you return false from the function it will cancel the default form action.
EDIT: If you would like to see all the data that is to be submitted you can serialize the form using jquery serialize() method or serializeArray() method.
If you're trying to accomplish validation, there's a much easier way, just use a validation plugin like this one:
http://docs.jquery.com/Plugins/Validation
Makes it much easier and takes the headache out of developing your own code. Jquery makes it easy to develop powerful javascript applications...but sometimes it's just easier to use stuff that's already been written and debugged (for the most part at least).

Page Redirection

I'm working on a script where all I want it to do (right now) is redirect the user based on which button they press. Eventually it will take form input and incorporate that into the redirect, but right now I'm just trying to get the buttons to send the user off to the appropriate site. However, My redirects aren't working.
<html>
<head>
<title>
Home
</title>
</head>
<body>
<script type="text/javascript">
<!--
var textstring;
var btnWhichButton;
//Gets the text from the form
function getQ() {
textstring = document.forms['Search'].elements[0].value;
}
//Does a Google Search
function googleSearch() {
window.location ="http://www.google.com";
}
//Does a YouTube Search
function youtubeSearch() {
window.location = "http://youtube.com";
}
//Figure out which button was pressed
function whichButton() {
if (btnWhichButton.value == 'Google Search' ) {
googleSearch();
} else if (btnWhichButton.value == 'YouTube Search' ){
youtubeSearch();
}
}
//main function to run everything
function main() {
getQ();
whichButton();
}
// -->
</script>
<form name="Search" >
<input type="text" name="q" size="31" maxlength="255" value="" />
<input type="submit" value="Google Search" onclick="btnWhichButton=this; main();" />
<input type="submit" value="YouTube Search" onclick="btnWhichButton=this; main();" />
</form>
</body>
</html>
When either button is clicked, the page just reloads with ?q= appended to the url, it doesn't redirect. Any help?
You want to use a button not an input type='submit'. Your current buttons are submitting the form, not performing their onclick actions.
Or block the submit action in some way. Or you could use your functions to set the form action to the url and just let it submit.
Your scripts seem highly overcomplicated. Why not have three functions: getQ, googleSearch, and youTubeSearch? Then inside the onClick event you can call the exact function, including this.value inside the input parameters and calling getQ from inside that function? Your method seems highly inefficient. If you're going to have separate functions for each of them anyways, there's no use in going through two other functions in order to get to them.
A submit button will always submit the form without a return false at the end of the onClick event, and since the default posting method is GET, its attaching ?q= to the end of your URL because that field is blank and it's the only input field in the form.
For redirecting to new page you no need to use the big javascript function.
<html> <body>
<input type="button" value="Google Search" onclick="javascript:window.location.href='http://www.google.com'" />
<input type="button" value="You tube Search" onclick="javascript:window.location.href='http://youtube.com'" />
</body></html>
Please check whether it helps you.
Well as jasonbar says, change your input to be of type 'button' and not 'submit'. Plus, I'd rather use window.location.href instead of window.location only. I don't know possible this is good practice...happy programming.

Categories