Is it possible to render json data into a javascript variable while making an ajax call in grails? - ajax

Is it possible to render json data into a javascript variable while making an ajax call in grails?
I am using the submitToRemote inorder to make an ajax call from my grails view to an action in my grails controller. The action returns a json variable/value. I need to to assign this value to a javascript variable for further usage on my web page. Is this possible to achieve? Any leads will be helpful.

submitToRemote have the onSuccess option that you can use to retrieve the json data. From the docs:
onSuccess (optional) - The JavaScript function to call if successful
An example of how doing it can be seen in this blog post.

You could use the onSuccess callback of submitToRemote to read the result of your request and pass them into a javascript variable.
<script type="text/javascript">
function passResult(result) {
yourVariable = result.responseText
}
</script>
<g:form action="show">
Login: <input name="login" type="text" />
<g:submitToRemote update="updateMe" onSuccess="passResult(result)"/>
</g:form>
<div id="updateMe">this div will be updated with the form submit response</div>
The code above is untested but should work.

Related

php post form max input vars strange behaviour

I am posting only 2 variables. If I do a direct POST using the form below it works.
<form action="http://someapi/post_html" method="post" enctype="multipart/form-data">
<input type="text" name="name" >
<textarea name="htmltemplate"> a html template of 3000 characters
</textarea>
<button type="submit">Submit</button>
</form>
When I use ajax to post the data I actually get a response back from the server max_input_vars limit of 1000 exceeded. How is it possible when I'm only sending 2 variables using ajax that I get that message?
I also tried using curl to do a POST and ended up receiving the same message.
$('form.ajax').on('submit',function() {
var formData = $('form.ajax').serialize();
formData += CKEDITOR.instances.textboxwyswygs.getData();
event.preventDefault();
$.ajax({
url: "http://someapi/post_html",
method:"POST",
data: formData,
success: function(response){
console.log(response);
}
})
});
Your formData looks broken - serialize() returns a JSON string and the CKEditor getData() returns a string of HTML.
Try this: synchronize the CKEditor value into the form before calling serialize and then your JSON will be correct. Try to console.log(formData) to check the formData before sending. So submitting the form without the syncrhonziation doesn't actually send the CKE content at all. This should be checked server-side to see what input it is getting.
Also the value of the ajax functions data member is expected to be correct JSON and servers might handle it in weird ways.
Other issues: $('form.ajax') does not actually target your HTML. Is this a correct example?
The event variable looks undefined, try naming it e and adding it as a parameter to .on('submit',function(e){..}.
You don't show the code where you actually replace the textarea with a CKEditor, it would be useful to see.

Laravel confused if I should use <form> tag or not when doing a ajax put request

I am making a simple put request to my app backend using axios.put();
This all works, I have a button that is binded to vue like #click="submitForm"
However looking around I see that some people still wrap their input fields in forms like those:
<form method="POST" #submit.prevent="onSubmit" action="{{ route('someRoute') }}" id="form-submit">
{{ method_field('PUT') }}
{{ csrf_field() }}
Even if I dont use a form like the one above I get the same result when calling my ajax put request.
Laravel allready adds csfr headers to axios by default in resources/assets/js/bootstrap.js
So is there any reason I still should wrap my inputs in a form like above?
Thanks
Your ajax request doesn't matter if you do your inputs in form tags or not, because the request still sends and receives data from a server.
I would use a form tag because everybody can read the markup much easier and it could be usefull for writing less code in javascript - one example
<form action="" method="">
<div class="form-group">
<label class="control-label">Input</label>
<input type="text" name="input" />
</div>
</form>
$(document).ready(function() {
$('#some-form').on('submit', function() {
var data = $(this).serialize();
... do whatever you want (like ajax call) ...
return false;
});
);
You're using an Ajax request, in which case a standard "form submit" would get prevented. Putting a form around it is not obligatory, especially if you use a button element, which is not a classic form element anyway.

Send form to server in jquery

I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})

How to create a simple ajax form in Drupal 7?

I want to create a simple form in Drupal7 with only one field. When hitting the submit button I need to call an ajax function with the field value and update a DIV on the page without reload.
I'm not familiar with Drupal form API, and I tried to implement the examples form the form api documentation but I always get errors like this:
Notice: Undefined index: #title_display form_pre_render_conditional_form_element() függvényben (/var/www/nmtest/includes/form.inc 2986 sor).
Notice: Undefined index: #value theme_textarea() függvényben /var/www/nmtest/includes/form.inc 3727 sor).
I can do it by creating a custom page and simply use native PHP but this is not an "elegant" way.
I want something similar like the one here, but without form valitation, page reload or so: Create a VERY simple form in Drupal
I only want one button that calls an ajax function. Shoud I do this with forms API or just use plain old native PHP and jQuery?
Edit: Looks like I don't even need a real ajax call, because I only need to change an SRC of an IMG tag.
Here's what I did in native PHP. I want to achive this trough forms api:
<script>
function getstar() {
starpoints = jQuery('#starpoints').val();
rand = Math.floor(Math.random() * 9999) + 1;
src = "test.php?star=" + starpoints + '&rand=' + rand;
jQuery('#starimg').attr("src",src);
return false;
}
</script>
<form>
<input type="text" name="starpoints" id="starpoints" />
<input type="submit" onclick="return getstar();" />
</form>
<img src="/test.php?star=5" id="starimg" />
Edit: Ok, I managed to render a form with the Drupal API. Now the only thing is that I want to insert the placeholder for the IMG via my module, but I don't know how to do it. The form renders fine, but I want to add a HTML block after it. Currently I do it by javascript:
jQuery(document).ready(function() {
jQuery('<div><br /><img id="starimg" src="" /></div>').insertAfter('#drawstar-form');
});
What hook should I catch to render this HTML block after the form? I tried drupal_get_form but that returns an array and I cannot attach the HTML block.
The Form API provides everything that you need to do this without writing a single line of JavaScript code. See http://drupal.org/node/752056 and http://api.drupal.org/api/examples/ajax_example!ajax_example.module/function/ajax_example_simplest/7 and .

