AJAX based search returning page information - javascript

I found the source of the error but do not know how to fix it. I'm using codeigniter and I'm trying to make a textbox with search results showing under it to help the user find what they are looking for. Think similar to google's search. When I make the AJAX call, it's returning everything on the webpage as well as the search results.
Example of issue: https://gyazo.com/244ae8f3835233a2690512cebd65876d
That textbox within the div should not be there as well as the white space. Using inspect element I realized the white spaces are my links to my CSS and JS pages. Then there's the textbox which is from my view.
I believe the issue lies within my JS.
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
}
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = encodeURI(document.getElementById('txtSearch').value);
searchReq.open("GET", '?search=' + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}
//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('txtSearch').value = value;
document.getElementById('search_suggest').innerHTML = '';
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
var ss = document.getElementById('search_suggest');
ss.innerHTML = '';
var str = searchReq.responseText.split("\n");
for (i = 0; i < str.length - 1; i++) {
var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
suggest += 'onmouseout="javascript:suggestOut(this);" ';
suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
suggest += 'class="suggest_link">' + str[i] + '</div>';
ss.innerHTML += suggest;
}
}
}
More specifically the getXmlHttpRequestObject function. it is returning the entire page including my header and footer. I don't believe any more info is needed but if anyone feels that way, I'll supply the view and controller.
https://gyazo.com/d0c43326191a4b09cc4b1d85d67a1bf6
This image shows the console and how the response and response text are the entire page instead of just the results.

Your call to the view method is loading the header view, the suggest view and the footer view while your suggest model is echoing the data that you're after.
You could just remove the line $this->view("suggest"); and your suggestions will be echoed.
This isn't great though. I would pass the titles back to the controller from the model then create a new controller method that outputs the data in a structured way (probably JSON).

Related

How to populate jqGrid filter toolbar and search when the page loads (ASP.net webforms)

Currently, I'm trying to populate the filterToolbar with values taken in from a cookie. If there is cookie data for the filters, I want it to fill the respective textboxes and filter the jqGrid for that data.
I'm using ASP.net webforms, so most of my data is initialized already. How/where could I add javascript in order to get this going?
I actually figured out what I was doing.
So what I ended up doing as a solution was adding a timeout function in the document.ready function
$(document).ready(function () {
// some code
setTimeout(function () {
$('#Jqgrid1')[0].triggerToolbar();
}, 500)
//some code
}
My guess is that I couldn't use the $('#grid')[0].toggleToolbar() to force it because whenever I tried to use it, it was before the whole grid was finish setting up.
In the ASP webform, I had several functions registered.
<cc1:JQGrid ID="Jqgrid1" runat="server"
Height="630"
SearchDialogSettings-Draggable="true"
EnableViewState="false"
AutoWidth="True" >
<ClientSideEvents
LoadComplete="Jqgrid1_LoadComplete"
GridInitialized="initGrid"
/>
<%-- grid code --%>
</cc1:JQGrid>
The LoadComplete is executed after the grid is loaded. I tried doing triggering my toolbar there, but didn't work. My guess is, again, it was too early in the grid execution to use the triggerToolbar() function.
The same went for the GridInitialized events (even though both events would seem to imply to me that the grid is done doing its thing... but whatever...)
The way that I read my cookies in was actually in the GridInitialized event handler.
function initGrid() {
var myJqGrid = $(this);
var valueName = 'GridFilters';
var myCookie = document.cookie;
var gridFilterString;
var gridFilterArray;
var currentFilter;
var myCookie_arr;
var myDic = {};
if (myCookie.indexOf(valueName) > -1) { // don't even bother if the cookie isn't there...
myCookie_arr = myCookie.split("; "); // looking for the cookie I need
// read cookies into an array
for (var i = 0; i < myCookie_arr.length; i++)
{
parts = myCookie_arr[i].split("=");
first = parts.shift(); // remove cookie name
myDic[first.trim()] = parts.join("=").trim(); // handles multiple equality expressions in one cookie
}
if (myDic.hasOwnProperty("GridFilters"))
gridFilterString = myDic["GridFilters"];
if (gridFilterString != "NONE") {
myFiltersDic = {}
myFiltersArr = gridFilterString.split("&")
for (var i = 0; i < myFiltersArr.length; i++) {
parts = myFiltersArr[i].split("=");
myFiltersDic[parts[0].trim()] = parts[1].trim();
}
myParams = $(this).jqGrid("getGridParam", "postData");
var filters = []
for (keys in myFiltersDic) {
$('#gs_' + keys.trim()).val(myFiltersDic[keys].trim());
}
$.cookie('m_blnSearchIsHidden', "0", "/");
if (!isLoaded)
{
$(this)[0].toggleToolbar();
}
isLoaded = true;
}
}
}

Reload a content almost invisibly and no blinking effect using JAVASCRIPT

I'm writing a small progam wherein I'm getting data using $.get then display the data so far so good and then there's this part then when I click a certain link it refresh the page but it has this blinking effect. Is there a way on how to reload the content get the new updated content then replace the previously loaded data.
NOTE: I didn't use setInterval or setTimeout function because it slows down the process of my website. any answer that does not include those functions are really appreciated.
Here's the code
function EmployeeIssues(){
$('#initial_left').css({'display' : 'none'});
var table = $('#table_er');
$.get('admin/emp_with_issues', function(result){
var record = $.parseJSON(result);
var data = record.data,
employees = data.employees,
pages = data.pages;
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
for (var i = 0; i < employees.length; i++) {
$('#table_er').fadeIn('slow');
table.append(write_link(employees[i])); // function that displays the data
}
if(pages){
$('#pagination').html(pages);
}
}else{
$('#er_tab_label').html('<b>No employees with issues yet.</b>');
}
});
table.html('');
}
then this part calls the function and display another updated content
$('#refresh_btn').on('click', function(e){
e.preventDefault();
var tab = $('#tab').val();
if(tab == 'er'){
EmployeeIssues();
}
});
What should I do to display the content without any blinking effect?
thanks :-)
This section might be the issue :
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
for (var i = 0; i < employees.length; i++) {
$('#table_er').fadeIn('slow');
table.append(write_link(employees[i])); // function that displays the data
}
if(pages){
$('#pagination').html(pages);
}
} else ...
It seems you're asking table_er to fade in once per run of the loop whereas s there can only be one such table, you only need to do it once ?
first try re-arringing it like this:
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
$('#table_er').hide(); // hide it while we add the html
for (var i = 0; i < employees.length; i++) {
table.append(write_link(employees[i])); // function that displays the data
}
$('#table_er').fadeIn('slow'); // only do this after the table has all its html
if(pages){
$('#pagination').html(pages);
}
} else ....
Another possibility is that you're running through a loop and asking jquery to do stuff while the loop is running. It might be better to work out the whole HTML for the new page data in a string and then get the screen to render it in one line. I cna't do this for you as I don't know what's in write_link etc but something like this ..
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
var sHTML ="";
$('#table_er').hide(); // hide it while we add the html
for (var i = 0; i < employees.length; i++) {
sHTML+=write_link(employees[i]); // maybe this is right ? if write_link returns an HTML string ?
}
table.append(sHTML); // add the HTML from the string in one go - stops the page rendering while the code is running
$('#table_er').fadeIn('slow'); // now show the table.
if(pages){
$('#pagination').html(pages);
}
} else ...

