I have a button on my Ruby on Rails view file.
Firstly when the button is clicked an Ajax call is made which in response gives a JSON string. So far I have accomplished this task.
Here is where I am stuck: The button also redirects me to another action of the same controller. Now I want to send the JSON string received by JavaScript as a parameter to that action.
Is there any way around this?
Your ajax call should look something like this:
... doing stuff before ...
$.ajax(
url:'url-to-script',
success: function(data) {
var json = JSON.parse(data);
$('#hidden-field').val(json); // set a hidden field in your form
$('#from-id').submit();
}
);
$('#submit-button').attr('disabled', 'true'); // disable the button
// set some spinny animation to notify the user that you are waiting.
// time out after a while if you don't get a response
... doing stuff after ...
Basically we fire off the ajax event, disable the button and notify the user you are waiting. When the call returns, your callback method submits the form to rails. You can also set a time out for the ajax call and let the user resubmit if necessary. You can handle the error case however you like.
Related
I am making a post request to google app script with the code below
var url ="MY WEBAPP EXEC"
function submitForm() {
var postRequest = {}
postRequest.name = $("#inputName").val();
postRequest.email = $("#inputEmail1").val();
postRequest.message = $("#inputMessage").val();
alert(JSON.stringify(postRequest)); // this alert
$.post(url, postRequest, function(data,status){
alert('success')
});
}
I am very confused why the post is working with the alert but doesn't work without it. Thank you.
===
OK I guess my question was not clear enough sorry.
I have a form accessing GAS remotely. I assumed the url implied that I was accessing GAS remotely. At the moment I am working on my localhost and on my JS above it works if the alert statement is present and does not do anything if alert is not there.
I was watching the execution list on GSuite Developer Hub to see if the request failed or completed. I observed if the alert statement is in the script the execution status is completed but if the alert statement is not there nothing happens. I assume that my post script is not working if alert is not there. Any idea why?
You haven't shown exactly how that function is called, but it's likely to be because, if this is truly a "form submit" action, the result of submitting a form is to "load a new page" (which can be the same page you're on, and is so by default with no action attribute in the form tag
Since you want to perform AJAX on form submit, you need to "prevent" the "default" form submit action - this can be achieved as shown in the second and third lines below
var url ="MY WEBAPP EXEC"
function submitForm(e) { // if this function is called using an event handler, it gets an event as the first and only argument
e.preventDefault(); // prevent the "default" form submit action
var postRequest = {}
postRequest.name = $("#inputName").val();
postRequest.email = $("#inputEmail1").val();
postRequest.message = $("#inputMessage").val();
alert(JSON.stringify(postRequest)); // this alert
$.post(url, postRequest, function(data,status){
alert('success')
});
}
I have a url say www.abc.com which display all data of a table
I have search box in the page which calls a function search() on keyup
//search function
function search(){
window.location.hash = "?query="+$("#search).val(); /* goes to the page and get data*/
}
When I type any key say a, it will send a the request www.abc.com?query=a and get all data starting with a
When I type any key say aa, it will send the request www.abc.com?query=aa and get all data starting with aa
I want to know a way to abort the request www.abc.com?query=a when
www.abc.com?query=aa is send because it takes a lot of time
Whatever "goes to the page and get data" is, it should return a handle. For instance, if you're using the Vanilla JS XMLHttpRequest, then you can return that object.
Then, before loading a new search, call its abort method to cancel the old one.
Note that this may not actually cancel it on the server side, so be careful.
I am using jQuery serialize() function to collect data in a form and submit to server using jQuery Ajax "post" method, like this: var params = jQuery('#mainContent form').serialize();.
The strange thing I saw is the serialized data from my form contains old data. It means, all of my changes in form (input to text-field, select on combo-box) is not stored to DOM, so when jQuery call serialize(), it collect the old data which appeared before I change the form. I tried to inspect to each element in that form and call .val(), it still showed the old values.
So how can I persist all my changes to form, that the serialize() method can build the string with newest data I entered?
Here is my snippet code, I called serialize() inside submit handler
jQuery('.myFormDiv input.submit').click(function() {
// Do something
// Collect data in form
var params = jQuery('#mainContent form').serialize();
// Submit to server
jQuery.post(url, params, successHandler);
}
Thank you so much.
When are you calling serialize? it should be $('form').submit( [here] ); It sounds like it's being called on page load, before you enter values into the fields, then being used after.
EDIT:
using the submit event instead of on click will catch someone hitting enter in a text field.
jQuery('#mainContent form').submit(function() {
// Collect data in form
var params = jQuery(this).serialize();
// Submit to server
jQuery.post(url, params, successHandler);
}
*the above code assume url is define and successHandler is a function.
I have a link that when clicked needs to call a controller action with certain data which must be retrieved via JavaScript. The action will be returning a FileStreamResult.
I looked at #Url.Action but I couldn't figure out how (or even if) I could pass value dictionary stuff which had to be retrieved via JS.
So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.
So any help on how you would do something like this would be great..
So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.
Exactly. You can't do much with a received byte in javascritpt: obviously you cannot save it on the client computer nor pass it to some external program on the client. So don't call actions that are supposed to return files using AJAX. For those actions you should use normal links:
#Html.ActionLink("download file", "download", new { id = 123 })
and let the user decide what to do with the file. You could play with the Content-Disposition header and set it to either inline or attachment depending on whether you want the file to be opened with the default associated program inside the browser or prompt the user with a Save File dialog.
UPDATE:
It seems that I have misunderstood the question. If you want to append parameters to an existing link you could subscribe for the click event in javascript and modify the href by appending the necessary parameters to the query string:
$(function() {
$('#mylink').click(function() {
var someValue = 'value of parameter';
$(this).attr('href', this.href + '?paramName=' + encodeURIComponent(someValue));
return true;
});
});
Instead of going with a post, I'd go with associate a JQuery on click handler of the link which would call the controller action. This is assuming that the action method returns a FileStreamResult and sets the correct content type so that the browser interprets the result and renders it accordingly.
With your approach you'd have to interpret in the onSuccessHandler of the post on how to render the generated stream.
I have been studying JavaScript from one book. Once I was playing with the codes concerning the client-server site communication, I wanted to do a POST request with the code below (which uses IE ActiveX object XMLHttpRequest):
<script type="text/javascript">
var oRequest = HTTPRequestUtil.getXmlHttp();
var sRequestType = "post";
var sURLofRequest = "MyPage.aspx";
var bAsnychronously = false;
oRequest.open(sRequestType, sURLofRequest, bAsnychronously);
oRequest.send(null);
alert ('Status is '+oRequest.status+' ('+oRequest.statusText+')');
alert ('Response text is '+oRequest.responseText);
</script>
I have breakpoint on the PAGE_load eventhandler of the MyPage.aspx" page. I was expecting the execution will stop at that place when this HttpRequest occurs above. (It is called on a html button click).
The thing is, the request is done, the responseText is obtained (which was the xml content of the page) and no stop at the Page_Load method where I have put a breakpoint.
So, now I cannot understand the difference between calling .send() function with POST request type and submit() function on the call.
I would appreciate if you can explain the main differences briefly.
thanks!
The difference is that using send will send the data back to the JavaScript calling routine without reloading the page, but calling submit on a form submits the form to the server and then reloads the results from the server as if the user had clicked on the submit button of the form.
The "send" is what is known as Ajax, and it is, for example, how the Stackoverflow voting buttons work to send the votes back to the server without reloading the entire page.