Github Gist: New Lines? - javascript

I'm trying to create a gist with multiple lines of content but not sure the best way to go about it. \n isn't working and neither is adding two empty lines. It shows up as a single line of text.
var content = 'content on\nnewline here';
$.ajax({
url: 'https://api.github.com/gists',
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "token TOKEN-HERE");
},
data: '{"description": "a gist for a user with token api call via ajax","public": true,"files": {"file1.txt": {"content": "' + content + '"}}}'
}).done(function(response) {
console.log(response.id);
});
How do I change the content variable to contain newline characters? I want the output to eventually show up as a .txt so I don't think I can change the media type? Thanks.

This is just a guess, but it might be because you're JSON-ifying manually, and the \n isn't being escaped properly. Try using JSON.stringify:
JSON.stringify({"description": "a gist for a user with token api call via ajax","public": true,"files": {"file1.txt": {"content": content }}})

Related

Ajax post breaks with special characters

I am trying to pass the value of a textarea to an php page to then be processed and added to a SQL database.
I want the text area to be able to support special characters.
Everything works fine till I put this string in the text area and post it:
JΛ̊KE#2##&($^#%###%))$&#("""
I am getting a 501 Not implemented error.
Now when I paste in certain PHP code into the text area (not to run, purely to save as a string), I get a 403 Forbidden error.
Why does the value of the text area affect the error code?
For now, the paste.php file has no code so that I could try and understand where the error is coming from. I am certain the error is coming from the ajax post. I've looked everywhere online but have not been able to find how to make the string safe to post. encodeURIComponent doesn't seem to work in this case.
Here is the JS for the button press:
var note = $("#note").val();
var dataString = encodeURIComponent(note);
$.ajax({
type: "POST",
url: "php/paste.php",
data: JSON.stringify({
paste: dataString
}),
dataType: 'text',
contentType: "application/json; charset=utf-8",
success: function(msg) {
alert(msg);
console.log(msg)
},
error: function(ts) {
alert(ts.responseText)
}
});
try adding this
Content-Type: application/x-www-form-urlencoded
What was needed was to use this function on the data.
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
Change the content type to
ContentType: "application/x-www-form-urlencoded; charset=UTF-8"
and for the kicker, add this to my .htaccess file :
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>

How do I send the operator "&" via an Ajax query?

I'm currently using the following ajax function to send ajax queries.
$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function (htmltwo) {},
error: function (htmltwo) {}
});
The problem is when i send the text which include the operator "&", the items on the right of the operator is deleted. The following is my dataString.
var dataString = 'id=' + id + '&dateoccur=' + dateoccur + '&timeoc=' +
timeoc + '&hitype=' + hitype + '&hid=' + hid;
So e.g if hid is text containing "EEEE&LLLLL", the items on the right of & will be removed when receiving it on the server side. So on the server end, will receive "EEEE". I assume ajax recognizes this because it's part of the dataString variable. How would I be able to solve this issue ?
You could use encodeURIComponent in Javascript to encode characters such as & and then decode them back at the server.
var hidValue = "EEEE&LLLLL";
var hidValueEncoded = encodeURIComponent(hidValue);
console.log(hidValueEncoded);
I always recommend using an object rather than a string. jQuery will then automatically encode everything properly.
var dataString = {
id: id,
dateoccur: dateoccur,
timeoc: timeoc,
hitype: hitype,
hid: hid
};
It's also much more readable, IMHO.
But if you really want to build the string yourself, use encodeURIComponent as in Nisarg Shah's answer. You should do this for all parameters, unless you're sure they don't contain any special characters.

Javascript / jQuery / AJAX - Request string from website

