I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. I need to somehow define the query terms in my window.location.hash.replace so I am just left with the search type from the URL. How can I go about changing the QUERYGOESHERE in my example below to the query the user has made? I hope people can understand my question.
My jQuery Script is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
if (window.location.hash != "") {
url = window.location.hash.replace('#', '').replace('/QUERYGOESHERE/', '');
$('#type_' + url).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
This should do it.
var full = window.location.hash.replace('#', '')
var queryType = full.substring(0,full.indexOf("/"))
var query = full.replace(queryType, '');
EDIT: Updated code
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0,full.indexOf("/"));
console.log('#type_' + queryType);
$('#type_' + queryType).click();
}
Related
I'm sure if I'm going about this the right way, but I need to pass the form variables in the URL redirect. The redirect is working, but I can't get the data to output.
$("#promoForm").on('submit', function(e) {
e.preventDefault();
var data = {
firstname: $("#firstname").val(),
lastname: $("#lastname").val(),
email: $("#email").val(),
code: $("#code").val()
};
if ( isValidEmail(data['email']) && (data['firstname'].length > 1) && (data['lastname'].length > 1) && (data['code'].length > 1) ) {
$.ajax({
type: "POST",
url: "php/promo.php",
data: data,
success: function() {
$('.success.pf').delay(500).fadeIn(1000);
$('.failed.pf').fadeOut(500);
setTimeout(function() {
window.location.href = "http://demo.example.com/signup?firstname=+data['firstname']+lastname=+data['lastname']+email=+data['email']+code=+data['code']"
}, 3000);
}
});
} else {
$('.failed.pf').delay(500).fadeIn(1000);
$('.success.pf').fadeOut(500);
}
return false;
});
Try this,
window.location.href = "http://demo.example.com/signup?firstname="+data['firstname']+"lastname="+data['lastname']+"email"=+data['email']+"code="+data['code']
You are not using variables to construct the URL:
window.location.href = "http://demo.example.com/signup?firstname=+data['firstname']+lastname=+data['lastname']+email=+data['email']+code=+data['code']"
Instead, close the string with " and append the values and follow-up strings:
window.location.href = "http://demo.example.com/signup?firstname=" + data['firstname'] + "lastname=" + data['lastname'] + "email=" + data['email'] + "code=" + data['code']
Additionally, you seem to be missing the parameter separators (&), so I should probably be:
window.location.href = "http://demo.example.com/signup?firstname=" + data['firstname'] + "&lastname=" + data['lastname'] + "&email=" + data['email'] + "&code=" + data['code']
I have a problem. I have features to sort, filter and search and when textarea of searchPhrase is null I have a problem:
Error: error https://localhost/cases/caselistsorted/no-filter/search_customer//casetype/desc
And I can't use sort and filter when searchPhrase is null.
How I can fix it?
This is my code:
function sendParam(element) {
var filterSelect = $("#filterSelect").val();
var searchOption = $("#searchOption").val();
var searchPhrase = $("#searchPhrase").val();
var params1 = $(element).attr("sort");
var params2 = $(element).attr("order");
var url = "{{restUrl}}cases/caselistsorted/" + filterSelect
+ "/" + searchOption + "/"+searchPhrase + "/"
+ params1 + "/" + params2;
$.ajax({
type: 'GET',
url: url,
data: null,
dataType: 'json',
success: function (data) {
if (data != null) {
console.log(url);
$(".case-list").html(data["code"]);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Error: " + textStatus + " " + url);
}
});
}
$(document).on('ready', function(){
$('.button-sort').on('click', function() {
sendParam(this);
});
$('#filterSelect').change(function () {
sendParam(this);
});
});
function customerSearch() {
sendParam(this);
}
function customerSearchTextInput(event) {
if (event.which == 13 || event.keyCode == 13) {
customerSearch();
return false;
} else if (event.which == 27 || event.keyCode == 27) {
customerSearchClear();
return false;
}
return true;
}
function customerSearchClear() {
var searchPhrase = $("#searchPhrase").val("");
console.log("FieldClear!");
}
When I write in searchPhrase somethink e.g "hello" I have such an outcome:
"https://localhost/cases/caselistsorted/no-filter/search_customer/hello/createDate/asc"
PHP Code :
if ($filter && $searchOption && $searchPhrase && $sortField == "createDate" && $order == "asc") {
usort($caseList, function ($a, $b) {
/* #var $a CMCase */
/* #var $b CMCase */
$time1 = strtotime($a->createDate);
$time2 = strtotime($b->createDate);
return $time1 > $time2;
});
You could check if searchPhrase is not null by adding a ternary
(searchPhrase ? "/" + searchPhrase : "")
and only add the / (and searchPhrase) if it holds a value:
var url = "{{restUrl}}cases/caselistsorted/" + filterSelect
+ "/" + searchOption + (searchPhrase ? "/" + searchPhrase : "")
+ "/" + params1 + "/" + params2;
If you can use arrays, you can try something like this.
Note, its better to have a dataStructure, an object or an array. Object will not have order, so either you will have to use map or if you are on ES6, use set
var data = [];
/*data.push($("#filterSelect").val());
data.push($("#searchOption").val());
data.push($("#searchPhrase").val());
data.push($(element).attr("sort"));
data.push($(element).attr("order"));*/
data.push("test");
data.push("");
data.push("Hello");
data.push("World");
data.push("");
function isNotEmpty(val){
return !(
val === undefined ||
val === null ||
val.toString().trim().length === 0
)
}
var qsString = data.filter(isNotEmpty).join("/");
console.log(qsString)
I am using jQuery.validationEngine plugin .I have a below ajax function to check duplicate unique value for a field.
function _is_unique(caller) {
var value = jQuery(caller).val();
var field_id = jQuery(caller).attr('id');
var field_name = jQuery(caller).attr('placeholder');
if (value != '') {
var uniqueObject = new Object();
uniqueObject.field_id = field_id;
uniqueObject.value = value;
var uniqueString = JSON.stringify(uniqueObject);
var getUrl = window.location;
//console.log(getUrl);
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
jQuery.ajax({
type: "POST",
url: baseUrl + "/dashboard/check_unique",
data: uniqueObject,
async: false,
cache: false,
dataType: "text",
success: function(msg) {
if (msg == "exist") {
isError = true;
promptText += " This " + field_name + settings.allrules["is_unique"].alertText + "<br />";
}
}
});
}
}
if the field value is present in server then from server I am returnning "exist" else I am returning "notexist".
Now while running my ajax script is calling infinitely . Can any please tell me what should I do to stop infinite loop of my ajax call.
Edited
This is the form Submit function . its also showing
too much recursion
error in console. By any chance am I having problem here ?
$('#searchform').on('submit', function(e){
var validateError ='';
var id='';
var fieldError = [];
$('#searchform :input:text').each(function(){
id = $(this).attr('id');
validateError = jQuery.fn.validationEngine.loadValidation(document.getElementById(id));
if(validateError)
{ fieldError.push(id);
}
});
if(fieldError.length!=0)
{
return false;
}
else{
$("form#searchform" ).submit();
return true;
}
});
});
Login with Gmail on my site on the HTML page using javascript & PHP. The page will not be refreshed after login.
I am using this code.
<script>
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile www.googleapis.com/auth/userinfo.email';
var CLIENTID = '<Client ID>';
var REDIRECT = 'url/'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch (e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText) {
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\#&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null)
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
</script>
This code will redirect to anothe page but I want page will not be referesh. Only give the response in the form of (true, false) from server.
please give better solution for this.
Thanks in advance.
I have a Google Instant style jQuery search script that queries a PHP file then parses the results into an HTML div. It uses tabs for the user to define the search type that they want and when a search is made, a URL is created which is something like #type/query/.
Currently, the search box is selected on page load with the $('#query').focus(); function however I want it to be deselected when the page is reloaded and there is text in #query. How can I go about doing this? I hope you can understand my question.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#query').focus();
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0, full.indexOf("/"));
$('#type_' + queryType).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}
});
Remove $('#query').focus(); from where it is now, and add it in with an else like this:
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}else {
$('#query').focus();
}