Using MVC3, how to get browsers to explicitly interpret a transferred script as HTML?

In my MVC app, I am returning some Javascript. Howveer, I am using the anti-forgery token on the view, so the rendered result would be
<input name="__RequestVerificationToken" type="hidden" value="E8as+4Ff1u/c/+kuFcNXXCREB5pz5GAfH2krN5RvzURJaHZSApuRc4czZqmoITaKdy0XhN5sFfRzl4ne+wB3PkWOscBWzoIxUk3hGaFwDxRXSbMs8K9IwojEAtV5u57MR7hiSujr6MOTpjjbf5FPaYgO4gmH6lSR9mbSyO2IedI=" />
<script type="text/javascript">
// Here, we ensure that jQuery is loaded then load up the rest of our JS in in order.
ord = Math.random() * 10000000000000000;
...
So there is some HTML to be added to the page then the JS.
The issue is that I get the following notification in Chrome:
Resource interpreted as Script but transferred with MIME type
I need the browser to interpret this as HTML in order to make use of the anti-forgery token.
I have tried putting this on the view:
<%#Page Title="" Language="C#" ContentType="text/xml" %>
Which renders:
<%System.Web.WebPages.DynamicPageDataDictionary`1[System.Object] Title="" Language="C#" ContentType="text/xml" %>
<input name="__RequestVerificationToken" type="hidden"
...
...but the same message persists.
In my controller I have also tried:
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(page.clientScript);
return new ContentResult
{
ContentType = "text/xml", // also tried text/html
Content = Encoding.UTF8.GetString(bytes),
ContentEncoding = System.Text.Encoding.UTF8
};
Same issue.
-- UPDATE --
This is how I'm invoking the MVC app to return the text:
// used to load scripts on to the client script using a non-blocking asynch request
(function() {
function async_load(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://myserver/MyAppPath/someids';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
}
if (window.attachEvent)
window.attachEvent('onload', async_load);
else
window.addEventListener('load', async_load, false);
})();
If I've understood correctly, you need an MVC action which returns both html and a script tag that can be injected in a page via a <script... include. You also want to render this via an MVC view.
The biggest issue you've missed is that in order to get this content into the calling page, you need to execute document.write from the script - you can't just send back HTML and script in response to the script include - the browser won't understand it, it's expecting javascript only.
There are a few ways to do this - I have written a full suite of ViewContent MVC controller methods, with the same overloads as View which returns the result of a view to a controller action as a string. I can then pass that back as a string literal (useful for html email generation) but also to a javascript encoder.
In this case, you don't need to be so generalist. We can leverage Darin Dimitrov's answer to this SO: Embed MVC Partial View into a document.write JS call and split your view into a View and a partial. The view writes the document.write() skeleton, and the partial view renders the dynamic html you want to be injected into the page. It's unclear if you're using the Anti Forgery Token in the main view which will call the script (in which case it should be rendered as part of the view that it returns) or if you're actually hard-coding it in the script. The second should definitely not be used but I'm writing this answer as if it is, because that appears to be what you want.
First, your partial view (let's call it Fragment.cshtml, put it in ~/Views/Shared)
<input name="__RequestVerificationToken"
type="hidden"value="[ommitted]" />
<script type="text/javascript">
// Here, we ensure that jQuery is loaded then load up the rest of our JS in in order.
ord = Math.random() * 10000000000000000;
...
Second, the host view, called SomeIds.cshtml
#{ Response.ContentType = "text/javascript"; }
document.write('#Html.Raw(HttpUtility.JavaScriptStringEncode(Html.Partial("~/Views/Shared/Fragment").ToHtmlString()))')
Now this view returns a document.write call that injects the HTML returned by the Fragment.cshtml into the page that includes the script.
Are you returning a PartialView that has all of the markup rendered?
Create a PartialView with your (form and script includes) and in your Controller:
public ActionResult Index(Models.MyModel model)
{
// validate the model if needed
return PartialView("[My PartialView Name]", model);
}
You could put your scripts in separate files, and add the [script src] tags in the PartialView.

Resources