I have a Python script, which does some computations and makes a figure. Then, I am using mpld3 to generate an HTML version of this figure and save it (e.g., figure.html). The Python computations are launched via the AJAX request to the HTTP server. In my JS file, I use the jQuery.load() method to insert the plot into HTML:
$("#includedContent").load('/figure.html');
In this way, everything seems to work fine. The question is can I do the same thing without saving the figures? I tried to return a figure as a response, here is my modified AJAX request:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/main.py",
data: JSON.stringify({ 'sim_dur': input }),
success: function (response) {
figure = response.figure;
var child = document.createElement('div');
child.innerHTML = figure;
child = child.firstChild;
document.getElementById('includedContent').appendChild(child);
}
});
If I assign an HTML-like string to child.innerHTML, the code works correctly. But when I try to assign it a figure (which has a string type as well), it is not showing on the HTML page. I'm new to JS, so I apologize if it is something basic. I did some research and it seems that people usually save the results in other answers, so maybe it is a common way to do it and what I am trying to do is not right.
In my experience, mlpd3 will only work when the client (browser) is loading the page. Once the page is loaded, updating or creating an mpld3 figure using an ajax call won't create the figure for you. I personally struggled with that for some time and then gave up. I am sure one can patch things up but then you'll be stuck to your own mpld3 patched version
Related
I have a variable within a laravel PHP page, held within Javascript. I currently print / output this as:
${data.id}
I now want to connect to PHPMyAdmin to check to see if the ID is within a table. However, I realise I can't use the ID number in PHP - as this is done on the server side and JS on the client side. A little stuck.
Unfortunately, I'm on a shared hosting package so node.js isn't a solution I can use.
Any help would be great! I think I can use AJAX, but unsure on how this would look.
here the AJAX sample.
$.ajax({
method: "POST",
url: "some.php",
data: { id: data.id}
})
.done(function( response) {
console.log(response);
//TODO:process your response here if receive response from php file.
});
I'm writing a small ASP.NET MVC site which also includes a WEB API in it that I wrote.
I've configured the project on my local IIS as http://localhost/mysite
On the main page of my site I'm including a js script that I wrote:
<script src="#Url.Content("~/Content/js/home.js")"></script>
on the page ready event of that js I call:
$.ajax({
url: 'api/getdetails',
accepts: 'application/json',
cache: false,
type: 'GET',
success: function (data) {
alert(data);
}
});
when looking with Fidler I see that the page call returns a 404 since it doesn't try to load it to the relative path I'm in (http://localhost/mysite) and it tries to load the root of the server - so the call looks like this http://localhost:80/api/getdetails
when I was writing web forms I used to do ajax calls such as this all the time and it always worked.
what am I missing?
Thanks
What I ended up doing is in my layout html I've added a js var:
var baseUrl = '#Url.Content("~/")';
then on my ajax call I've added that base url:
$.ajax({
url: baseUrl + 'api/getdetails',
accepts: 'application/json',
cache: false,
type: 'GET',
success: function (data) {
alert(data);
}
});
this does the trick no matter how the page looks like. even if I navigate to http://localhost/mysite/home/index
It's probably not the perfect solution, and I definitely think the old webforms way which worked was better - but I guess there are pros and cons to any technology.
Still would be happy to hear if someone has a better solution. for now - this does the trick.
When you navigate to
http://localhost/mysite
The behavior is a little different from
http://localhost/mysite/
Try that to confirm. Without the trailing slash, the "mysite" looks like a document name, not a folder, so relative paths would form from the root of the server.
What you may need to do is pass in the site content URL into your home.js and form absolute paths from it in your code.
I'm using Laravel 3, and I am AJAXing in a user comment. We are adding images to this comment and I can't seem to get the File Data to go through. When I set processData to false, I am also unable to access the other data such as the comment and privacy. Any insight?
var commentforms = $('form.compose');
commentforms.on('submit', function(e){
e.preventDefault();
var file = document.getElementById('file_input').files[0];
$.ajax({
type: 'POST',
url: '/issue/comment/' + issue_id,
processData: false,
data: {
side: side,
comment: comment,
privacy: privacy,
file: file,
},
success: function(response){
console.log(response);
new_comment = comment_template(response);
updateSide(new_comment);
},
});
Going off of what Kevin B commented, there are a couple ways to do this.
First, the reason it is not working is that, by default, you cannot send files with an AJAX request. That is it, and that is why it isn't working. No matter what you do to your form and your AJAX request, you are stuck. (AJAX here meaning NOT XMLHttpRequest2)
SOLUTION 1
Kevin B recommended the Javascript formData object which is part of the XMLHttpRequest Level 2. Information on how to use it can be found: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
In relation to your code, you code do something along the lines of:
commentforms.on('submit', function(e){
e.preventDefault();
var oData = new FormData(document.forms.namedItem("composeForm"));
var oReq = new XMLHttpRequest();
oReq.open("POST", '/issue/comment/' + issue_id, true);
//on a side note, issue_id isn't declared anywhere...
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
console.log("Uploaded!");
} else {
console.log("Error " + oReq.status + " occurred uploading your file.");
}
};
oReq.send(oData);
});
PROBLEM
Again, as Kevin B said, it isn't widely supported. Checking here: http://caniuse.com/xhr2 you can see that IE9 and below isn't supported, which is XP, Vista, and non-upgraded Windows 7. If your app is on your own controlled network, and you can ensure everyone is using Firefox/Chrome/IE10+, you are good to go. If you are going to be using this feature with the public, then you need another solution.
OTHER SOLUTIONS
Many sites currently use AJAX to upload files, or trick you into thinking it is AJAX. What other websites do is one of two things: hidden iFrames or Flash.
The hidden iFrame trick is to create an iframe that populates the data of your current form, and then sends it off like it normally would, meaning a page reload. Because it is in an iFrame and hidden, the user never sees the page reload and the content is uploaded like you would expect.
The Flash trick is to use a little Flash app/plugin that finds the file and then sends it to your server. It is fairly easy to use, and since Flash is widely supported, it can do the trick on most browsers. You just have to include the plugin and you are good to go.
Plugins
I prefer to use plugins, as they do all the hard work for me. The one I am fond of right now for it's simplicity is Fine Uploader. It is easy to configure, looks great, can be Bootstrapped, or used with jQuery. Plugins may use one or both methods to upload the files, or they may even try the XMLHttpRequest2 first, then fall back on one of the other methods to upload the files. Ultimately, most of the popular plugins are easy to configure and provide fairly decent documentation to get it to do what you want.
Other popular plugins:
Uploadify
BlueImp
Plupload
read this:
With XHR2, File upload through AJAX is supported. E.g. through
FormData object, but unfortunately it is not supported by all/old
browsers.
Try with this:
Tutorial
And see this code:
var data= new FormData();
data.append( 'file', $('#file') );
$.ajax({
url: 'file.php',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(response){
console.log(response);
}
});
Suerte!
I am attempting to teach myself some JQuery/REST/Google API by putting together a simple page that does the following:
Authenticates with Google
Validates a token
Gets a list of Google Calendars for the user
List events for a selected calendar
Add an event for a selected calendar
I have #1 through #4 working (although no doubt in an ugly manner), and am getting tripped up on #5. Here's the JQuery ajax call:
var url = 'https://www.googleapis.com/calendar/v3/calendars/[MY_CALENDAR_ID]/events?sendNotifications=false&access_token=[GOOGLE_API_TOKEN]';
var data = { end: { dateTime: "2012-07-22T11:30:00-07:00" }
, start: { dateTime: "2012-07-22T11:00:00-07:00" }
, summary: "New Calendar Event from API"
};
var ajax = $.ajax({ url: url
, data: data
, type: 'POST'
}).done(addEventDone)
.fail(function (jqHXR, textStatus) {
console.log("addEvent(): ajax failed = " + jqHXR.responseText);
console.log(jqHXR);
});
The results are a global parseError: "This API does not support parsing form-encoded input.". The first four steps are all using GET ajax calls, so I'm not sure if that is what is tripping me up.
Here's the API in question: https://developers.google.com/google-apps/calendar/v3/reference/events/insert
I think I may be doing things the long and hard way, and my new approach is to tackle this using the javascript API instead of going straight at it with manual JQuery and REST. This is the approach I am attempting going forward http://code.google.com/p/google-api-javascript-client/wiki/Samples#Calendar_API, although I would still love to use this as a learning opportunity if there is something simple I am screwing up in the code above.
Thanks for any help, insights, pointers, etc. I will post updates if I make any progress using the javascript API.
Interestingly, I just answered a similar question here. Your intuition to use Google's JS client library is a good one. It's going to handle OAuth 2 for you, which is a requirement if you're going to do any manipulation of the Calendar data.
My other answer has both a link to a blog post that I authored (which demonstrates configuration of the client and user authorization), as well as an example of inserting a Calendar event.
you need to set contentType: "application/json", to do JSON.stringify for your data and method : 'POST'
var ajax = $.ajax({
url: url,
contentType: "application/json",
data: JSON.stringify(data),
method : 'POST',
});
I currently have the following within my view
function loadData() {
var url = "/Testx.mvc/GetData";
var id = "111111";
var format = "html";
$.ajax({
url: url,
type: "POST",
dataType: format,
data: "id=" + id,
success: populateResults
});
}
function populateResults(result) {
$('#results').html(result);
}
I also have a controller called TestxController with an action method called GetData(int? id).
Now the ajax call above works on Visual Studios 2008's built-in development server, but when i switch it to use IIS webserver it doesn't. It seems like the route isn't being found because I tried putting a break point on GetData but it doesn't even reach there.
Does anyone know what i would need to do to fix this?
Edit: I've also tried the wildcard mapping method discussed at http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx and it worked perfectly. (Of course I had to remov the .mvc from the url)
Is there any way to get this to work with the .mvc extension?
Thanks
Is Testx.mvc at the root of your webserver? If your application is running in a virtual directory on IIS then the correct path would be something like /YourApp/Testx.mvc/GetData.
The Visual Studio built-in webserver might be placing Testx.mvc at root, which is why it works within VS.
If that is the case, then try using the relative path Testx.mvc/GetData rather than /Testx.mvc/GetData.
Is there an actual function called 'callback'? Just asking because it seems like you might mean to be calling 'populateResults' with a successful response.
Try this perhaps:
$.ajax({
url: url,
type: "POST",
dataType: format,
data: "id=" + id,
success: function(results){$('#results').html(result)}
});
Did you check your ISS setup to see if it supports the POST action? It might only be specifying the GET action... see http://haacked.com/images/haacked_com/WindowsLiveWriter/07de283cb368_B754/application-mappings_3.png