there is any sample showing how to use the blobstore api with ajax?
when i use forms works fine, but if i use jquery i don't know how to send the file and i get this error:
blob_info = upload_files[0]
IndexError: list index out of range
I have this code in javascript
function TestAjax()
{
var nombre="Some random name";
ajax={
type: "POST",
async:true,
//dataType:"json",
url:"{{upload_url}}",
data:"nombreEstudio="+nombre,
error: function ()
{
alert("Some error");
$("#buscando").html("");
},
success: function()
{ alert("it's ok") }
};
$.ajax(ajax);
}
When i use forms the file it's sended with a input tag (exactly like the doc's sample)
I wrote a series of posts about exactly this.
Somehow you still need to get the multipart form data request to the server... so when you're using forms, I assume your <form> tag has something like this on it: enctype="multipart/form-data", right?
When you're just sending a "POST" via ajax, you're losing that multipart request, which is where your file is.
There are some jQuery "ajax file upload" plugins out there that may help you out.
Hope this helps!
** EDIT **
I guess one thing I can add to this is usually ajax file uploads (on the client) are implemented by either creating a hidden iframe, and using that iframe to submit a form, or using a form and posting it via JavaScript.
Related
This post by #BenjaminRH (How to change/edit the text of a paragraph/div using jQuery?) provides exactly the sort of functionality I'm trying to build on.
By clicking on a button, a new paragraph is created on the page, which can be edited and saved to the page.
I want to save it to a database. When I look at the page source after editing, I don't see the changes there, which doesn't surprise me... but I don't know where to "capture" the changed text so that I can validate and post to mySQL.
JQuery is a javascript library - which runs client side. If you wanted to save that data into the database - you would have to send it to the server (php/asp/mvc etc) using ajax and then insert the data into the database.
See the jquery Ajax function for details on how to accomplish sending data asynchronously.
Create the data in javascript that you want to show and save in database.
Wrap the data in JSON and use ajax to POST the data to the server side code
Server-side retrieve the posted data and parse it into something usable
Server-side write a script to insert the data into the database.
Handle any errors that may occur.
Pseudo-code:
// step 1
var someData = 'this is my data';
$("#myDiv").html(someData);
// step 2
$.ajax({
type: "POST",
dataType: 'json', // <-- if the data is complex and needs to be object-oriented
url: "some.php", // <-- that is the file that will handle the post server-side.
data: JSON.stringify({ someData }) // <-- just pass someData if your data is not complex
})
.always(function(jqXHR, textStatus) {
if (textStatus != "success") {
// step 5: handle error.
alert("Error: " + jqXHR.statusText); //error is always called .statusText
} else {
alert("Success: " + jqXHR.response); //might not always be named .response
}});
OK, I've managed to solve it for myself, without using ajax. I took the example from (How to change/edit the text of a paragraph/div using jQuery?) and modified it by placing the elements in an (html) form.
The second modification was to use <textarea> elements, not <p> elements, as <p> elements cannot be posted.
As #caspian pointed out (in the comments) those two steps do populate the $_POST array and away we go.
I'm trying to create a javascript api to take a word doc as input from the server side (say A) and post it to another api (say B) that will convert it to pdf. The reason I'm doing this is so that i can use the call to B against any A instead of having to modify each of the A APIs (there are multiple As that give word docs).
This is what I have done so far. The problem is when I'm calling B I'm not able to get the file that i'm sending.
Here's my code.
javascript call to server.
$("#downloadFile").click(function(){
$.ajax({
url : "/fileDownload.action",
success : function(data){
handleFile(data);
}
});
});
});
function handleFile(inputFile){
$.ajax({
url : "/convertFile.action",
type : "POST",
data : {inputFile : inputFile },
cache:false,
processData:false,
contentType: "application/msword",
success : function(data){
alert("yay?");
}
});
}
On my server side (a struts 2.3 action class) for "/convertFile.action", I have a setInputFile(File inputFile) method to set the file from request. However, it is not setting the file.
Now if I use a standard file upload with a form in HTML it sets the file (no javascript though, just plain html and server side code).
Also If I try to construct a form and post without an ajax call, I still get the same result. I tried to use the js in this answer to post the form.
What am I doing wrong? One possibility is that I need to take the input as a string or a stream. But is there anything else that I'm doing wrong/violating/can't do?
I have a basic form with some input fields. I want to save the form data into a json file on submitting the form.
The format of the saved data in the json file should be like this.
[
{"title":"some text","description":"some text","info":"some text","username":"some name"},
{"title":"some text","description":"some text","info":"some text","username":"some name"},
{"title":"some text","description":"some text","info":"some text","username":"some name"}
]
I tried doing this by using this code, but no data is saved in my 'story.json file'
$('form').submit(function() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'story.json',
data: $(this).serialize(),
success: function(data) {
alert(data.message);
},
failure: function (data) {
alert('Please try again');
}
});
});
I want to save this form data on my local file.
Please help me to find the correct way of doing this. Thanks
You need to post data to a simple php file...
like url: 'story.php'
In that php file create a 'story.json' using fopen and store that json
EDIT: if you want to use serialize() than use someting like this
data:{'mydata':$(this).serialize()}
and in php file
parse_str($_POST['mydata'],$newarray) ;
echo json_encode($newarray);
JavaScript cannot save to a file unless it's a FireFox plugin.
What you do is post a form (sent it to the webserver) then let server side script handle it.
Serialize does not turn the form values into a JSON string:
http://api.jquery.com/serialize/
And when you use $.post then you have to return false in the $('form').submit(function() or the browser will submit the form for you.
Submitting a form is when you click a button and the whole page goes white for a moment and then you get a new page.
Ajax ($.post, $.get, $.getJson ...) is when you send information to the server without refreshing the page. Google maps is an excellent example.
Calling the serialize method on the form jQuery object does not return a JSON representation of its data. It returns a querystring representation of its data. As has been mentioned above, you will need to use a server side script to interpret (and manipulate) sent data and store it in a file as JSON.
Having trouble accessing javascript code in a mixed html/js ajax response. jQuery ajax doc states:
If html is specified, any embedded JavaScript inside the retrieved
data is executed before the HTML is returned as a string
Which I can confirm by adding a simple snippet to the html reply:
<script type="text/javascript"> alert($(this)); </script>
How then to retain access to the js code vs. one-and-done execution?? Trying to implement a modal login (to prevent data loss on session timeout in form submission screens). Of course I need to be able to access the ajax'd js code to then validate email/password fields and ajax authenticate user credentials on the remote server.
Here's the modal login coffeescript snippet:
# submit form
$.ajax
success: (data) -> ...
error: (data) ->
popAuth(data.responseText) if(data.status == 401)
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
title: title
})
Perhaps I can add a success callback to popAuth() ajax options to store the returned js code? How about jQuery "live" handler? Unfortunate that this scenario is not as straight forward as one would hope ;-) I have seen $.getScript as an option, but would prefer to not separate html from js since server-side already assembles html + js and the original ajax call pulls it all down in one go. (i.e. avoid creating a dedicated server-side controller to send back js file content bundle)
I am of course open to alternative solutions to workaround this issue. For example, I could store login fields and js login validation code on every screen (JVM CRUD application living behind WordPress front end so every screen is basically auth required) in a hidden div, and then pop the modal login window "locally", which I assume would get around the annoying one-and-done js execution of remote ajax content.
Anyway, Ideas appreciated! client-side is both wonderfully simple and...horribly complex ;-)
Ok, fending off the veritable deluge of responses, I'll take a stab myself.
As I understand it now, since mixed html/js content is one-and-done executed, we have one chance to capture ajax response js code and bind it to current scope.
First, in the original ajax call (i.e. form submit that returns a potential 401 not authorized status) set the context of the modal login's ajax setup to $(this), the currently executing scope that contains jquery validation and other shared js code needed for modal login ajax submit to work.
In my case, using fancybox, adding context param it now looks like:
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
context: $(#)
title: title
})
Then, since the parent window contains the majority of needed javascript, the only requirement is to create a js file that binds modal login form button click event to validation and $.ajax submission.
# login.coffee
jQuery ->
$('#loginSubmit').click (e) ->
e.preventDefault()
isValid = $('#loginForm').validate().form()
if isValid
$('#spinner').show()
$.ajax
data: $('#loginForm').serialize()
success: (data) ->
$('#status').fadeOut()
location.href = '/foo'
error: (data) ->
$('#status > div').html( data.responseText )
$('#status').fadeIn()
complete: () ->
$('#spinner').hide()
Done, all good, works ;-)
Right now, I have a webapp that uses the jquery ajax to make a call (with params that change from call to call via a form) to my backend and retrieve an xml file. I want to put the xml data into a file with a different extension for a private application.
Basically I just want the user to be able to click a button, and it automatically prompts them to "open or save" a file containing the returned ajax xml data.
I've dabbled with sending a raw http header using php, but I can't figure out how to get it to work.
I'm writing all of this in javascript and jquery.
The only thing the below code does is (1)Make the Ajax Call, (2)Write the XML into an HTML page, (3) open the HTML page.
var format = function() {
$("button#format").click(function() {
$("#form").submit();
$.ajax({
url: "find",
beforeSend: function (xml) {
xml.overrideMimeType("application/octet-stream; charset=x-user-defined");
},
data: $("form#form").serialize(),
dataType: "html",
success: function(xml) {
xmlWindow = window.open("download.ivml");
xmlWindow.document.write(xml);
xmlWindow.focus();
},
error: function(request) {
$("#webdiv").html(request.responseText);
}
});
});
};
There is no need to force something like this into the AJAX paradigm, unless you need to play around with the data you retrieve before making it available for the user, then again, that should be able to be done in php. So I would do something like this:
<form id="format" action="download.ivml" target="_blank">
...
</form>
And in jquery modify the action like this
$('#format').submit(function(){
// tweaking the post data, otherwise this whole block is not needed.
return true;
});
Finally on my server use a .htaccess file to handle that weird URL download.ivml
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)download.ivml$ /path/to/where/I/process/the/request
not quite sure about the syntaxis of this last .htaccess file though.