I'm trying to create a function, using an API, to get the definition in french of a word.
I'm using this API:
"http://www.igrec.ca/project-files/wikparser/wikparser.php?word="
+ word +
"&query=def&count=1&lang=fr"
This url returns one definition in plain text of the word entered.
e.g: http://www.igrec.ca/project-files/wikparser/wikparser.php?word=manger&query=def&count=1&lang=fr
How does one manage to get this text? I looked at similar questions, some mention Ajax / xmlHttpRequest but I'm pretty lost.
Thanks
P.S: I don't mind using jQuery or some other technics as long as I understand what I'm doing.
The basic jQuery AJAX call can be done like this ... (using your data).
$.ajax({
type: "GET",
url: "http://www.igrec.ca/project-files/wikparser/wikparser.php",
dataType: "text",
data: {
word: word,
query: "def",
count: 1,
lang: "fr",
},
success: function(data) {
// Do something
}
});
Basically, you are performing a GET, at the URL.
The data type you expect back is text.
The data gets "transformed" into the url format from your question, then there is a success function to handle the data received.

How can I get a value from another webpage and store it as a variable?

I am using graphite to get stats and want to render a justgage gauge for a variable. Graphite can spit out values using either json:
[{"target": "snmp.ssbSubstation.realEnergy.1", "datapoints": [[4511552439.0, 1417540920]]}]
or raw:
snmp.ssbSubstation.realEnergy.1,1417540860,1417540920,60|4511552439.0
That's the entire one line of the source returned depending on if you specify either json or raw. The url is formatted like http://<graphite server>/render?target=snmp.ssbSubstation.realEnergy.1&format=raw&from=-1min
Either way, I'd like to grab 4511552439.0 and set it as the value for the gauge and render in in a html panel in grafana. Is there a very simple way to do this?
You can do this with an JSONP ajax request. Please have a look at the example below (as a starting point for your app).
You can find the same demo also as jsFiddle here.
Maybe the data access could be done better. The two dimensional access looks a bit strange but it works.
I've used mocky.io to simulate your data.
// data format [{"target": "snmp.ssbSubstation.realEnergy.1", "datapoints": [[4511552439.0, 1417540920]]}]
// http://www.mocky.io/v2/547df7d558eb49190856a759
(function ($) {
var url = 'http://www.mocky.io/v2/547df7d558eb49190856a759'; // mocky.io demo source
var jsonCallback = function (data) {
var gauge = data[0].datapoints[0][0];
console.log(gauge);
$('#data').html(JSON.stringify(data, null, 2));
$("</p>").text('value for gauge ' + gauge).appendTo('#data');
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>

Using '&' in ajax form submit

I am submitting a form using .ajax().
The current script contains:
data: dataString,
dataString contains:
var list = $('.listsummary').val()
The class listsummary belongs to a textarea which users fill in,
or will be (partially) filled in dynamically through a different script.
The problem is that users nearly all of the time use the '&' sign, for example:
Potato & Patota blah blah blah
This screws up the dataString allowing to post everything written before the first '&' is found.
How can I achieve that the var list will be properly sent to the PHP handler in order to store the entire textarea content into the database WITH the use of '&'?
You can encode the string with encodeURIComponent()
var list = $('.listsummary').val();
var urlEncoded = encodeURIComponent(list);
You have 2 options. Either pack the data as an object:
data: { list: $('.listsummary').val() }
Or encode the URI components:
var dataString = "list=" + encodeURIComponent($('.listsummary').val());
Welcome to the world of injections. This is a simple problem, but there are multiple approaches that you can take:
If your data is simple unstructured text, you should set contentType to text/plain or application/octet-stream:
$.ajax({
....
data: "Hello & world",
contentType: "text/plain",
...
});
If your data is key values structured, then you should encode your data as application/x-www-form-urlencoded. This can be achieved in JQuery by passing a JavaScript key-value object to data:
$.ajax({
....
data: { text: "Hello & World", location: "Boston" },
...
});
If your data has more complex structure, you should encode your data in the most appropriate Content Type (e.g. JSON, XML, CSV) and set contentType to (e.g. "application/json", "application/xml", "text/csv")
$.ajax({
....
data: JSON.stringify(["Hello & world", {"Hello & World"}]),
contentType: "application/json",
...
});
--
On the PHP side, if you need to process anything other than application/x-www-form-urlencoded, you'll need to read the request body directly as a string. Which can be fine with this code:
$body = file_get_contents('php://input');
Or if you have PECL:
$body = http_get_request_body();
If you use a web framework, they probably also have ways to process custom content types. Check the documentation of your web framework.

Categories