JSON Post after fetching from Dropbox JavaScript Chooser - javascript

I'm using the Javascript Dropbox Chooser https://www.dropbox.com/developers/dropins/chooser/js and with the help of #smarx (How to display selected file name when using the Dropbox API JS Chooser) I've managed to fetch the <img src="" to fetch images into the browser.
The next thing that I want to do is to POST those image url's into a json file stored on my localhost as: galeria.json via $.ajax after the submit button is clicked, however, I can't seem to accomplish it.
I'm relatively new with jQuery and AJAX so I don't understand the error response that I get on my console: Error: [object, Object].
Here's the code:
<body>
<form class="gallery-form" action="galeria.json" method="POST">
<input id="chooser" type="dropbox-chooser" name="selected-file" data-link-type="direct" data-multiselect="true" style="visibility: hidden;"/>
<div id="chosen" style="display:none"></div>
<input type="submit" id="submit" value="Enviar" disabled />
</form>
<script>
$(function () {
$('#chooser').on('DbxChooserSuccess', function (e) {
for (var i = 0; i < e.originalEvent.files.length; i++) {
var url = e.originalEvent.files[i].link;
var filename = e.originalEvent.files[i].name;
var linkTo = "<img src='" + url + "'" + ">" + "</img>";
$('#chosen').show();
$('#chosen').append(linkTo);
}
$('#submit').prop('disabled', false);
$(".gallery-form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "galeria.json",
dataType: "json",
data: {imgUrl: url},
success: function(response){
console.log("Success: " + response.imgUrl);
},
error: function(error){
console.log("Error: " + error);
}
});
});
});
});
</script>
</body>
If you would like to help me a little bit more, the goal of doing this is to later GET those img url's from the galeria.json file into my index.html and insert them on a gallery <section id="gallery">.

What code are you running on the server to receive the JSON request? I suspect you're missing a piece here. Your code to send the URL to the server looks right, but that's not the only step required. On the server, you need some code that's going to receive the request and write the URL to a file.

You might want to store the urls in an array and then submit that to the server. Note that in the AJAX request I'm assuming you have a server that accepts post requests to the resource "/images".
<script>
$(function () {
$('#chooser').on('DbxChooserSuccess', function (e) {
var urls = [];
for (var i = 0; i < e.originalEvent.files.length; i++) {
var url = e.originalEvent.files[i].link;
urls.push(url);
var filename = e.originalEvent.files[i].name;
var linkTo = "<img src='" + url + "'" + ">" + "</img>";
$('#chosen').show();
$('#chosen').append(linkTo);
}
$('#submit').prop('disabled', false);
$(".gallery-form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/images",
dataType: "json",
data: {imgUrls: urls},
success: function(response){
console.log(response.message);
},
error: function(error){
console.log(error.message);
}
});
});
});
});
</script>
On the server side (Rails in my example since I know you have worked with it) you would process the array. JSON Data sent with an ajax request should be available in the params hash. The params[:imageUrls] would be the array of urls.
def create
params[:imgUrls].each do |url|
Image.create(path: url)
end
respond_to do |format|
format.html
format.json { render :json {message: 'Success!'} }
end
end

Related

Displaying the result of a GET request with JS and REST

