Javascript JSON display hashtag symbol - javascript

I'm saving some data through the URL and one of these data elements is a text. I want to be able to save and store notes with hashtags on them. For example, I want to be able to save "I believe in #yolo", but when I save it (through php), and retrieve it again with javascript, I get "I believe in". Anyway, I can get that #yolo back? I tried using str_replace, but I may have gotten the regex wrong.
Thanks for all the help!
function dropsuccess() {
answerArray = [];
answerArray.id = Math.round(new Date().getTime() / 1000);
answerArray.text = document.getElementById("boglory").value;
$.getJSON("saveBlade.php?id="+answerArray.id+"&text="+answerArray.text,
function(data) {
if (data.hasOwnProperty("error")) {
alert(data.error);
} else {
$("#handle").animate({marginTop:"100%"},800,
function() {
document.getElementById("handle").style.display = "none";document.getElementById("bladecontainer").style.display = "none";$('#qod').fadeIn('medium');
});
}
});
}
answerArray.text includes the text that is being passed. Ex ("I believe in #yolo.") #yolo is a string, not a div-id tag.

The problem is that # is a reserved character in URLs to indicate a jump to an anchor.
You need to escape it. JQuery automaticly escape all characters that need to if you supply them as the data argument in the getJSON function:
$.getJSON("saveBlade.php",
{
id: answerArray.id,
text: answerArray.text
},
function(data) {
Look here for details

Related

How can I redirect with extra information in jquery?

I'd like to perform a redirect, but I also wish to send additional information along with it.
I've tried to change the value of window.location.href but that doesn't seem to pass along the extra information.
I also get how I can do
$.get(
new_url,
{data : "mydata"},
function(data) {
alert('page content: ' + data);
}
);
and that will display the html content of the new page, but that doesn't help with actually getting there.
How can I achieve this?
Edit: I feel as if I must be phrasing this terribly because I'm pretty sure this is an easy/common task. This shouldn't be something that would require cookies - it should basically be like a post request (I think).
You have a few different options for this:
URI Variables - You can append extra data to the URL by appending a question mark (?) followed by a set of key-value separated by an ampersand (=) with each variable being separated by an ampersand (&). For instance, http://www.google.com/search?q=javascript+url+variables&ie=UTF-8 gives you a link to a Google search for "javascript url variables" using UTF-8 encoding. Your PHP code or JavaScript would need to handle passing along and processing these variables. If using JavaScript a nice library for processing URLs is URI.js or using PHP you can use the parse_url and http_build_query functions. You can use this with window.location.href; for instance: window.location.href = "http://www.google.com/search?q=javascript+url+variables&ie=UTF-8" (replace the Google URL with the one you created or set in a variable).
Storage API - You can use the localStorage or sessionStorage properties to store and retrieve information using JavaScript (information is stored in the user's browser - supported by IE 8 and newer and all other major browsers). Note that this is JavaScript only unless you grab the data with JavaScript and pass it to your PHP server through URL variables, form, AJAX request, etc.
Cookie - You can store additional information inside a cookie - however this is more difficult since you have to setup your variables as a parsable string (possibly JSON) and remember to encode/decode the string when setting/getting the cookie. I don't recommend this method.
IndexedDB API - This is a more advanced client-side/browser storage mechanism and currently only supported in IE 10 and newer (and nearly all other browsers). There are also still changes being made to the standard which means newer versions of browsers could break current implementations or be buggy. If all you need is simple key-value storage (not an SQL-like database) then you should stick with one of the above options.
You can use the window open method to redirect your user,and remember to use "_self"
window.open('url','_self');
Preferably you'd store the data in localStorage and fall back to a cookie (I really like js-cookie).
Here are the two helper functions you need to store and retrieve data:
function setMultiPageData(itemName, data) {
var dataStr = JSON.stringify(data);
var hasLocalStorage = typeof localStorage !== 'undefined';
if (hasLocalStorage) {
localStorage.setItem(itemName, dataStr);
}
else {
Cookies.set(itemName, dataStr, { path: '/' }); // path set to root to make cookie available on any page
}
}
function getMultiPageData(itemName) {
var data = null;
var hasLocalStorage = typeof localStorage !== 'undefined';
if (hasLocalStorage) {
data = localStorage.getItem(itemName);
}
if (!hasLocalStorage || data === null) {
data = Cookies.get(itemName);
}
var parsedObject = null;
try {
parsedObject = JSON.parse(data);
}
catch (ex) {
console.log(ex); // remove in production
}
return parsedObject;
}
usage:
var data = { first: 'this is the first thing', second: 'this is the second thing' };
setMultiPageData('stackoverflow-test', data);
// go to a new page
var retrievedData = getMultiPageData('stackoverflow-test');
if (retrievedData === null) {
console.log('something went wrong')
}
else {
console.log(retrievedData); // { first: 'this is the first thing', second: 'this is the second thing' }
}

URL encoding giving errors when contacting API

I'm working on a school project where I'm trying to make a search function for The New York Times Article Search API.
I have a problem with one of their search filters as when I run the function I get error 400 as for some reason it can't read the url encoding. The fun thing is if I replace all the %3D's with = and the %26's with & in my own URL it works and I can see the API responds correctly.
if($('#date1').is(':checked')) {date="day_of_week&begin_date=18500101&end_date=19000101";}
if($('#date2').is(':checked')) {date="day_of_week&begin_date=19000101&end_date=19500101";}
if($('#date3').is(':checked')) {date="day_of_week&begin_date=19500101&end_date=20000101";}
if($('#date4').is(':checked')) {date="day_of_week&begin_date=20000101&end_date=20150101";}
$.getJSON('http://api.nytimes.com/svc/search/v2/articlesearch.json',
{'api-key': 'XXXXXXXXXXXXXXXXXXXXXXX',
'fq': 'headline:("'+sogestreng.toLowerCase()+'")'+" AND "+finalSections,
'facet_field': date},
This code returns "http://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=XXXXXXXXXXXXXXXXXXXXXXX&fq=headline%3A(%22dubai%22)+AND+section_name.contains%3A(%22Sports%2C+%22)&facet_field=day_of_week%26begin_date%3D20000101%26end_date%3D20150101"
While if I manually replace the last part of the url encoding and open it in my browser I get the result I'm looking for.
I do this by changing:
"&facet_field=day_of_week%26begin_date%3D20000101%26end_date%3D20150101"
to
"&facet_field=day_of_week&begin_date=20000101&end_date=20150101"
Also to clarify, the "fq" criteria works perfectly fine, it's just the facet_field.
How can this be? And is there any fix for it?
You're shoving the description of several fields into one field's value. To get the results you want, try:
var begin_date, end_date;
if($('#date1').is(':checked')) {
begin_date = 18500101;
end_date = 19000101;
}
else if($('#date2').is(':checked')) {
// etc.
}
$.getJSON('http://api.nytimes.com/svc/search/v2/articlesearch.json',
{
'api-key': 'XXXXXXXXXXXXXXXXXXXXXXX',
'fq': 'headline:("'+sogestreng.toLowerCase()+'")'+" AND "+finalSections,
'facet_field': 'day_of_week',
'begin_date': begin_date,
'end_date': end_date
},
// ...

Name Game Social Share

I am working on a Name Game type of Name Generator where you enter some fields and associated variables are pulled. I have the generator working and the share links working, however I can't get them to populate with the final 'sillyname' variable.
AKA When you click share, it has a generic message but I am trying to get it to dynamically enter the name into the tweet or facebook share text.
Any help on this would be awesome.
Here is the link for you to dig deeper.
http://codepen.io/drewlandon/pen/VLvpjq
I have this in the twitter/facebook share function:
var twitterWindow = window.open('https://twitter.com/intent/tweet?url=http://sweetleafmarijuana.com/&text=My Sweet and Fierce Name... &via=TheSweetestLeaf &hashtags=SweetFierceName', 'twitter-popup', 'height=350,width=600'); if(twitterWindow.focus) { twitterWindow.focus(); }
return false; } var facebookShare = document.querySelector('[data-js="facebook-share"]');
However I found this and feel like it needs to be something along these lines:
function twitterShare(){
var shareText='My funny pseudonym is '+accents_to_regulars(outputName)+', according to #...'
So i'm thinking i need something like this (but having trouble from there)
var twitterMessage = "My #SWEETFIERCENAME is " + hungryName + ", according to #thesweetestleaf's #SweetFierceName Name Generator";
var facebookMessage = "My name is " + hungryName + "";
You need to escape the text for the URL.
It works here: http://codepen.io/anon/pen/Kpdvqa
twitterShare.onclick = function(e) {
e.preventDefault();
var twitterWindow = window.open('https://twitter.com/intent/tweet?url=http://sweetleafmarijuana.com/&text='+encodeURIComponent(getSillyName())+'&via=TheSweetestLeaf &hashtags=SweetFierceName', 'twitter-popup', 'height=350,width=600');
if(twitterWindow.focus) { twitterWindow.focus(); }
return false;
}
The # character has special meaning in URLs.
As for the Facebook message, there is no way to pre-fill that anymore:
http://www.quora.com/With-Facebooks-share-link-is-there-a-way-to-prefill-the-text-to-be-posted
You will have to take a closer look at the FB Feed Dialog to see other options, like perhaps updating the caption property instead.

Get a specific string from Url

I know it may sound as a common question, but I have different variables here:
I have an Url like this one:
https://www.facebook.com/events/546604752058417/?suggestsessionid=791e61ca005570613fa552635bc794a5
Now I need to get the number 546604752058417. So logically I should get all what is after events/ but all what is after the first slash after 546604752058417
Now the problem is that the Url may or not start with http, https, www, etc..
I am a little lost and new to Javascript.
What's the simple way to do it?
I have a function that check if the Url is valid and it is from Facebook, but I don't know now how to get that 546604752058417.
Obviously this is only a sample. The function should be able to work with any event id.
function fbProcessSearch() {
var search_url = $("#search_fb_url").val();
if(isFbUrl(search_url)) {
$("#search_fb_event").validationEngine("hide");
// gets the event id from the Url and passes it to the below function.
fbProcess(eid);
}else{
$("#search_fb_event").validationEngine("showPrompt", "Please enter the Facebook event Url", "load", "topLeft", true);
}
}
function isFbUrl(url) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/
return regexp.test(url) && url.indexOf("facebook.com") > -1;
}
Use .match with this regexp: /events\/(.*?)\//
"https://www.facebook.com/events/546604752058417/?suggestsessionid=791e61ca005570613fa552635bc794a5".match(/events\/(.*?)\//)[1]
=> "546604752058417"
Explanation:
events\/ -> Match "/events/" literally
(.*?)\/ -> match anything until first "/" and also capture it
if you know how the url is going to look and can confirm it's facebook. then .split("events/")[1].split("/")[0] to get the code between /events/######/
you can start by "spliting" your url with "/"
var search_url = $("#search_fb_url").val().split("/");
and then you take the field after the one containing "events" ....

Ajax in Dojo with Perl

Anyone can tell me what I'm doing wrong?
I am creating a simple system to get people in and out of user groups and for that purpose I am using Dojo and Perl. (If I could have it my way it would be PHP but I am not the boss.)
At the moment I only use three files, one for Perl, one for JavaScript and one for CSS styles.
The start of the CGI script routes to different functions as follows:
if ($search = $cgi->param('psearch')) {
dbConnect();
jsonSearchPersons($search);
dbDisconnect();
} elsif ($user_id = $cgi->param('person')){
dbConnect();
create_form($user_id);
dbDisconnect();
} elsif ($user_id = $cgi->param('saveuser')) {
save_user();
} else {
mainPage();
};
...
sub save_user {
print $cgi->header(-type=>'text/plain',-charset=>'utf-8');
print("success");
}
The problem I have now is when I want to save the new groups for the user though an Ajax call (a call to this URL: users.cgi?saveuser=xx). This should (in my point of view) be a POST call, so I made this and tried to append the resulting HTML/text in a <div> but it didn't work:
dojo.xhr.post({
url: "/cgi-bin/users.cgi?saveuser="+user_id,
content: {
new_groups: group_ids.toString()
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
When I do it with dojo.xhr.get(); it works fine, but when I do it with the POST it's like it jumps over that part of the if statement and just appends the mainPage() function. Is there something basic I don't understand between Dojo and Perl? Do I have to set up the pages so it will accept a POST call? Or what am I doing wrong?
NOTE: This is the first "system" I have made though Dojo and Perl. (I'm normally a PHP/jQuery kind of guy who makes everything UI by hand, so I'm kinda new to it.)
Try adding the saveuser-parameter to the content-object of dojo.xhrPost instead of passing it in the url.
You're trying to pass the saveuser-parameter as GET and the other as POST, maybe that confuses your serverside part.
Try it like that:
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
content: {
new_groups: group_ids.toString(),
saveuser: user_id
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
Found a solution.
The problem was my javascript. When posting to a perl script you use $cgi=new CGI; and all that. This takes both GET and POST variables and validates them. In my javascript/dojo code, i then used an url with GET vars and then made a POST as well. This meant perl could not find out (or was mixing) the two variable types. So when i changed my ajax code (as below) it worked, since $cgi->param('saveuser') both fetches GET and POST of "saveuser" (no change to the perl was needed):
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
content: {
saveuser: user_id,
new_groups: group_ids.toString()
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
Kinda wack bug, but im glad since it works great now :D
Line 675 of CGI.pm :
# Some people want to have their cake and eat it too!
# Uncomment this line to have the contents of the query string
# APPENDED to the POST data.
# $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
Made me laugh !

Categories