I need to build a search form with Select2 but I have problems getting it to work right.
The user enters the search term into the field which populates suggestions via AJAX. A click on the suggestions brings him to the page. Otherwise he needs to click on the submit button / or press enter, to get to the extended search. The last point (click on the submit button) doesn't work.
<form action="/search" method="get" class="form-search" id="global_search_form">
<div class="input">
<input type="text" name="q" class="search-query" id="global_search" placeholder="Enter search term ...">
<button type="submit" class="btn">Search</button>
</div>
</form>
<script type="text/javascript">
jQuery("#global_search").select2({
placeholder: "Enter search term ...",
minimumInputLength: 2,
multiple: 1,
containerCssClass: 'search-query',
ajax: {
url: 'remoteGlobalSearch',
dataType: 'jsonp',
quietMillis: 100,
data: function (term, page) {
return {
q: term,
per_page: 10,
page: page
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {
results: data.items,
more: more
};
}
},
formatResult: itemFormatResult,
formatSelection: itemFormatSelection,
escapeMarkup: function (m) {
return m;
}
});
function itemFormatResult(item) {
var markup = '<table class="item-result"><tr>';
if (item.image !== undefined) {
markup += '<td class="item-image"><img src="' + item.image + '" /></td>';
}
markup += '<td class="item-info"><div class="item-type">' + item.type_string + '</div>';
markup += '<div class="item-title">' + item.title + '</div>';
markup += '<div class="item-description">' + item.description + '</div>';
markup += '</td></tr></table>';
return markup;
}
function itemFormatSelection(item) {
location.href = item.url;
}
</script>
Cheers
I think there is a compatibility issue with button, type=submit and how various browsers interpret it.
Have you tried to use
<input type="submit" value="Search">
instead of the button tag?
Or, if you really need to use the button tag, then I would recommend having something as:
<button type="button" class="btn" onclick="this.form.submit()">Search</button>
Did this solve your problem?
Cheers!
Related
I want to get a JSON file from another server xyz.com (not writhing here original site name for safety) for my HTML page but the problem is that the website xyz.com only supports HTTP POST requests.
To check if my HTML code is working fine I use HTTP GET method and upload JSON data on another site that supports HTTP GET request. And I found that it is working fine. But when I try for HTTP POST method it is not working. Can you help me?
I am using currently and working fine
<script>
$(function() {
var people = [];
$.get('https://api.myjson.com/bins/c307c',function(data) {
$.each(data.video, function(i, f) {
HTML CODE FOR xyz.com and it also return a .json file
<html>
<head>
<form action="https://www.xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="Passkey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="Passkey" required>
<button type="submit" >GET Json File From Server</button>
</div>
</form>
This is i tried but not working
<script>
$(function() {
var people = [];
$.post('https://xyz.php', usedId=5&passkey=55, function(data) {
$.each(data.video, function(i, f) {
Try this way code
$.post( "https://xyz.php", { usedId: 5, passkey: 55},
function(data) {
//your code
} );
Please make necessery change so that when i click on button it take data from server and show in a table format
<html>
<head>
<form action="https://xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="passKey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="passKey" required>
<button type="submit" >GET DATA</button>
</div>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.post( "xyz.php",function(data) {
$.each(data.video, function(i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
var tblRows = "<tr>" +
"<td>" + f.videoName + "</td>" + "<td>" + f.date + "</td>" + "<td>" + f.time + "</td>" +
"<td>" + f.videoDuration + "</td>" + "<td>" + f.liveStatus + "</td>" + "<td><a target='_blank' href='"+link+"'>"+link+"</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" width="50%" border="2">
<thead>
<th>VIDEO NAME</th>
<th>DATE</th>
<th>TIME</th>
<th>DURACTION</th>
<th>LIVE STATUS</th>
<th>LINK</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</html>
Some changes I suggest:
Give the form an ID, in this case login seems like an appropriate ID
Standardize your capitalization for form fields
Here's some code to get you started. You'll notice I'm creating your data twice. Decide if you want to build your data by hand or use jQuery's serialization to do it for you. Since this is a simple form, the latter is probably fine.
I'm also getting the AJAX endpoint right from the form so you aren't repeating yourself there.
// when the document has loaded...
$(document).ready(function () {
// if the user is already logging in
var login = false;
// when the form is submitted...
$('#login').on('submit', function (event) {
// block the form if it's already been submitted
if (login) {
event.stopPropagation();
event.preventDefault();
return;
}
// lock the form
login = true;
// get a handle on the form
// I use $ as a prefix to differentiate jQuery objects
// currentTarget is the subject of the event
var $form = $(event.currentTarget);
var url = $form.prop('action');
/*
* MANUAL
*/
// form fields are added to the form object as properties by name attribute
// note that they are not jQuery objects
var data = {
userId: $form.userId.value,
passKey: $form.passKey.value
};
/*
* AUTOMATIC
*/
// uses jQuery's form serialization to automatically create an object mapping names to values
var data = $form.serialize();
$.post(url, data)
// on success
.done(function (data, status, request) {
$.each(data.video, function (i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
// backslash at the end of a string means to continue the string on the next line
var $row = $('<tr>\
<td>' + f.videoName + '</td>\
<td>' + f.date + '</td>\
<td>' + f.time + '</td>\
<td>' + f.liveStatus + '</td>\
<td><a target="_blank" href="' + link + '">' + link + '</a></td>\
</tr>');
$row.appendTo('#userdata tbody');
})
// on failure
.fail(function (request, status, error) {
window.alert('Failed with a status of ' + status + ': ' + error);
})
// executes after either of the above
// parameters are inconsistent and use either done's or fail's
.always(function () {
// do cleanup, i.e. unlock form submission, close modal dialogs, etc.
login = false
});
// stop default form submission
event.stopPropagation();
event.preventDefault();
});
});
Picture above shows snippets of Furnitures table. The user will key-in their desired reference number in ReferenceNum field. The problem is, the data itself have slash(/). Everytime the user try to submit the value, my url became MyWebsite.com/Furniture/PriceList/Ref/3/Case2, thus the website couldnt find the website.
View
<div class="form-group row">
<label class="control-label col-md-2">Reference Number</label>
<div class="col-md-8">
<input type="text" class="form-control" id="RefNum" />
</div>
<div class="col-md-2">
<input class="btn btn-success" id="getReference" value="Find"/>
</div>
</div>
<p id="rData">
</p>
JS
<script type="text/jscript">
$('#getReference').click(function () {
$.getJSON('/Furniture/PriceList/' + $('#RefNum').val(), function (data) {
var items = '<table><tr><th>Name</th><th>Reference Number</th></tr>';
$.each(data, function (i, lists) {
items += "<tr><td>" + lists.ItemName + "</td><td>" + lists.ReferenceNum + "</td></tr>";
});
items += "</table>";
$('#rData').html(items);
});
})
Controller
public JsonResult PriceList(string id)
{
var result = db.Furnitures.Where(x => x.ReferenceNum == id);
return Json(result, JsonRequestBehavior.AllowGet);
}
You can add the result as a query string value, rather than a route value
$('#getReference').click(function () {
$.getJSON('/Furniture/PriceList?id=' + $('#RefNum').val(), function (data) {
or
$('#getReference').click(function () {
$.getJSON('#Url.Action("PriceList", "Furniture")', { id: $('#RefNum').val() }, function (data) {
You can use %2F to escape slash(/) character in URL.
So updated JS code will be:
<script type="text/jscript">
$('#getReference').click(function () {
$.getJSON('/Furniture/PriceList/' + $('#RefNum').val().replace(/\//g,'%2F'), function (data) { //<--- Fix
var items = '<table><tr><th>Name</th><th>Reference Number</th></tr>';
$.each(data, function (i, lists) {
items += "<tr><td>" + lists.ItemName + "</td><td>" + lists.ReferenceNum + "</td></tr>";
});
items += "</table>";
$('#rData').html(items);
});
})
I have a input box. I enter the search term and the values get returned. What I am trying to do is click the dynamic button with the value attached to it. However when I click on the button it reloads the page instead of showing an alert box. This only happens with the dynamic button not the searchButton
$(document).ready(function () {
$('.cta-button').click(function () {
event.preventDefault();
alert("You clicked the button");
});
$('#searchButton').click(function () {
event.preventDefault();
var varSearch = $('#searchDB').val();
if (!varSearch) {
$('#result').html("Please enter a search term");
return;
}
$.ajax({
contentType: "application/json; charset=utf-8",
data: 'ID=' + varSearch,
url: "getTest.ashx",
dataType: "json",
success: function (data) {
var result = '';
$.each(data, function (index, value) {
result += '' +
'<div class="main-area bg-white">' +
'<div class="row">' +
'<div class="medium-6 columns">' +
'<button type="submit" id="OfferID_' + index + '" class="cta-button cta-button-icon">Add to Cart</button>' +
'<br />' +
'</div>' +
'</div>' +
'</div>'
});
if (!result) {
result = 'No data were found for ' + varSearch;
};
$('#result').html(result);
}
});
});
});
<section>
<div class="row">
<div class="medium-4 columns medium-centered">
<div class="search-rewards">
<input type="search" id="searchDB" />
<button type="submit" id="button" class="button"></button>
</div>
</div>
</div>
<div class="row">
<div class="medium-6 columns medium-centered">
<div id="result">
</div>
</div>
</div>
</section>
You're missing the event argument to your click functions. Without it, event.preventDefault() does nothing.
$('.cta-button').click(function(event) {
event.preventDefault();
alert("You clicked the button");
});
Update
To bind to dynamic buttons, you'd need to use a delegate as #MACMAN suggested:
$(document).on('click', '.cta-button', null, function(event){
event.preventDefault();
alert("You clicked the button");
});
Use delegate to assign the click property to the dynamic button.
Sometimes JQuery events not working for dynamically generated elements. You can use JQuery.on() for dynamically generated elements.
http://api.jquery.com/on/
try using this
$('.cta-button').on("click", (function() {
event.preventDefault();
alert("You clicked the button");
});
I have a dynamic table that I will be submitted to database.
The html is looked like this :
<form id="upload">
<div class="box-body">
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="tableReport">
<thead>
<th>TYPE</th>
<th>ITEM</th>
<th>DAMAGE</th>
<th>REPAIR</th>
<th>REMARKS</th>
<th>MANHOUR</th>
<th><button class="btn btn-block btn-primary" id="addRow" type="button">ADD</button></th>
</thead>
<tbody>
<!--GENERATED BY JQUERY-->
</tbody>
</table>
</div>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-info" type="submit">Upload</button>
</div>
</form>
See, on my <th>, I have a button with id addRow that have a function to add a row on a last row.
This is the code :
$(document).on('click', '#addRow', function () {
var selType = '<select class="form-control" name="type">';
var selItem = '<select class="form-control" name="item">';
var selDamage = '<select class="form-control" name="damage">';
var selRepair = '<select class="form-control" name="repair">';
$.each(<?php echo json_encode($type); ?>, function (i, elem) {
selType += '<option>' + elem.NAMA_TYPE + '</option>';
});
$.each(<?php echo json_encode($item); ?>, function (i, elem) {
selItem += '<option>' + elem.NAMA_ITEM + '</option>';
});
$.each(<?php echo json_encode($damage_codes); ?>, function (i, elem) {
selDamage += '<option>' + elem.NAMA_DAMAGE + '</option>';
});
$.each(<?php echo json_encode($repair_codes); ?>, function (i, elem) {
selRepair += '<option>' + elem.NAMA_REPAIR + '</option>';
});
selType += '</select>';
selItem += '</select>';
selDamage += '</select>';
selRepair += '</select>';
$("#tableReport").find('tbody').append('<tr><td>' + selType +
'</td><td>' + selItem +
'</td><td>' + selDamage +
'</td><td>' + selRepair +
'</td><td><input type="text" class="form-control name="remarks" placeholder="Describe it..">' +
'</td><td><input type="text" class="form-control time" name="manhour">' +
'</td><td><button class="btn btn-block btn-danger">Delete</button>' +
'</td></tr>');
$(".time").inputmask("hh:mm");
});
Now, this is the problem. How to handling the form. When <button class="btn btn-info" type="submit">Upload</button> is clicked to submit, I will handled it use jquery ajax. The code looked like this
$(document).on('submit', '#upload', function(){
/*First, How to handled the dynamic row ?? */
/* Commonly, I use var aVar = $('selector').val(); */
/* Ex, I have two rows, How bout to handle two select option in different row ?*/
$.ajax({
url: 'LINK TO CHECK THE POST if has SUBMITTED',
type: 'POST',
data : {/*dynamic row that will be passed : data*/}
dataType: 'json',
success: function(obj) {
})
return false;
});
How can I handle that dynamic row, and how can I debug if the post have success ?
UPDATED
This code to check the condition of a ship container. If a container have many damage, it will be representated with one row as one damage. If the container have 3 damage, it will be have 3 rows. I want to submit it on a table in my database in tbl_damage_detail. I have plan to multiple insert. So, I Imagine to store that rows into an array. with foreach, I will be inserted them.
JSFIDDLE
If the inputs are added correctly to the form you just need to submit the form with AJAX, no need for anything special, one way is to use the jQuery serialize() method like this.
$(document).on('submit', '#upload', function(event){
$.ajax({
url: 'LINK TO CHECK THE POST if has SUBMITTED',
type: 'POST',
data : $(this).serialize(),
dataType: 'json',
success: function(obj) {
})
event.preventDefault();
});
with your code,i really don't know what you want to do .
first, "on" is used to bind event with dynamic dom ,but id=addRow is not a dynamic dom,it is unnecessary to use on
"$(document).on('click', '#addRow', function () {"
just use $("#addRow").click( function () {...})
and then, <form id="upload">, i am not sure you have decide to post date to service with submit, in fact ,here is a dynamic table ,if you use submit to post your data ,it may complex with your whole table data .(using submit , input must set the name tag)
i suggest you should handle each row data
//get every row data
var tableData = [] ;
$("#tableReport tbody tr").each( function(){
var tr = &(this);
var text2 = tr.find(".time").val(); //should use more clean tag
var data = {test2:test2}//...
tableData.push(data)
//use ajax with the data
});
//next handle the tableData with ajax
this scene is very fat to mvvm like: angular , vue.js or avalon.js ,use one of them,with more clean but less code .
Hey guys and gals I'm having some major issues trying to get my application to work. I've been trying to hack through this and am missing the very first part which is sending the correct input value (button value) to get the ball rolling, I'm sure this is something simple but I've been having an issue getting it working. I'd appreciate it if someone could pick out the error(s) to help me along.
This is extremely easy to do in PHP, but since this is a standalone offline
app I cannot use PHP =( I need to do all my fetching and parsing in JQuery
or Javascript....
We start with a very basic form with some buttons that have unique values.
<form>
<fieldset>
<legend>Select Orders</legend>
<table id='master'></table>
</div> <!-- end input1 -->
<div>
<button name="select" type="submit" id="btnLoad" value="load">Refresh</button>
<button name="select" type="submit" id="btnJson" value="down">Download JSON</button>
<button name="select" type="submit" id="btnView" value="view">View/Enter</button>
</div>
</fieldset>
</form>
which triggers this function
$(function() {
$("form").submit(function() {
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
// $this.button.val() never makes it through?
queryJsonServer($(this), "class/");
return false;
});
});
I've tried things like
var button = $(this).attr("value");
var button = $('button').attr("value"); // ends up with the first buttons value,
// but never the selected or $(this).val()
$('button').click(function() { // which WILL console.log the buttons val,
console.log($(this).val()); // but will not let me turn it into a var?
return false; // ALSO this looks like it only reads the
}); // value the SECOND click?
The Mission here is to send the buttons value as a $_POST type over to a parser which will return the appropriate JSON array to be parsed, or to be stored in a Local SQLite DB.
Either way, here's the full code of the page, could someone please give me a hand, or if I need to clarify please let me know.
<?php
ini_set('display_errors', 1);
error_reporting(E_ERROR | E_PARSE);
var_export($_POST);
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title> </title>
<script src='http://www.google.com/jsapi'></script>
<script> google.load('jquery', '1.7.1'); </script>
<script>
$(function(){
$("form").submit(function()
{
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
$('button').click(function() {
var state = $(this).val();
return true;
});
// state is undefined. L29
console.log(state);
// $this.button.val() never makes it through?
queryJsonServer($(this), state, "class/");
return false;
});
// query json server for
function queryJsonServer(form, state, path)
{
// on first return or refresh inputs will be returrned
var view = $('input[name="orders"]:checked').val();
var url = path + "json.php?" + state; // status = button.val()
var state = $(this).attr("value"); // ends up class/json.php?undefined
// we have data, lets post to json parser and
$.getJSON(url, view, function(data)
{
$('form').unbind('submit').trigger('submit');
var items = [];
switch(state)
{
case 'load' :
$.each(data, function(index, obj) {
items.push('<tr>');
$.each(obj, function(key, val) {
items.push((key == "report_number")
? '<td class="check" ><input type="checkbox" name="' + val + '" /></td><td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>'
: '<td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>')
});
items.push('</tr>');
});
$('<div/>', {
'class': 'jsonOutput',
html: items.join('')
}).appendTo('#master');
break;
case 'down' :
// populate SQLite Database
break;
case 'view' :
$.each(data, function(index, obj) {
items.push('<tr>');
$.each(obj, function(key, val) {
items.push('<td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>')
});
items.push('</tr>');
});
$('<div/>', {
'class': 'jsonOutput',
html: items.join('')
}).appendTo('#master');
break;
default:
return false;
break;
}
});
}
});
</script>
<style type="text/css">
p, ul {width:100%; text-align:left;font-size:80%;}
.reports_box {width:auto; padding:25px 20px 20px 20px;border:1px solid #91bce6;background-color:#eff5fb;}
.inputs {width:300px; font-size:15px;padding:5px;}
.check input {padding:0 !important;}
.caps {text-transform:capitalize;}
#reports_list td, #reports_list tr {padding:10px 0 10px 2px;color:#34567b;}
</style>
</head>
<body>
<div class="reports_box">
<form id='submit'>
<fieldset>
<legend>Select Orders</legend>
<table id='master'></table>
</div> <!-- end input1 -->
<div>
<button name="select" type="submit" id="btnLoad" value="load">Refresh</button>
<button name="select" type="submit" id="btnJson" value="down">Download JSON</button>
<button name="select" type="submit" id="btnView" value="view">View/Enter</button>
</div>
</fieldset>
</form>
</div> <!-- end reports_box -->
</body>
</html>
Block form submission unless triggered by a button.
When form submission is triggered by a button:
Use $(form).serialize() to serialize the form
add "&select=ButtonValue" to the serialized string
Use $.getJSON to send a get request to your server page and get a JSON object back.
FINAL EDIT: Here's a working fiddle where I use serialize correctly: http://jsfiddle.net/YYZGG/5/
(When using the code change the form action to your correct page)
$(function(){
$("form").submit(function()
{
var state;
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
$('button').click(function() {
state = $(this).val();
return true;
});
// state is NOW DEFINED
console.log(state);
// $this.button.val() never makes it through?
queryJsonServer($(this), state, "class/");
return false;
.......................
Also, if having trouble getting the right values, try:
$('button').on('click', function(e) {
console.log(e.target.value);
});
EDIT:
Are you sure it should'nt just be:
$("form").submit(function(e) {
var state = e.target.value;
console.log(state);
---------
Why does your submit not include a post inside it? The method your using is GET that's why it's not a POST, either use .submit() and .post() together or just use an entire different approach working all together using GET and .click() functions, but here's an example of what using .post() looks like:
<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="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post and put the results in a div */
$.post( url, { s: term },
function( data ) {
var content = $( data ).find( '#content' );
$( "#result" ).empty().append( content );
}
);
});
</script>
http://api.jquery.com/jQuery.post/