php post form max input vars strange behaviour - ckeditor

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.

Related

form data moves through ajax on page load instead of on submit

I am sure there are things I haven't read out there, but every search I do just turns up purple links. My goal is to have a form that uses ajax in order to avoid page refresh and avoid submit on manual page refresh. I want to both upload a file and insert data into the database table. I actually have this part down. The problem is that the action is started on page load. I think this is because my ajax function uses #multiform).submit, but if I change that to #submit).submit then the ajax script doesn't send the data to upload.php and I just end up with a blank array being passed to upload.php.
I can make the upload work on click with a button instead of an input for the form submit. That's all without using formdata though. I need to use formdata to also upload the file. The below script does work. I just need it to work after clicking submit, and not automatically when the page loads.
As I'm learning, I'm thinking that formObj=$(this) is referring to the multiform and grabbing the objects, so when I change multiform to submit (this) doesn't work anymore. Is it possible that I just need to change that field somehow? I've been working on this non stop for weeks. I keep getting closer, but still not there. Please help me. Thank you.
my form:
<form name="multiform" id="multiform" action="upload.php" method="POST" enctype="multipart/form-data">
Name: <input type="text" name="dname" value="Ravi"/> <br/>
Age :<input type="text" name="age" value="1" /> <br/>
Image :<input type="file" name="photo" /><br/>
<input type="submit" id="submit" value="Ajax File Upload" />
</form>
my js:
jQuery(document).ready(function($) {
$("#multiform").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData($(this)[0]);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{ alert(data)
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //Prevent Default action.
});
$("#multiform").submit(); //Submit the form
});
I figured this out by looking at it backwards. I googled how to make the form submit automatically on page load and found out that $(document).submit() makes a form submit on page load, so I took out $("#multiform").submit(); and now it works. An added note to anyone else who might find this and be working on something similar. For some reason, having an id of submit for input type submit causes the name and age variables to be ignored.

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();
})

HTML form Ajax post on Success

As below, I am using a 'Form' and 'AJAX' to post the content of a text area to a URL within my site. I see the POST does work and posts the conetn to the server and on success I have tried to find the element on the page to append it, though it is not working.
Can you please advise?. The function success part of the call should be where I specificy the destination, though how do I append this data, put some ajax in the destination page html, on load etc?
<form id="test" onclick="submitForm();">{% csrf_token %}
<textarea id="red_content" name="content"></textarea>
<p>
<input type="submit" value="Publish" name="send">
</p>
</form>
function submitForm()
{
$.ajax({
url: "http://127.0.0.1:8000/Test/Trial",
data: $('#test'),
type: 'POST',
dataType: 'html',
success: function(data)
{
//$('.content-container5').setFocus();
$('.content-container5').html(data);
}
});
Many Thanks,
Tom
I'm not very familiar with submitting a single field via ajax (or in your case jQuery's ajax function). I did however have to do a similar function in a project I recently had.
I found this plugin:
jQuery Ajax Form Submit
It seemed to work really well. You may want to look into this for your project as well. In this case, instead of submitting your one field, the form will be submitted. This may be easier since you won't have to map the fields yourself. You can post the form to the same page and process it or post it to a given url.
Hope this helps.

How do I send arbitrary JSON to node.js without a page reload?

My ultimate goal is to send an arbitrary JSON to node.js when a button is clicked. I currently only know how to send input from a form. Here's some code I put together to send form information:
function postForm() {
$('form').submit(function(e) {
e.preventDefault(); // no page reload
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data) { console.log('Code for handling response here.') },
'json'
);
});
}
Where the HTML looks like:
<form action='/send' method='post'>
<input name= "foo" type="radio" value=1>
<input type="submit" value="Submit">
</form>
And the relevant express/node.js code looks like:
app.post('/send', function(request, response) {
fs.appendFile('test.txt', JSON.stringify(request.body) + '\n', function(e) {
if(e) throw e;
console.log(request.body);
});
});
However, I don't know how to adapt this example to use data that is not from form input. To give context, I'm building a web-based user study, and I want to send various information collected about the user to node.js. I've tried variants of what was working for the form submission, but none of my attempts have been successful. My impression was that I could just swap out $(this).serialize() to any other data that the client can access, but I couldn't get this line of thought to work. I also tried altering some of the many .ajax() examples, but those always redirected the page which is undesirable, since my study will lose user-state information if the page refreshes.
I've done decent amount of client and server side programming, but I have next to no knowledge about how ajax works, which is proving rather problematic for solving this! And also rather silly since, often times, that's what glues the two together :)
Since you're using jQuery, sending data is simple – call $.post(url, data) from the button's click handler:
$('#somebutton').click(function() {
var data = { key: 'value', ... };
$.post('/send', data, function(res) {
// success callback
});
});
The browser will POST to url with a URL-encoded serialization of the data argument.
POST /send HTTP/1.1
Content-Type: application/x-www-form-urlencoded
...
key=value&...
Which Express' bodyParser will have no trouble with. Alternatively, you can tell jQuery to send a JSON serialization of data:
$.post('/send', data, function(res) {}, 'json');
In your case, it really doesn't matter how jQuery transmits the data (URL encoded or JSON), since bodyParser automatically deserializes both formats.

jQuery form upload error

I am using this version of jQuery form plugin https://raw.github.com/malsup/form/master/jquery.form.js
getting an error on submit:
error on line form.submit();
SCRIPT87: Invalid argument. jquery.form.js, line 347 character 5
My code:
<form id="ajaxUploadForm" action="#Url.Action("Upload", "Home")%>" method="post" enctype="multipart/form-data" >
<fieldset>
<legend>Upload a file</legend>
<label>File to Upload: <input type="file" name="file" /></label>
<input id="ajaxUploadButton" type="submit" value="Upload" />
</fieldset>
</form>
$(function () {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
// $("#ajaxUploadForm").block({ message: '<img src="/Content/themes/start/images/progress.gif" />' });
},
success: function (result) {
// $("#ajaxUploadForm").unblock();
//$("#ajaxUploadForm").resetForm();
$.growlUI(null, result.message);
},
error: function (xhr, textStatus, errorThrown) {
//$("#ajaxUploadForm").unblock();
//$("#ajaxUploadForm").resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
I am doing this upload in side simple model dialog.
May be some one may have any ideas how ti fix that?
If the controller action that you are POSTing to is returning JSON you might need to wrap it in a <textarea> tags as explained in the documentation:
Since it is not possible to upload
files using the browser's
XMLHttpRequest object, the Form Plugin
uses a hidden iframe element to help
with the task. This is a common
technique, but it has inherent
limitations. The iframe element is
used as the target of the form's
submit operation which means that the
server response is written to the
iframe. This is fine if the response
type is HTML or XML, but doesn't work
as well if the response type is script
or JSON, both of which often contain
characters that need to be repesented
using entity references when found in
HTML markup.
To account for the challenges of
script and JSON responses, the Form
Plugin allows these responses to be
embedded in a textarea element and it
is recommended that you do so for
these response types when used in
conjuction with file uploads. Please
note, however, that if there is no
file input in the form then the
request uses normal XHR to submit the
form (not an iframe). This puts the
burden on your server code to know
when to use a textarea and when not
to. If you like, you can use the
iframe option of the plugin to force
it to always use an iframe mode and
then your server can always embed the
response in a textarea.

Resources