Using this tutorial http://aymeric.gaurat.net/2010/how-to-develop-live-search-textbox-in-ruby-on-rails/ as a guideline I have tried to implement my own search bar which will allow a user to start to write in another user's name and see that user (if in the database) as a drop down selection option.
However, when I run my code and type something in, nothing happens.. I am very new to Ruby, Rails and jquery/ajax, so if it's something obvious I apologise.
Here is my code:
customers_search.html.erb:
<form id = "live-search-form" method = get action = "<%= search_customers_path %>">
<input id="search-box" name = "query" type="text" placeholder="find colleagues" />
</form>
<div id="search-results"></div>
my customers controller search method:
def search
#q = "%#{params[:query]}%"
#customers = Customer.where("first_name LIKE ? or last_name LIKE ? ",#q,#q)
end
and here is my application.js file:
var main = new function(){
$('#search-box').bind("keyup", function(){
var form = $("#live-search-form"); //gets form wrapping search bar
var url = "/customers/_search"; //_search action
var formData = form.serialize(); //gets data in the form
$.get(url, formData,function(html){ //perform an AJAX get
$('#search-results').html(html);
});
});
}
$(document).ready(main);
Am I missing an AJAX plugin or something down those lines? Or is it a problem with my actual search method? How can I fix this?
I was trying to match whatever the user typed to either a customer's :first_name or :last_name.
Thanks guys
I have now stopped nesting my 2 forms and placing them side by side. I have also fixed my 'main' undefined error. Still I am getting no response to my search bar.
Related
I am using a form to post a record to my database in Django. The form looks something like this:
<form>
<div>Field 1</div>
<input/>
<div>Field 2</div>
<input/>
...
<a id='save'>Save</a>
</form>
I am using an event listener to let me know when this Save link has been clicked. When it is clicked, I would like to store the fields as a record in the database.
Here is my JS:
const savebtn = document.querySelector('#save');
savebtn.addEventListener('click', showSelected);
function showSelected(e) {
// post record to database here
window.location.replace("/"); // redirect to home page
I am hoping to use some python to post this record like shown below:
e = Entry()
e.field1 = 1
e.field2 = 2
e.save()
But I don't know how I can access a python function within JS. I'm thinking maybe a template tag could work here but can't figure out how to use it. Ideally I wouldn't have to rewrite the form as the formatting is kind of specific, is there a way to make this work?
You have to create an endpoint that will do the algorithm.
ie. some urls.py:
urlpatterns = [
path('my_save_view', my_save_view, ...),
]
views.py:
def my_save_view(request):
e = Entry()
e.field1 = 1
e.field2 = 2
e.save()
and in javascript just get/fetch that endpoint when you want to. You can pass any values to the view with either GET or POST method in a standard way if needed.
I have a webpage that has a dynamic search field that will query a database as you type in the search string (much like a google search with suggestions as you type). This part works via AJAX.
In the results, there are multiple rows of data that are displayed below as data is entered into the search field. What I decided to do is create an edit link on the right side of each row (with pencil icon) that is returned by ajax so I can click to another page for editing the data. Something like this...
<a href="edit.php?id=12&search=Goodyear"><i class="fa fa-pencil" aria-
hidden="true"></i></a>
So lets say that I searched for "Goodyear" in the example search and on row 12, I click the link that takes me to another page. I was wanting to use $_GET["search"] to turn around and create a BACK link to the original AJAX page. I know how to get this far, however, I need help customizing the ajax to reload the original search (which in this example is "Goodyear") when the link is clicked back to the search page. The link on the EDIT page would look something like:
Back to Search Page
But here is the issue. When the user returns, I need the search bar prefilled and the search results listed below. In other words, I want the page to be just like it was when they left prior to going to the edit page. I want AJAX to search the search again on page load just because it visited this url /search.php?search=Goodyear Making the url in the link on the edit page is not a problem for me. But it is when it is clicked to return to original search page.
Here is the AJAX code that does all the heavy lifting on the search.php page.
<script>
$(document).ready(function () {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: { query: query },
success: function (data) {
$('#brand').html(data);
}
});
}
$('#search_text').keyup(function () {
var search = $(this).val();
if (search != '') {
load_data(search);
}
else {
load_data();
}
});
});
</script>
I know that this search happens on a keyup event and the div called #brand displays the resulting rows of data below the search bar. It actually works well just on the search alone, but leaving the page and clicking back with a url (search.php?search="goodyear") like I mentioned is not doing what I need it to.
When I try to modify it, the search results stop showing. .
I have tried to customize this code to process the url using GET variable within this code that uses POST in the AJAX but I have been been unsuccessful so far. Any ideas on what I need to do?
I found the original page I originally used to make my search page.. here it if anyone wants to look: http://www.webslesson.info/2016/03/ajax-live-data-search-using-jquery-php-mysql.html
This may not be the perfect answer but it does work pretty nicely. Although the only thing it does not do is show the text in the search field when you return to the page. If anyone know how, give the answer... but this is what I did...
I found a nice piece of code that strips out the value of the parameter in the url and then throws it into an array variable. I found it on http://www.designchemical.com/blog/index.php/jquery/8-useful-jquery-snippets-for-urls-querystrings/. Here is the code.
var vars = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}
load_data(vars['search']);
search is the parameter in the url and if it says search.php?search=255 then it returns 255. So I threw that into the load_data argument value and it does the search. The only drawback so far is I haven't figured out how to make the value show in the search bar. I'll keep plugging.
UPDATE: I figured out the text in search box issue with this code:
$('input[name="search_text"]').val(vars['search']);
It put the search parameter back into the search input field like I wanted! One more note, be sure to put the above code above the load_data(vars['search']); may not matter but that is what I did to make it work!
This is what it looked like:
var vars = [], hash;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
vars.push(hash[1]);
vars[hash[0]] = hash[1];
}
}
$('input[name="search_text"]').val(vars['search']);
load_data(vars['search']);
I have a multi page form.
Page One has a few fields that get passed into the second form, via GET method, and it auto fills the first four fields of the second part of the form.
Page two has a few more questions, and when you submit it, it submits into our CRM(vanillaSoft), and leads to a thank you page.
My current issue:
I want to be able to take an affiliate link, such as:
http://something.com/step-one.html?AFFILIATE_ID=#affid#&SUB_ID=#s1#
I need to dynamically populate the AFFILIATE_ID parameter with a unique transaction ID, and the SUB_ID with a unique ID as well.
I currently have two fields on my first page with hidden fields, ex:
<input type="hidden" name="SUB_ID">
<input type="hidden" name="AFFILIATE_ID">
But that isn't working. I need this date to be sent into the CRM I use.
Any advice?
Thanks!!!
Your current setup will work if you set your form submit method to GET. You probably have it set to POST.
Setting your form method to GET will put those hidden fields in the URL, like you are expecting.
On the last form, set that one to POST (to POST to the server).
You can grab the Query string with JavaScript, like this:
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();
How can I get query string values in JavaScript?
You could also send both POST and GET methods. But POST can be done only on server side, where JavaScript is Client-side scripting language.
<form method="POST" action="form.php?a=1&b=2&c=3">
PHP -> Send both POST and GET in a form
How to read the post request parameters using javascript
One of our customers has a new requirement to dynamically capture the page/screen title and the labels of all the controls(textboxes, checkboxes, radio buttons, normal buttons,link,images,menu/menu items) on the page the users interacts with and then push them to an excel file.
If customer navigates/opens a page A and sets a value in the textbox Name = John , enables the checkboxChBox/radio button Rbutton and then finally clicks save/submit button, then the following output is being expected. User Action and Results being the first 2 columns of the Excel file.
**User Action** **Result**
Open Page/Screen A Page/Screen A is displayed
Set textbox Name = John Field Name is set successfully
Set ChBox = true ChBox is enabled successfully
Set Rbutton = true Rbutton is enabled successfully
Click Submit button Page B is displayed
Just wondering if it is possible to accomplish this and generic way of capturing the user interactions of any page.
Just an idea : you could listen all events (with jquery, for example), and then post an ajax request for each 'interesting' event (you have to filter...), store it in a database, and then add an 'export' function in csv or excel format.
Maybe some performance issues, it depends on the amount of pages, events and users...
The idea to use class name to filter is good, thanks to Hasan Iqbal Anik.
Javascript doesn't have access to writing files in hard drive. However you can capture the data, make a model and then store it in the server using ajax calls.
Some ideas:
Use a layout or master page that is rendered throughout the application views.
Give same class name for all the page labels, buttons, checkboxes and anything you need to store information about.
Use some jquery magic in the master/layout page to get the values of those elements and make an array.
Send that array through ajax call to the server.
Now you can get tons of examples of how to get element values using jquery. I'm saving you from giving all that. Hope that helps... :D
//edit: i'm trying to extend my answer as per steve requested.
<form action="someAction" id="myForm">
Name: <input type="text" class="Name">
Checkbox: <input type="checkbox" class="ChBox"/>Click this box
RButton: <input class="Rbutton" type="radio" />
Submit: <input type="submit" class="submit"/>
</form>
Now some jquery:
$(function() {
$(".submit").click(function(){
var dataToSend = new Object();
dataToSend.pageUrl = window.location.pathname + " is displayed";
if ($(".Name").val().length > 0) {
dataToSend.Name = "Field Name is set successfully";
}
else {
dataToSend.Name = "Field Name is empty";
}
if($(".ChBox").is(':checked')){dataToSend.ChBox = "ChBox is enabled successfully";}
else{dataToSend.ChBox = "ChBox is not enabled";}
if($(".Rbutton").is(':checked')){dataToSend.Rbutton = "Rbutton is enabled successfully";}
else{dataToSend.Rbutton = "Rbutton is not checked";}
dataToSend.Submit = $("#myForm").attr['action'] + " is displayed";
});
//now send it to the server via ajax
$.ajax({
type: "POST",
url: "your server action url that would make excel file with these data",
data: dataToSend,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//do as you wish
}
});
});
I am working in ASPDotNetStorefront on an XML package (largely irrelivant). Basically I have a form with a bunch of fields and a button that 'submits' the form. I would actually like to have the button convert the values of the fields into a querystring and then perform a GET instead of a POST.
I would imagine that I could do something like this with JavaScript, perhaps jQuery, but I'm not sure how I would do that. Ideally, I would like a simple function I could call.
I should note that I'm using ASP.Net and I only want to convert the actual values of the fields to a query string, not any state information. This is for a search form.
With jQuery:
$.ajax({
url: 'url/Action',
type: 'GET',
data: $('#formId').serialize()
})
using:
jQuery ajax
jQuery serialize
Response.Redirect("Webform2.aspx?Name=" +
this.txtName.Text + "&LastName=" +
this.txtLastName.Text);
in WebForm2.aspx you can do like this
for (int i =0;i < Request.QueryString.Count;i++)
{
Response.Write(Request.QueryString[i]);
}
for jquery you can use AJAX to send data between pages. Here is the sample code
This is the best article i have found Using jQuery for AJAX in ASP.NET : codeproject
example of using AJAX
<div style="width:350px">
<div style="background:#CCC"> Edit</div>
<div id="divView"><asp:literal id="litName" runat="server"/></div>
<div id="divEdit" style="display:none"></div>
</div>
var options = {
method: 'POST',
url: 'ChangeName.aspx',
after: function(response) {
$("div#divView").html(response).show();
$("div#divEdit").empty().hide();
$("a#editName").show();
}
};
//bind to form's onsubmit event
$("form#ChangeName").ajaxForm(options);
Example without AJAX.Simple Javascript with Query String
<script lang=”javascript” type=”text/javascript”>
function testQueryStrings()
{
window.location = “search.aspx?q=abc&type=advanced”;
}
</script>
<input type=”button” id=”btn” value=”Test Query Strings” onclick=”testQueryStrings()” />
for search.aspx
<script lang=”javascript” type=”text/javascript”>
var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split(‘&’);
for (var i=0;i<arr.length;i++){
// splits each of field-value pair
var index = arr[i].indexOf(‘=’);
var key = arr[i].substring(0,index);
var val = arr[i].substring(index+1);
// saves each of field-value pair in an array variable
arrQrStr[key] = val;
}
document.write(“<h1>Search parameter: “+arrQrStr["q"]+”. Extra parameter: “+arrQrStr["type"]+”</h1>”);
You could do this:
<input type="submit" value="get">
With (since you tagged this jQuery):
jQuery('input[type=submit]').click(function () { this.form.method = 'GET'; });
… but forms that might go to bookmark-able data or might make significant changes sound like they would be confusing to the user (and I can't think of any other reason to switch from post to get on the fly in end user controls).
If you always want to GET data, then you should modify the source sent to the browser instead of twiddling the DOM on the fly with JS.
Really, you just need to change the method attribute of your <form> tag in your HTML.
If you don't have direct control over the markup that your .NET component generates, you can always manipulate the <form> tag and set the attribute with JavaScript when the page loads.
Or, you can bind a click event to the form's submit button, and cancel the event (by returning false for example), and do a GET yourself.
You could just se <form method="GET"> instead of <form method="POST">. No Javascript needed (unless you do not want to refresh the page).