Jquery - Send only some value from a form - javascript

using the checkTL() function, i need to send to the server (for example) only the input value into div with class "sideon". So, in the example, i need to get (server side) only the value of inputside0 and inputside3. How is possible this?
cheers

How about using AJAX?
<form method="POST" action="./index.php?general=example3" name="addtl">
...
</form>
and then:
$(function() {
$('form[name=addtl]').submit(function() {
var dataToPost = $(this).find('.sideon :input').serialize();
$.post(this.action, dataToPost, function(result) {
alert('success');
});
return false;
});
});
Of course putting input fields whose values shouldn't be submitted to the server into a form is doubtful. Maybe you should rethink the way you organize the forms.

two ways:
make them into lots of seperate forms.
do return false on the form submit in jquery and use $(".sideon").find('input').val(); to post an ajax query

Related

ajax form validation before submit how?

I am doing ajax cross domain request to my php page on server.
I am posting form from html via ajax to my php page on server.
Have problem with validation in client side.
I don't know how to do validation in client side before send form.
html form is standard form, posting input fields: name, last name, message....
My html form, client side:
<script type="text/javascript">
var output = $('.nesa');
$(document).ready(function(){
$("#form1").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'http://www.example.com/form.php',
crossDomain: true, //set as a cross domain requests
type: 'post',
data: $("#form1").serialize(),
beforeSend: function (){
// add spinner
$('.spinner').append('<img id="animacija" src="spinnersmall.gif" alt="Loading" />');
},
success: function (data) {
$(".nesa").html(data);
alert("sent " + data);
},
error: function(){
output.text('Message is not sent!');
}
});
});
});
How to to validation? I try to put code in beforeSend but without success.
Or maybe to use submitHandler?
Idea is when user click submit, that validation start, and if fails to tell "insert your email address". Now when i click submit it send data to server. I want that first check input fields.
This form is actual working it sending data to server, but just need to figure out how to do validation. Where to put validation in ajax call?
Thanks
Create a function to validate form which return true/false. Call the function just before the $.ajax. check if return is false then return.. see the example below...
if(!validateForm())
return false;
First, are you actually using an AJAX form?
You explained that you load the form itself via AJAX, but do you send it that way, too? It looks to me that you're trying to send it the HTML way. You can hook into the click event of the send button before you send the form. However, since the button is added to the page at runtime, you need to register the event to document.
$(document).on('click', 'input[type=submit]', function() {
// Validate form
// Add error message on fail, and return
// Else submit form via AJAX
});
In either case, you can use jQuery's blur event as an alternative to validate each field when the user jumps to the next. You could even validate every time the user presses a key with keypress.
I always validate them right before I enter them into an AJAX call. Here is my exampel
$('#form_nieuwsbrief').bind('submit',function(){
var name = $('input[name=naamNieuwsbrief]').val();
var email = $('input[name=emailNieuwsbrief]').val();
var proceed = true;
if (name==""){
$('input[name=naamNieuwsbrief]').css({'border':'2px solid red'});
proceed = false;
}
if (email==""){
$('input[name=emailNieuwsbrief]').css({'border':'2px solid red'});
proceed = false;
}
if(proceed == false){
$("#msg").append("<div class='alert alert-danger' role='alert'>U bent informatie vergeten in te vullen.</div>");
setTimeout(function(){
$('.alert').fadeOut(400, function(){
$(this).remove();
})
;},10000
);
}
if(proceed == true){ // make the ajax call
This is just a quick one for a newsletter that just requests name and email. But the principle is the same. Just before you make an ajax call, create the if else statement with a variable you set if something is false. else you stick it tot he original validation, thus you can proceed.
Please validate the form before sending ajax request. If there is no error then ajax request should be send otherwise return false.
You can do like:
$("#form1").submit(function (e) {
e.preventDefault();
// Get the Login Name value and trim it
var name = $.trim($('#name').val());
// Check if empty of not
if (name === '') {
alert('Text-field is empty.');
return false;
}
});
You can see the demo Here's (http://jsfiddle.net/LHZXw/1/)
You can also make a function onKeyup.
You're already validating via server side correct? Why don't you use that same validation rules to appear like your client side - via Ajax. I have a tutorial on how to do that:
http://michaelsoriano.com/how-to-ajax-validate-forms/

JavaScript to make some calculations and pass data to PHP

This is what I want to do:
When a HTML form is submitted, the form data is passed to JavaScript to do some calculations, then the form data along with the results (of JavaScript calculations) are passed to PHP to save data to the database.
Now, I know how to pass form data to JavaScript (or) PHP alone. But how to pass the data to both of them at the same time? And how to pass JavaScript data to PHP?
Also, am I going about it the wrong way?
1. Make calculations in Server Side:
"I wish to use client side for the maximum possible effect to reduce server costs" is not the best reason for doing so, if the calculations are not O(4^n), you should go ahead with doing this in the server side.
$myvariable = $_POST['numbers']; //I will skip sanitize
SomeCalculations($myvariable); //Making the calculations
2. If you really want to use Javascript:
If you really want to use javascript (I will use Jquery for simplicity) for learning or because you really think that is necessary in this case, then you can get the form data before submit and doing the calculations:
2.1 Submit the form like a normal form after make the calculations:
$('form').submit(function(e){
e.preventDefault()
var $this = $(this)
var formData = $this.serialize()
// do some calculations
var yourData = makeCalculations(formData);
$(this).submit();
});
2.2 Submit the form via Ajax (recommended since you are already using Javascript)
$('form').submit(function(e){
e.preventDefault()
var $this = $(this)
var formData = $this.serialize()
// do some calculations
$.ajax({
type: "POST",
url: "http://nakolesah.ru/",
data: makeCalculations(formData),
success: function(msg){
//This is returned in the server side
alert('wow'+msg);
}
});
});
Why not just do the needed calculations on PHP end? It's much easier and saves you headache making sure the data isn't tampered with, etc. The data is being passed there already.
Anyway - You'd either need to have javascript monitor the form and run the calculations as the user completes it. You can:
store those values in other (hidden?) form fields, which then get passed to php
use php to do the same calcs (not recommended)
cancel the form send action and send the data via ajax
You can use AJAX method for your stuff. $.ajax() or $.post() and etc. you can use any one of the method for your use.
Ref: http://api.jquery.com/jQuery.ajax/
Ref - POST: http://api.jquery.com/jQuery.post/
Since you wish to pass data to both PHP and JavaScript at the same time, I can think of only one method. It's not really simultaneous but it's very close to it.
So, let us say that you have this form #myAwesomeForm.
Write a JavaScript like this (assuming you are using jQuery $.post):
$( '#myAwesomeForm' ).submit( function( e ) {
var result = someAwesomeFunction() // this will do your calculation and return it
$.post(
'someAwesomePHPScript.php',
{
formData: $( this ).serialize(),
calculatedData: result
}, function( data ) {
// some more awesome stuff happens here
}
);
});
If you want to pass the data without changing the page, then use AJAX.
http://www.w3schools.com/ajax/
Otherwise use window.location("someFile.php?var1=xyz&...");

How to get POST variables in jQuery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to get GET and POST variables with JQuery?
I have the following HTML:
<form action='.' method='post'>{% csrf_token %}
<div class="parameters">
Show
<select name="earnings_filter">
<option value="all">Total earnings</option>
<option value="hd">HD earnings</option>
<option value="sd">SD earnings</option>
</select>
<input type="submit" name="submit" class="submit float-right" value="submit" id="submit_financials"/>
</div>
</form>
I need to do an ajax call with this, which I'm triggering on:
$("#submit_financials").live('click', function(){
...
});
Is there a way to get the variables that are submitted in POST, for example which option was selected (and there are about 10 other variables I need to get). Or do I need to use the jQuery selectors to get the value of each?
$("#submit_financials").live('click', function(){
$.ajax({
url: '', // script url to send
method: 'POST', // method of sending
data: $('form').has(this).serialize(), // .serialize() make query string with form inputs name and value
dataType:'json', // expected data format returned from server, you may have something else
success: function(response) {
// response contains data returned from server
}
});
});
It would be better replace live() with .on() if you're using jQuery > 1.7 and it'd be better if possible. So you can write it
$("#container").on('click', '#submit_financials', function(){
$.ajax({
url: '', // script url to send
method: 'POST', // method of sending
data: $('form').has(this).serialize(), // .serialize() make query string with form inputs name and value
dataType:'json', // expected data format returned from server, you may have something else
success: function(response) {
// response contains data returned from server
}
});
});
Here #container point to holder of #submit_financials that belong to DOM at page load.
If all the values are in input elements on the form...
$("#formId").serialize()
You could serialize the form and send to the server page
$.post("yourServerPage.php", $("form").serialize(),function(data){
//Do whatever with the result from ajax server page.
});
How about creating several input values of type hidden
<input type="hidden" id="sample_id" value="SOMETHING" />
give them ids and acces the data inside using:
$('#sample_id').val()
Unfortunately, POST variables are communicated in the request from the client to the server, but they are not automatically included in the response from the server back to the client. This is one of the things that sets them apart from GET variables.
If your data isn't excessively long, you may want to switch to the GET method instead. You can then retrieve the variables using a function like one listed in this question: How can I get query string values in JavaScript?
Alternatively, if you have access to the server-side code, you could include these variables in HTML returned; however this is another question entirely :)

How to simulate a GET action and pass it to the same page without reload?

So, I'm making a site that gets data from a server (Names, with an autocomplete script), gathers it all up, then on submit is SUPPOSED to send the data gathered to the server to get a JSON string back for usage further down on the page.
However, said server does not have the last part and I need to simulate it. But I have no idea how.
Using HTML, JS, jQuery and nothing else.
So the question being, as the structure is there,
how do I get
<form action="Search" method="get">
<input type="hidden" name="foo"/>
<input type="hidden" name="bar"/>
<input id="submitButton" type="submit" value="Search"/>
</form>
Where foo and bar will have values at the time of submit,
to end up as a JSON object containing foo, bar and some random data I just make up,
in the .js, on pressing submit, WITHOUT reloading the page. (That is, pressing submit just kicks in the script and gives the form data to it but nothing else)
Edit: Sorry, changed post to get. The server will when working, respond to GET with JSON.
Put whatever JS array/object you expect back from the server in returnedData:
$(function(){
var handleNewData = function(data){
alert('I got:\nfoo:'+data.foo+'\nbar:'+data.bar+'\nresults:'+data.results);
};
var reallySubmit = false;
$('form').submit(function(evt){
if (reallySubmit){
$.get(this.action,$(this).serialize(),handleNewData,'json');
}else{
// Put whatever spoof data you want here.
var returnedData = {
foo:this.elements.foo.value,
bar:this.elements.bar.value,
results:["jim", "jam", "jamboree"]
};
handleNewData( returnedData );
return evt.preventDefault();
}
});
});
See the working example here: http://jsfiddle.net/sQtkY/4/
Edit: Sorry, I forgot that jQuery will properly parse a JSON string for you if you pass the parameter. Updated the answer to show this; no need to stringify your spoof values.
Edit 2: OK, one more update to show you how to include form values as well as spoof data.
Try this:
$("form").submit(function (event) {
event.preventDefault();
// NOTE: the following would work when the server is ready
//$.getJSON("http://whatever.com/endpoint.php", $(this).serialize(), function(data) {
// console.log(data);
//});
var fakeData = {
whatever: "data",
you: "need",
foo: "value",
bar: "value"
};
console.log(fakeData);
});
Make sure you have firebug open to see the console.log().
Try this
$("form").submit(function(event){
event.preventDefault();
$.post("http://whatever.com/post.php",$(this).serialize(), function(data){
alert(data);
});
});

Send data from javascript to server

I am building a ASP.NET MVC webapplication and have a question:
Say that I have a strongly typed view, when hitting submit the object(of the strongly type) will be filled and sent to the server.
Now say that one of the properties of the strongly typed is not used in the form, instead I need to set this with javascript if the user press a button (not submit button).
How do I do this?
As I understand it, you want to assign a value to the property when a button is pressed?
Add it as a hidden input (sample uses Razor view engine):
#Html.HiddenFor(model => model.TheProperty)
Create a small jquery script:
<script type="text/javascript">
$('document').ready(function(){
// this is the id of the button that the user presses.
// It must have a "ID" attribute
$('#someButtonId').click(function() {
$('#TheProperty').val('Value to set');
});
});
});
</script>
You could use AJAX to send a request to the server with javascript. jQuery has great methods for doing so such as $.ajax, $.post, $.get. Example:
$(function() {
$('#someButtonId').click(function() {
// when some button is clicked send an AJAX request:
$.ajax({
url: '/home/someaction',
data: { someField: 'some value to send' },
success: function(result) {
alert('value successfully sent to server');
}
});
});
});

Categories

Resources