I'm trying to get and display a field in a SharePoint list
using a Content Editor Web Part. This is just proof of concept, I want the CWP to display the Title (the currency) and the Currency Description. I think I just need a tweak and want to understand what I'm doing wrong. The var query URL displays the title fine.
Ultimately what I want to do is to store the returned value from the Exchange Rate column so that when a user selects a drop don in a separate list and an amount it will convert by the Exchange rate.
Any help is appreciated. Code below:
<script type="text/javascript">
DisplayExchangeRate();
function DisplayExchangeRate()
{
var listName = "Currency Exchange Rates";
var titleField = "Title";
var rateField = "Currency Description";
var query = "http://collaboration-dev.norgine.com/sites/it/Tools/IT- Contracts/_vti_bin/listdata.svc/CurrencyExchangeRates?
$select=Title,ExchangeRate&$filter=Title eq 'Dollars'";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function (i, result) {
$("#CurrencyExchangeRatesTitle").text(result.Title);
$("#CurrencyExchangeRatesCurrencyDescription").html
(result.CurrencyDescription);
});
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving Tips: " + jqXHR.responseText);
});
}
</script>
I don't believe you can put JavaScript directly in a Content Editor Web Part. Try using a Script Editor Web Part instead (housed in the same category of web parts as the CEWP), or pointing your CEWP to a local HTML page with the JavaScript.
http://info.summit7systems.com/blog/dont-script-in-the-wrong-web-part
Also, it looks like you're using JQuery. Do you have a reference to that library elsewhere that is loading successfully?
Below is my Working code , I have saved this code in a text file, and uploaded that file in "Site Assets" library and pointed my CEWP to this code file.
<script type="text/javascript" src="https://test.sharepoint.com/sites/devsite/SiteAssets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var i,result;
$('#getEmployee').click(function () {
var dispalyResults="";
$.ajax({
url: "https://test.sharepoint.com/sites/devsite/_api/web/lists/getbytitle('Employee')/items",
method: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data) {
var jsondata = JSON.stringify(data);
result = JSON.parse(jsondata).d.results;
for (i = 0; i < result.length; i++) {
dispalyResults+="<p><h1>"+ result[i].ID + " " + result[i].Title +"</h1></p>";
}
$('#displayResults').html(dispalyResults);
},
fail: function () {
alert("Response fails");
}
})
})
})
</script>
<input type="button" value="GET" name="GET" id="getEmployee"/>
<div id="displayResults"></div>
I have created a button and a DIV tag. When i click the button , it will display the list item Title and ID inside the DIV tag.

Uploading a file through AJAX with a Django Form

I've been trying to create a system that allows uploads of text and a file through my Django form. Whenever I try post the form I can only seem to get the message part of the form. I've been following this answer for reference but I've been running into trouble. First, my form looks like this:
class MessageForm(forms.Form):
message = forms.CharField(widget=forms.Textarea, required=False)
file = forms.FileField(label="Attachment", required=False)
and it's rendered to HTML like this:
<form id="message-form" enctype="multipart/form-data">
{{form.message}}<br>
{{form.file}}
<div class="sectio4-bottom">
<div class="right-bottom">
<input id="send-button" type="submit" value="Send"/>
</div>
</div>
</form>
The current version of my JS function I'm working with looks entirely like this:
$('html').on('submit', '#message-form', function(e){
e.preventDefault();
var data = new FormData($('#message-form').get(0));
$.ajax({
url: '#',
type: 'POST',
data: {
'data': data,
'csrfmiddlewaretoken': $('.csrftoken').text()
}
});
return false;
})
but the part I'm interested in is var data = new FormData($('#message-form').get(0));. I got this from the linked question but when it runs it gives me an empty object. I've also tried passing the data as 'data': $('#message-form').serialize() but when it gets to the backend and I look at request.POST I see that the only thing included in data is the message I send. request.FILES is empty.
How can I access the specified file?
Try adding:
data.append('file',$("#file").files[0]); #Assume 'file' is id of your file field
after
var data = new FormData($('#message-form').get(0));
Here an example function that I'm using
function saveVeichle() {
$(".sk-wave").show();
var dati = new FormData();
dati.append('csrfmiddlewaretoken','{{csrf_token}}');
dati.append('note',$("#note").val());
dati.append('dip',$("#dip-0").val());
dati.append('stato',$("#stato").val());
$("input").each(function(id,obj){
if (obj.type == 'checkbox') {
dati.append(obj.name,obj.checked);
} else {
dati.append(obj.id,obj.value);
}
});
dati.append('foto',$(".foto")[0].files[0]);
dati.append('libretto',$(".libretto")[0].files[0]);
$.ajax({
url: "/mezzi/api/salva_mezzo/",
type: "POST",
data: dati,
cache: false,
contentType: false,
processData: false,
}).done(function(data) {
if (data.res == 'ok') {
window.location = '/mezzi/' + data.id + '/';
} else {
if (data.errors) {
for (d in data.errors) {
noty_alert(d + ":" + data.errors[d]);
}
} else {
noty_alert('Errore Salvataggio Mezzo!');
}
$(".sk-wave").hide();
}
});
}

How to get user data from Javascript user back to Django

