I am learning Javascript. I wrote a JS to return a Json-type value.
var generateUrl = function(Name, Letter, rootUrl, V1) {
rootUrl = rootUrl || Letter;
return {
classname: 'mycss-' + Letter,
text: Name,
url: rootHref.replace(Rex, "$1" + rootUrl + "."),
onclick: {
fn: clickFn,
obj: V1
}
};
};
I want to add a if statement inside url:.
For example, if Name = google, url won't use this logic rootHref.replace(Rex, "$1" + rootUrl + "."), instead it will directly return an url.
I have searched for an answer quite a while but still have no luck. May someone tell me how to add a if statement logic in my code.
Try as follows
url: (num == 1) ? Link1 : Link2,
Related
I need to be able to store the text value of a search box term, which can be used as a query parameter in a getJson request. I'm appending the search term to the end of the url the user is taken to after hitting the enter key, but the issue is that on the location replacement, it shows up as an error because the url for the page is /faq/search-results/.
$(".faq-search").keyup(function(e){
if(e.which == 13) {
window.location.replace("/faq/search-results/" + $(".faq-search").text());
}
});
Once the user has been sent to the search results page, I have a script which, if the user is on that url, is supposed to grab the search term from the pathname in the url, and submit it as a query parameter to the getJson request:
if(window.location.pathname == "/faq/search-results/"){
$("document").ready(function(e) {
var url = window.location.pathname;
var exp = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/);
var question = exp[5].split("/")[3];
$.getJSON("//search.url-to-search.com?q=" + question + "&results_type=faq", {
},
//Get results and make 'em look good
function(data) {
console.log(data);
$.each(data.data, function(i, data) {
if(data.type === "FAQ"){
$(".faq-results").append("<li class='result-item'><h3>" + data.title + "</h3><p class=\"content\">" + data.text + "</p><p class=\"category\">" + data.type + "</p></li>");
}
});
});
});
}
I believe the issue is that it won't fire off the request because its looking for only /faq/search-results/. I think I need a way to store the search term as a variable and pass it as a query parameter, but not sure how to accomplish this, as I believe it would make the variable out of scope.
A couple of things are wrong in your code:
first to collect the input value use .val() note text().
Secondly you are not passing the input value as a query string you are adding it to the url path /helloWorld. I think it is better to add as a query string ?q=helloworld.
I have therefore adjusted your code, removed your code to extract the text from the path and implemented a function to extract a named query param, this function is called getParameterByName.
The code below should be pretty much self explanatory.
$("document").ready(function(e) {
//
// Collects the input param as passes it as a query string note
// ?q= our string
//
$(".faq-search").keyup(function(e) {
if (e.which == 13) {
window.location.assign("file:///C:/Users/spydre/Desktop/text.html?q=" + $(".faq-search").val());
}
});
// snippet gets a query param from url
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// collect any query string param whos name is q
var question = getParameterByName("q");
if (question) {
// pass question to our getJson
$.getJSON("//search.url-to-search.com?q=" + question + "&results_type=faq", {},
//Get results and make 'em look good
function(data) {
console.log(data);
$.each(data.data, function(i, data) {
if (data.type === "FAQ") {
$(".faq-results").append("<li class='result-item'><h3>" + data.title + "</h3><p class=\"content\">" + data.text + "</p><p class=\"category\">" + data.type + "</p></li>");
}
});
});
} //if question
})
I like the way jQuery's $.ajax() method allows to specify request url:
{
url: 'http://domain.com/?param=1',
data{
param2: '2'
}
}
$.ajax() method will (probably) call $.param() on provided data and optionally append it to provided URL.
My question is: is this type of url manipulation available outside of $.ajax() call?
For example, I want to open a popup window, and I would like to construct URL in the same way that I do with $.ajax().
I have written a function which does this, but I have a feeling I am reinventing the wheel and duplicating already existing function of jQuery:
var prepareUrl = function( url, data )
{
var params = $.param( data );
if ( params.length > 0 )
{
// url contains a query string
if ( url.indexOf( '?' ) > -1 )
{
// get last char of url
var lastChar = url.substr( url.length - 1 );
// Append & to the end of url if required
if ( lastChar != '&' && lastChar != '?' )
{
url += '&';
}
}
else // url doesn't contain a query string
{
url += '?';
}
url += params;
}
return url;
}
thanks!
Since other replies didn't answer my question, i have made a few tests with the $.ajax() call to see how it merges urls with param data.
My findings so far:
if url contains a ?, then $.ajax() will append '&' + $.param(data)
if not, then $.ajax() will append '?' + $.param(data)
So if I want to keep my url processing function consistent with the way $.ajax() does it, then it should be something like the following:
var addParams = function( url, data )
{
if ( ! $.isEmptyObject(data) )
{
url += ( url.indexOf('?') >= 0 ? '&' : '?' ) + $.param(data);
}
return url;
}
I am still wondering if there is a built-in jQuery method to do this.
You can build query string like this:
getQueryStr = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
console.log(serialize({
param1: "val1",
param2: "val2"
}));
For recursive :
getQueryStr = function(obj, prefix) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push(typeof v == "object" ?
getQueryStr(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
console.log(serialize({
favfruit: "apple",
data: {
name: 'js',
points: [1, 2, 3]
}
}));
yes you can use jqueries .param() function to do this.
jsfiddle demo
var params = { param1:"foo", param2:"bar"};
var str = jQuery.param( params );
alert(str);
The param method will generate a query string for you, but you will need to to remove the existing query string.
var base = "http://example.com/foo/?example=old";
var data = {
foo: "hello",
bar: "world?"
};
var url = base.replace(/\?.*$/, "") + "?" + jQuery.param(data);
alert(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
As mentioned in this SO answer, just use URLSearchParams
let urlParams = new URLSearchParams(location.search.substr(1));
urlParams.set(key, value);
where key=value is new url parameter that you want to add
You could check the browser compatibility here
Is it possible to put a function into a parameter for Jquery Ajax like below. dataType and data are given as functions. dataType returns a value of JSON if the returntype is JSON and text if isJson is false.
dataVal and dataVar are arrays containing the parameter names and values used to construct the data paramater. The result of the data: function would be a string as:
{dataVar[0]:dataVal[0],dataVar[1]:dataVal[1],.....,}
I'm getting an error when I try this, so, just wanted to know if this method was possible.
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
},
data: function () {
var dataString = '{';
for (var i = 0; i < dataVar.length; i++) {
dataString = dataString + dataVar[i] + ':' + dataVal[i] + ',';
}
console.log(dataString);
return dataString + '}';
},
success: function (res) {
dfd.resolve(res);
}
});
}
Edit
As per answers and comments, made the changes. The updated function is as below. This works:
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: isJson ? "JSON" : "text",
data: function () {
var dataString ="";
for (var i = 0; i < dataVar.length; i++) {
if (i == dataVar.length - 1) {
dataString = dataString + dataVar[i] + '=' + dataVal[i];
} else {
dataString = dataString + dataVar[i] + '=' + dataVal[i] + ',';
}
}
return dataString;
}(),
success: function (res) {
dfd.resolve(res);
}
});
}
And my original question is answered. But apparently, data is not getting accepted.
The return value of the data function is just treated as the parameter name and jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
So, my server is unable to pick up on the proper paramater name.
From the manual:
data
Type: PlainObject or String
So no.
Call the function. Use the return value.
data: function () { ... }();
// ^^ call the function
Not that way. But it will work with a little change:
(function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
})()
That should work. You just call the function immidiately after you created it. This way, dataType is a String and the script will work.
Same with data. Also use the (function(){})()-notation here
jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
No, your devtools display does. However, as you're data string does not contain a = sign, and you send the content as application/x-www-form-urlencoded, the whole body is interpreted as if it was a parameter name.
For sending JSON, you should:
use contentType: "application/json"
use data: JSON.stringify(_.object(dataVar, dataVal))1
to ensure valid JSON is sent with the correct header (and correctly recognised as such at the server).
1: _.object is the object function from Underscore.js which does exactly what you want, but you can use an IEFE as well:
JSON.stringify(function(p,v){var d={};for(var i=0;i<p.length;i++)d[p[i]]=v[i];return d;}(dataVar, dataVal))
You need to call the function with parenthesis like below:
function func1(){
//func1 code in here
}
function func2(func1){
//func2 code in here
//call func1 like this:
func1();
}
So, you can use like this:
data: function () {
//your stuff her
}(); // which mean you are having data()
I'm using Javascript Object literals , but i can't concatenate string attributes.
var cart = {
baseURL : "http://www.domain.com/",
addURL : this.baseURL + "cart/add",
deleteURL : this.baseURL + "cart/delete",
totalURL : this.baseURL + "cart/total",
// functions
}// cart
i get a link as http://www.domain.com/undefinedcart/add
Please any help,
Thanks in advance
You don't have access to the baseURL in that way. Thats because this is actually window and it probably does not has property baseURL.
You can use Immediately-Invoked Function Expression (IIFE) and closure instead:
var cart = function () {
var baseURL = "http://www.domain.com/";
return {
addURL : baseURL + "cart/add",
deleteURL : baseURL + "cart/delete",
totalURL : baseURL + "cart/total"
};
}();
The problem isn't concatenation within the context of the object, it's that the this you're looking for doesn't exist yet. A simple solution might look like this:
var baseURL = "http://www.domain.com/";
var cart = {
baseURL : baseURL,
addURL : baseURL + "cart/add",
deleteURL : baseURL + "cart/delete",
totalURL : baseURL + "cart/total",
}
Or this:
var cart = new function() {
this.baseURL = "http://www.domain.com/";
this.addURL = this.baseURL + "cart/add";
this.deleteURL = this.baseURL + "cart/delete";
this.totalURL = this.baseURL + "cart/total";
};
The variable "this" is a instance of Window, so you can't use "this" as "cart"
How do you encode a javascript object/hash (pairs of properties and values) into a URL-encoded query string with YUI (2.7.0 or 3.0.0 Beta) ?
I want to do the equivalent of Object.toQueryString() from Prototype:
I need this to encode parameters for GET and POST requests with YAHOO.util.Connect.
It turns out YAHOO.util.Connect has a setForm() method to serialize a form but that still leaves me out cold to encode parameters for GET requests, or the 4th parameter of YAHOO.util.Connect.asyncRequest() to pass post data.
I've made this little helper for my own project.
var toQueryString = function(o) {
if(typeof o !== 'object') {
return false;
}
var _p, _qs = [];
for(_p in o) {
_qs.push(encodeURIComponent(_p) + '=' + encodeURIComponent(o[_p]));
}
return _qs.join('&');
};
// And to use it
var qs = toQueryString({'foo' : 'bar'});
YUI3 has the io-form module, which you can instantiate in your call the use. It allows you to write code like this:
YUI().use('node', 'io-form', function(Y) {
Y.get('#formId').on('sumbit', function(e) {
e.preventDefault();
Y.io(postURL,
{
method: "POST",
on: {
complete: on_complete_handler
},
form: {
id: "formId"
}
});
}
});
This code will make a POST request to postURL, with all the input values from the form with id "formId" is submitted. This module also works for GET requests.
I ended up using something like this based on some code found on github. The function must handle posting arrays..
"Y" is a reference to "YAHOO"
/**
* Turns an object into its URL-encoded query string representation.
*
* #param {Object} obj Parameters as properties and values
*/
toQueryString: function(obj, name) {
var i, l, s = [];
if (Y.lang.isNull(obj) || Y.lang.isUndefined(obj)) {
return name ? encodeURIComponent(name) + '=' : '';
}
if (Y.lang.isBoolean(obj)) {
obj = obj ? 1 : 0;
}
if (Y.lang.isNumber(obj) || Y.lang.isString(obj)) {
return encodeURIComponent(name) + '=' + encodeURIComponent(obj);
}
if (Y.lang.isArray(obj)) {
name = name; // + '[]'; don't do this for Java (php thing)
for (i = 0, l = obj.length; i < l; i ++) {
s.push(arguments.callee(obj[i], name));
}
return s.join('&');
}
// now we know it's an object.
var begin = name ? name + '[' : '',
end = name ? ']' : '';
for (i in obj) {
if (obj.hasOwnProperty(i)) {
s.push(arguments.callee(obj[i], begin + i + end));
}
}
return s.join("&");
}
I see YUILibrary Ticket 2528174 refers to an accepted contribution on for this.
The Querystring Utility
Provides static methods to serialize objects to querystrings and deserialize objects from querystrings.
Three modules are available:
querystring - Both parse and stringify functionality
querystring-parse - Parse valid querystring into JavaScript objects
querystring-stringify - Serialize JavaScript objects into valid query strings