On page reload, check boxes get selected and then disappear automatically within a second

I have a problem with a function that i'm writing.
Basically, I'm simulating a landing page. The landing page will contain a querystring. What I'm doing is to deserialize it on a button click and show(to check) the checkboxes defined in the querystring in the HTML.
Below is the click function which contains two functions.
The first one "simulateLandingPage" performs the url change.
The second one called "selectFacetsAutomatically" deserializes the "landingUrl" path and checks automatically the checkboxes in the HTML page according to what is defined in the querystring.
The problem that I'm encountering is that when I click on the "reload-page" button everything works but the checkboxes get selected just for a second and then disappear automatically quickly without any reason. Hence the page won't show the selected checkboxes in the end but just this weird thing.
Can anyone help? I'm pretty new to this and i'm stuck.
Thanks a lot!
$(".reload-page").click(function() {
var landingUrl = "size:4,10,16|base_colour:1,4|brand:53,3392,12767";
simulateLandingPage(landingUrl);
selectFacetsAutomatically(landingUrl);
return false;
});
function simulateLandingPage(landingUrl){
window.location.href = "refinements.html?refine="+ encodeURIComponent(landingUrl);
return false;
}
function selectFacetsAutomatically(landingUrl){
var facetGroup = [];
var selectedFacets = [];
var facetType;
//split string when it finds the pipe symbol
$.each(decodeURIComponent(landingUrl).split(/\|/), function (i, val) {
selectedFacets.push(val);
console.log("val", selectedFacets[i].split(/\:/)[1].split(/\,/));
facetType = selectedFacets[i].split(/\:/)[0];
facetGroup = selectedFacets[i].split(/\:/)[1].split(/\,/);
$.each(facetGroup, function(i,val){
var facetToBeSelected = facetType + "_" + val;
$('[data-id='+facetType+']').find("#"+facetToBeSelected).prop('checked', true);
});
});
return false;
}