I'm using Django and Bootstrap to create a simple website.
In my .html file, I'm using Bootstrap to display a datepicker.
<div id="datepicker" ></div>
Also in the .html, I have some quick and dirty javascript code that gets updated when my datepicker gets clicked on.
<script>
function setup(){
<SOME OTHER JS>
$('#datepicker').on("changeDate", function() {
$('#my_hidden_input').val(
$('#datepicker').datepicker('getFormattedDate')
);
});
$(document).ready(setup);
</script>
I want to pass back this new date to my Django page. Basically I want to refresh the page with data pertaining to this new date, and my Django code knows how to handle the new date.
How should I do that? Should I redirect back to my current page, but add something to the URL so that Django's regex will pick it up? Or should I make it an Http GET with the new date?
<script>
function pass_this_to_backend(date){
$.ajax({
type: "POST",
url: "/get_date/",
data: { 'date':date },
dataType: "json",
success: function(response) { alert(response); },
error: function( rrror) { alert(error); }
});
}
function setup(){
<SOME OTHER JS>
$('#datepicker').on("changeDate", function() {
$('#my_hidden_input').val(
$('#datepicker').datepicker('getFormattedDate')
);
pass_this_to_backend(date);
});
$(document).ready(setup);
</script>
You can use Ajax to get data from server without page refresh:
jQuery.ajax({
type: 'POST',
url: 'web/path/to/php/file.php',
data: {
post_date: $('#datepicker').val() //this is the data to post to server
},
success: function(res) {
//code executed after server response. res - server response
$('#datepicker').append(res); //modifying your html
}
});
And in file.php for example:
echo $_POST['post_date']; //accessing your date on server side and return it
If you do need to refresh the page, you can send your data in url:
$('#datepicker').on("changeDate", function() {
var val = $('#my_hidden_input').val(
$('#datepicker').datepicker('getFormattedDate')
);
val = encodeURIComponent(val); //encode data for url passing
window.location.href = '?date = ' + val; //goto url with appended parameter
});
To get data you use:
$date = urldecode($_GET['date']);

populate drop down list with json

I am trying some stuff and populating drop down list with a json and javascript for some reason I am getting a console error when trying to populate
I am using Scripts/jquery-2.0.2.js
this is the error:
Failed to load resource: the server responded with a status of 404 (Not Found)
POST //localhost:9819/Home/Home/Test 404 (Not Found)
jquery-2.0.2.js:7858 send jquery-2.0.2.js:7858 jQuery.extend.ajax
jquery-2.0.2.js:7314 RetrieveData Index:45 (anonymous function)
Index:64 jQuery.event.dispatch jquery-2.0.2.js:4692 elemData.handle
This is the View Code:
<script>
$(document).ready(function () {
var Load = false;
function RetrieveData() {
if (Load == false) {
Load = true;
$.ajax({
url: <%= Url.Action("Test", "Home") %>
data: "{}",
dataType: "json",
type: "POST",
contentType: "application/json",
success: function (data) {
$("#selectMe").html(data);
Load = false;
},
error: function (data, status, jqXHR) {
alert("Error: " + data);
Load = false;
}
});
}
}
$(document).on("click", "#test", function () {
RetrieveData();
});
});
</script>
<input type="submit" id="test" />
<select id="selectMe"></select>
Controller:
public string GenerateHTMLforDropDownList(Dictionary<string, string> myData)
{
string HTMLString = "";
foreach (KeyValuePair<string, string> k in myData)
{
HTMLString += "<option value=\"" + k.Key + "\">" + k.Value + "</option>";
}
return HTMLString;
}
[HttpPost]
public JsonResult Test()
{
Dictionary<string, string> myData = new Dictionary<string, string>();
myData.Add("0", "Mike");
myData.Add("1", "Mark");
myData.Add("2", "Karl");
myData.Add("3", "Rhona");
return Json(GenerateHTMLforDropDownList(myData), JsonRequestBehavior.AllowGet);
}
any help of how I can fix this thanks
As the error states, the resource is not found. Look at the URL in the error:
http://localhost:9819/Home/Home/Test
Assuming you're not doing anything more custom, if you have a Test action on a Home controller then the URL should be:
http://localhost:9819/Home/Test
Notice also how you're specifying the URL in your code:
url: "Home/Test"
If you're currently at http://localhost:9819/Home/Anything then that relative URL says to look for a resource called Test in a "subdirectory" (using the word loosely) of the current resource. So there's your problem.
Instead of specifying the URL manually like that, use the Url.Action method in MVC. Something like this:
url: '#Url.Action("Test", "Home")'
This will generate a fully-qualified URL from server-side code regardless of where your current context is, so you don't have to adjust it based on the current URL or anything like that.
I have not done this in MVC but I've done this countless times in Web Forms and it looks like your URL might be the problem...
//localhost:9819/Home/Home/Test
In your ajax call you should probably adjust this line...
url: "Home/Test"
and make it look something like ...
url: <%= Page.ResolveUrl("~/Home/Test.asmx") %>
Sorry if this is way off base for MVC.
You need to change your button type to 'button' not submit as this is ajax call

Using javascript to access Google's URL shortener APIs in a Google Chrome extension

I am writing my first google chrome extension which will use Google's URL shortener api to shorten the URL of the currently active tab in Chrome.
I am a longtime sw developer (asm/C++) but totally new to this "webby" stuff. :)
I can't seem to figure out how to make (and then process) the http POST request using js or jquery. I think I just don't understand the POST mechanism outside of the curl example.
My javascript file currently looks like this:
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('chrome.browserAction.onClicked.addListener');
chrome.tabs.getSelected(null, function(tab) {
var tablink = tab.url;
console.log(tablink);
//TODO send http post request in the form
// POST https://www.googleapis.com/urlshortener/v1/url
// Content-Type: application/json
// {"longUrl": "http://www.google.com/"}
});
});
The easiest solution would be to use jquery's $.ajax function. This will allow you to asynchronously send the content to google. When the data comes back you can then continue to process the response.
The code will look something like this question
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL +'"}',
dataType: 'json',
success: function(response) {
var result = JSON.parse(response); // Evaluate the J-Son response object.
}
});
Here is the jquery ajax api
Update in Jan, 2016: This no longer works, as the link shortening API requires authentication now.
I wrote a blog post with a simple solution:
http://uihacker.blogspot.com/2013/04/javascript-use-googl-link-shortener.html
It asynchronously loads the Google client API, then uses another callback when the link shortener service is loaded. After the service loads, you'd be able to call this service again. For simplicity, I've only shortened one URL for the demo. It doesn't appear that you need an API key to simply shorten URLs, but certain calls to this service would require one. Here's the basic version, which should work in modern browsers.
var shortenUrl = function() {
var request = gapi.client.urlshortener.url.insert({
resource: {
longUrl: 'http://your-long-url.com'
}
});
request.execute(function(response) {
var shortUrl = response.id;
console.log('short url:', shortUrl);
});
};
var googleApiLoaded = function() {
gapi.client.load("urlshortener", "v1", shortenUrl);
};
window.googleApiLoaded = googleApiLoaded;
$(document.body).append('<script src="https://apis.google.com/js/client.js?onload=googleApiLoaded"></script>');
Here I will explain how to create a google url shortener automatically on every web page using javascript and html
Phase-stages are
1) Make sure you have a jquery script code, if there is already advanced to phase two.
2) Add the following script code, after or below the jquery script code:
<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>
3) How to use it:
If you want to use html tags hyperlink
<a id="apireadHref" href="blank">blank</a>
If you want to use html tag input
<input id="apireadValue" value="blank"/>
The end result
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>
HTML
<a id="apireadHref" href="blank">blank</a>
or
<input id="apireadValue" value="blank"/>
DEMO
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHf3wIv4T',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ "longUrl": "' + longURL +'"}',
dataType: 'json',
success: function(response) {
console.log(response);
}
});
Worked out a quick and simple solution on this issue. Hope it will solve the problem.
<html>
<head>
<title>URL Shortener using Google API. http://goo.gl </title>
<script src="https://apis.google.com/js/client.js" type="text/javascript"> </script>
</head>
<script type="text/javascript">
function load() {
gapi.client.setApiKey('[GOOGLE API KEY]');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("result").innerHTML = "";
var Url = "http://onlineinvite.in";
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': Url
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + Url + "<br>";
str += "<b>Test Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("result").innerHTML = str;
}
else {
alert("Error: creating short url \n" + response.error);
}
});
});
}
window.onload = load;
</script>
<body>
<div id="result"></div>
</body>
</html>
Need to replace [GOOGLE API KEY] with the correct Key
Your LongUrl should replace Url value i.e. http://example.com

Categories

Resources