Is there a way to submit a "fake" form using jQuery? - javascript

What I want to do is make a POST request with arbitrary params, much like submitting a form. That is not merely doing the XHR. What I ideally want is to emulate a submit (like submiting a form, not POSTiing and then redirecting). I want to avoid the latency of $.post + window.top.location = blah
The most direct way would be to have a 'fake' form and insert a bunch of elements, then serialize and use jQuery.submit(), something like Is there a way using jQuery to submit a form without the elaborate field by field breakdown?
I wish there were a more elegant way.
My use case is that I am gathering a bunch of random fields through external API calls (from Facebook and other services) and want to submit ALL that info at once to user creation, as if the user filled out all this information and pressed 'submit'
Any suggestions? Thanks!

yes
you can use $.ajax (example)
or $.post and $.get ... example:
$.post(
"url_to_page",
/* string like this: "text=me%20man&mail=peace#man.com or an object": */
{text: "me man", mail: "peace#man.com"}
)
/* you can check if the request was submitted successfully */
.success(function(data) {
alert("Success!");
alert(data); //data on page
})
/* you can check if the request failed */
.error(function() {
alert("Error!");
});

Related

Contacting server in JS client side form validation

I have an HTML form. I am already doing a client side HTML.
<form id='myForm' onsubmit='return myFormValidation()'>
...
</form>
Now, in myFormValidation function, after making sure the client side is OK, before really submitting the form, I want to do also a server side form validation.
I am using JQuery. So,I changed my function to something like this:
function myFormValidation(){
//first, client side validation
...
//then, server side validation
$.post(url_of_server_side, $("#myform").serialize(), function(json) {
data = JSON.parse(json);
if(!data.ok)
{
$("#msg").text("some error");
}
else
{
$("#myForm").submit();//Oops!
}
});
return false;
}
But the "submit" function of form behaves like a recursive function and tries to validate the form again!
Should I disable the validation function before calling submit? Or, I guess, there is a better way for my problem (which is slightly or even totally different than this)?
If you need server side validation you should extend your "Save" enpoint to support correct response status codes and do not use separate "Validation" url. Use single url with different response types:
200 (Success) - data was saved successfully
400 (Bad request) - input data was incorrect. As response message you can include "validation result" message which you will display to user.
So your code can looks like
$.post(url_of_server_side, $("#myform").serialize())
.done(function() {
//show some success confirmation or redirect to main page
}).fail(function(xhr, status, error) {
$("#msg").text(error.message);
});
I would suggest, if all data is OK, the server-side script to perform the action that you want, e.g. saving to database. That way, you will not need a second post of the form in case everything is correct.
If something is wrong, then obviously, the checks must take place the second time as well.

Anyway to return JSON from form.submit()

Morning,
I am submitting a form from jquery like:
$('#form').submit();
which successfully submits the form onto the server. However, I would like to return JSON from the post so I can dynamically update a modal without any redirection.
Though I could change my submit into a AJAX request. (so the return contents from the method will enter the success callback in the AJAX code) I already have the controller method accept my ViewModel object from the post so I can do easy validation on the server e.g.
If ModelState.IsValid Then
also I have the objects accessible to me (other posts suggest to serialize the data but with 20+ properties being sent, this will take a lot of effort on the server)
Is there anyway I can keep this same logic and return JSON? or will a re-write be required?
Thanks
Get the form data from the form and make an AJAX call.
$('#form').submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(json) {
alert(json);
}, 'json');
return false; // important to have this
});
Return json_encode($data) from your PHP file

Is it possible/how can I enter data into and submit a form on a remote server using jQuery/Ajax

I have a form on a remote server, consisting of just a text box and a submit button. Once this form is submitted (PHP) XML is returned. How can I go about using ajax/jQuery to fill out this form, submit it, and receive the XML to process?
Untested, I think you should be heading somewhere in the direction of the following JS. Ofcourse, this is light thinking, there could be all kind of implications with the following (eg. XSS protection etc..). But if we're talking a simple, plain form, I think this could work.
Also, expanding the following with some failure fallbacks etc would be good practice. For documentation on the Ajax function, check the API docs.
// This should be the URL where your <form> action's value is pointing at
var url = 'http://remote/form/action';
// The textfield's data you want to submit
var textFieldValue = 'foobar';
$.ajax(
url,
{
'type': 'POST', // Could also be GET, depending on your form
'data': {
'textFieldName': textFieldValue,
},
'success': function (data) {
console.log(data); // Your raw XML in a string
}
}
);
Edit: As Kevin B mentioned, you'll be heading into cross-domain policy problems with the above, making this situation that more complex. Therefor you should need to make sure you have CORS arranged on the targeted domain. See Wikipedia CORS for more info.

Create a POST header

Here's the thing: I have an array which I must send to another page... not using an AJAX request. I'm trying to redirect my user to this new page, or maybe to open a popup with the new page, but this new page must receive the array data on a POST request.
How do I do this in javascript? I have no problem JSON encoding my array before sending it, I just don't know how to redirect my user to a new page with the data "attached", in javascript.
I'm using ExtJS4, so if there's anything on Ext.util, I have no problem using it.
Thanks.
You can do this (using javascript)
make a new FORM
set the action as the new page
set the method as POST
add a hidden field
set the value of the field to this Value you want to send
Pragmatically submit the form
You can Ajax POST to the target page's url:
Ext.Ajax.request({
url:'/target/url/', async:false, method:'POST',
jsonData: {
jsonArray: yourJsonArray
}
success: function() {
console.log('posted successfully');
}
});
async:false loses the asynchronous functionality; simply remove it if you don't need your POST to be synchronous.

Sending normal request in jquery ( not ajax)

Is there any method in jquery like $.post , $.ajax etc which works like a normal form submission. I know about .submit() but it requires a form element , can we send a normal request without a form element in jquery?
You can submit without a form using $.ajax(). Further, to make it behave like a normal form would, set the async property to false.
$.ajax({
url: "/controller/action",
data: {'foo':'bar'},
async: false
});
This will result in you being sent to:
"/controller/action?foo=bar"
window.location.href = '/controller/action?foo=bar';
You are not clear on what you want to achieve. From what I understand, I'd suppose you want to send a GET or POST (form-submit-like) request to the server and make it seem like a real one.
In that case you would:
Create a XMLHTTPRequest with appropriate parameters.
Make it synchronous.
With the response, overwrite the DOM.
Not entirely clear what you are after, however you can use jQuery's serialize (docs) to pass a collection of values from input not in a form or any other items. You would still need to post the data in some manner however.

Categories