Javascript to build mvc actionlink conditionally

This is in a VB.NET MVC 3 Razor view and fires when a JsonResult of success is returned. The problem is that I would like to conditionally build an actionlink if data.Object.Status == 'Completed';
I have looked around and nothing seems to be fitting at all to solve this. This is what the actionlink should look like in razor:
#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = currentItem.firstName, .lastname = currentItem.lastName, .classRef = currentItem.course_ref, .cNumber = currentItem.conf_number}, Nothing)
And this is the javascript function that will do it. Currently it just Places the contents of data.Object.Status. Which should only show like that when data.Object.Status != 'Completed';
function updateSuccess(data) {
if (data.Success == true) {
//we update the table's info
var parent = linkObj.closest("tr");
parent.find(".CompletedClass").html(data.Object.Status);
//now we can close the dialog
$('#updateDialog').dialog('close');
//twitter type notification
$('#commonMessage').html("Update Complete");
$('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").html(data.ErrorMessage);
$("#update-message").show();
}
}
Below is what I am thinking will work I am still trying to figure it out but this is a rough markup of it.
function updateSuccess(data) {
if (data.Success == true) {
//we update the table's info
var parent = linkObj.closest("tr");
var d = parent.find(".CompletedClass");
if (data.Object.Status == 'Completed') {
d.html = #Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = Model(0).firstName, .lastname = Model(0).lastName, .classRef = Model(0).Completed_Class, .cNumber = Model(0).conf_number}, Nothing)
}
//now we can close the dialog
$('#updateDialog').dialog('close');
//twitter type notification
$('#commonMessage').html("Update Complete");
$('#commonMessage').delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").html(data.ErrorMessage);
$("#update-message").show();
}
}
What you suggest right now should work, there is a typo on your code assigning the HTML, you probably know it but the way you add HTML to an element is (You have a = sign which is not valid) :
d.html (#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", ....)
Assuming is an element that accepts html, otherwise, use the "text" function.
In any case, my recommendation would be to generate the HTML before hand but have it hidden on the page (unless you have thousands of them, of there are security concerns). Then you just have your Javascript simply show the element:
var parent = linkObj.closest("tr");
var linkElement = parent.find(".mylinkelement-class");
if (data.Object.Status == 'Completed') {
linkElement.show();
}
This should give you the benefit of allowing better separation between your Javascript and your MVC code.
HTH,
-Covo
You should update your code to something like this
d.html('#Html.ActionLink("Completed(Print Cert)", "Ind_Cert", "Printing", New With {.firstName = Model(0).firstName, .lastname = Model(0).lastName, .classRef = Model(0).Completed_Class, .cNumber = Model(0).conf_number}, Nothing)');
To assign html with jQuery you should use jQuery.html().
The Razor #Html.ActionLink will print HTML to the page, to not break your Javascript, put those inside quotes d.html('#Html...')

Execute javascript only in specific url

I have an external JS file with inside this code:
var mobile_number_param = document.getElementById('mobile_number_param');
mobile_number_param.maxLength = 9;
mobile_number_param.readOnly = true;
var email = document.getElementById('email');
email.readOnly = true;
var user_notes = document.getElementById('user_notes');
user_notes.maxLength = 90;
var admin_notes = document.getElementById('admin_notes');
admin_notes.maxLength = 90;
Now my goal is to apply the code related to "mobile_number_param" but ONLY when I'm on the "reserve.php" page otherwise I'm not allowed to modify my Mobile Phone number in other area such my profile page.
Somebody told me this:
You can recognize the current url by checking window.location.href and e.g. searching for reserve.php to know you're on the reservation page..then apply your code.
Unfortunately I'm not a coder and don't have any idea how to do.
Any suggestions ? Thank for your time...
if (window.location.href.indexOf('reserve.php') != -1) {
// do stuff for reserve.php page here
}
Just add the following function in your external JS File:
function myFunction(pagename) {
var pageurl = window.location.href;
var pg = pageurl.split("/"); /*SPLITS THE URL ACCORDING TO DELIMINATOR "/". Eg x/y/z/reserve.php pg[0]=x,..pg[3]=reserve.php*/
var pgname = (pg[pg.length - 1]);
if (pagename == pgname) /*check whether the current page is reserve.php or not*/
{
return true;
}
return false;
}
Calling the Function:
if (myFunction("reserve.php")) {
/*Yes reserve.php page*/
} else {
/*Not reserve.php page*/
}
Server sided you could read the HTTP referer field.
If it contains reserve.php include the one js else an other js.
If you prefer to use only one js you could wrap the fucionality into a function.
called from reserve.php with parameter 1, from other pages parameter 0
or else.

Categories

Resources