submitting form and variables together through jquery - javascript

I'm using 2 types of submit.
There is $.post
$.post('servers_side.php', { var1: var1, var2:var2},
function(result)
{
some code...
});
which sends separate variables to server side script.
And there is AjaxSubmit plugin which submits the whole form
$('#form').ajaxSubmit({success: function(result)
{
some code...
}
});
But now I have the following task let's say I have a form and a few variables which I must submit at the same time.
So Is that possible to submit form + some variables together ?

Update
And here is how you can submit:
var Vars = {var1: var1, var2:var2};
var varsData = $.param(Vars);
// form data
var formData = $('#formID').serialize();
var data = varsData + '&' + formData;
$.ajax({
type: 'POST',
url: 'servers_side.php',
data: data,
success: function(res){ alert (res) }
})
You can use jQuery.param() to convert an array or an object into url-friendly name-value paris. You may also need to use jQuery.serialize() to convert form data into name-value paris. Here is how you can go about:
var Vars = {var1: var1, var2:var2};
var varsData = $.param(Vars);
// form data
var formData = $('#formID').serialize();
var data = varsData + '&' + formData;
Now data contains all data of your custom vars and form elements you can send in ajax request.

Well, it's possible but code might look messy. As best practice you should add some hidden fields
<form>
.
.
.
<input type="hidden" name="var1" id="var1" />
<input type="hidden" name="var2" id="var2" />
<input type="hidden" name="var3" id="var3" />
.
.
.
</form>
And use this JavaScript to set values to these hidden fields
$("#var1").val("some data 1");
$("#var2").val("some data 2");
$("#var3").val("some data 3");
And you can carry on with your existing $.post() code

Related

How to send the values of multiple created input fields on php via ajax

I have there an example part of my form, (my form has 4 different fields/div like that) and i cannot think of how i can send the values of those created input fields on php via ajax. Sorry if i can't explain it well. I have searched for this but i can't get the exact answer i'm looking for.
<input type = "text" class = "form-control" placeholder="Knowledgeable/Proficient in.." name = "skills[]" >
I want to use a function which uses some kind of name="skills[]" (or array type) instead of something like name="skills1". tyia!
If you give the skill inputs a class like so
<input type="text" class="form-control skill-input" placeholder="Knowledgeable/Proficient in..">
You can then create an object from your form in javascript (example using jquery)
var skills = [];
$(".skill-input").each(function() {
skills.push($(this).val());
});
console.log(skills); //final array of skills
var resume = JSON.stringify({
firstName: $('[name=firstName]').val(),
lastname: $('[name=lastName]').val(),
skills: skills
});
$.ajax({
dataType: 'json',
url: './submit.php',
type: 'POST',
data: {resume:resume}
});
then on your submit.php you can have
$form = json_decode($_POST['resume'], true);
echo $form['skills'];

How to turn HTML POST data into JSON?

'recipient.firstName': 'Fred',
'recipient.lastName': 'Johnson'
Is there any elegant way to turn this into:
var recipient = {
firstName: 'Fred',
lastName: 'Johnson
}
Using JS on the frontend? I want to POST JSON but it doesn't seem like that is done very easily with HTML, therefore I want to intercept the POST with jQuery and format it into the JSON I want.
EDIT: I am leaving the original question above for clarity's sake, but if you read closely you will see that the issue I have is not posting the data with AJAX to a REST API. That's very simple and already implemented. What is happening is that I am dynamically building forms using a template engine that I have created, and the forms id and names are built to represent nested data such as recipient.firstName. However, when I receive this data passed as JSON to the API endpoint, I need to transform it programatically from the first format to the second format, which is what the question is actually asking if you read it closely. Sorry for any confusion, the answer I have listed below solves the question.
var recipient = [{firstName: "Fred",lastName: "Johnson"}]
//:: CONVERT TO JSON
recipient = JSON.stringify(recipient);
//:: POST THE DATA
$.post(LINK_url,{post_recipient : recipient },json/*:: json not important, it can be auto guessed. delete ',json' */,function(output){
//var data =jQuery.parseJSON(output);});
______________________________edit_______________________________________
if i get you right this time your output is plan text and you need to convert to json, if so try this.
var recip = JSON.stringify[{ output }];
var data = jQuery.parseJSON(recip);
var viewdata='';
$.each(data, function(key, recipient){viewdata +=
recipient.firstName +" "+recipient.lastName+"<br/>"
})
prompt(viewdata);
With jQuery with a form by Using serializeArray() and forEach and other object:
$(function() {
var recipient = $("#frm").serializeArray();
var output = {}; // Declare an object.
recipient.forEach(function(v, i) {
output[v.name] = v.value; // Assign the current value to the current key.
});
$.ajax({
url: "http://httpbin.org/post",
type: "POST",
data: JSON.stringify(output), // Send the object.
contentType: "application/json",
success: function(response) {
//console.log(response);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="frm" method="post">
firstName:
<br/>
<input id="firstName" name="firstName" type="text" value="Fred" />
<br />lastName:
<br/>
<input id="lastName" name="lastName" type="text" value="Johnson" />
<br />age:
<br/>
<input id="age" name="age" type="text" value="30" />
</form>
In the request, you send:
UPDATE
Now that I know your server side is NodeJs you simply need to learn how to call NodeJS server side methods:
How to send data from JQuery AJAX request to Node.js server
So your approach is just wrong, you have this unnecessarily complex string of data that you want to intercept. Do not intercept anything, send a well formatted HTTP POST from the start, with jQuery or Javascript to your server Controller or API. The signature of your API method should be:
DoSomethingWithRecipient(string firstName, string lastName);
Your recipient should have a userId as well but that is up to you. If you are not using a Server side framework that can parse the incoming the request and map it to your DoSomethingWithRecipient function like PHP or ASP.NET than you your reinventing the wheel for no reason most likely.
Than with jQuery you simply perform an Ajax HTTP Post like so:
var recipient = {
firstName: 'Fred',
lastName: 'Johnson'
}
var json = JSON.stringify(recipient);
$.ajax({
url: '/MyUrl/DoSomethingWithRecipient',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
},
error: function (result) {
}
});
This is what I am using:
_.forOwn(options, function(value, key) {
if(key.indexOf('.') != -1){
var split = key.split('.')
if( !global[split[0]] ) {
global[split[0]] = {}
}
global[split[0]][split[1]] = value
}
});
Using global as I'm using NodeJS on the backend.
Seems to work so far, I'll report back on if I finally end up using it.

Using Ajax and JSON to display PHP echo message in HTML

Ive been trying to connect my PHP file to my HTML file using Javascript/jQuery and json. When the user inputs a number into the input box in the form and submits it, the PHP file should multiply the number by two and send it back to the user.
However when I press the submit button it takes me to the php page instead of displaying the information (processed in the php file) in HTML.
This is my HTML form:
<div id="formdiv">
<form action="phpfile.php" method="get" name="form1" id="form1" class="js-php">
Mata in ett nummer: <input id="fill1" name="fill1" type="text" />
<input type="submit" id="submit1" name="submit1" value="submit">
</form>
This is my Javascript file
$(".js-php").submit(function(e){
var data = {
"fill1"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
$("#formdiv").append("Your input: "+data)
alert (data);
}
})
e.preventDefault();
});
PHP file:
$kvantitet = $_GET['fill1'];
$y = 2;
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
echo json_encode($work) ."<br>";
echo json_encode($bork);
There are a few things you could do a bit differently here to make this work:
Currently, using both .serialize and $.param your data variable contains something like this:
someurl.php?fill1=1&0=f&1=i&2=l&3=l&4=1&5=%3D&6=1
If you use only .serialize you will get something easier to work with:
?fill1=5
On the PHP side, currently your code outputs something like this:
4<br>8
By adding your values to an array you can get a response back that you can work with:
$result = array();
$kvantitet = $_GET['fill1']; // Lets say this is 5
$y = 2;
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
//add the values to the $result array
$result = array(
"work" => $work,
"bork" => $bork
);
echo json_encode($result);
Which will output:
{"work":4,"bork":8}
Back on the JS side you can then handle the data in your success callback:
$(".js-php").submit(function(e){
data = $(this).serialize();
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
// *data* is an object - {"work":4,"bork":8}
$("#formdiv").append("Your input: "+data)
console(data);
}
});
// Use return false to prevent default form submission
return false;
});
One way to access the properties in your object is by using dot notation:
data.work //Outputs 4
data.bork //Outputs 8
But here is a really great answer on processing / accessing objects and arrays using JavaScript.
Here is a Fiddle containing your (working) jQuery
You are expecting JSON Data but what you send back is not JSON
Try output the following in your PHP File:
$data['work'] = $work;
$data['bork'] = $bork;
echo json_encode( (object)$data );
Use console.log to inspect incoming data on the AJAX call then handle it according to how you want.
I think you need &
data = $(this).serialize()+'&'+$.param(data);
and as #leonardo_palma mentioned in comments maybe you need to use e.preventDefault(); in the beginning of submit function
and I prefer to use
$(document).on('submit','.js-php',function(){/*code here*/});

How to simply send a request parameter with jquery form submit?

I am able to submit a form as Post type using the following in my javascript:
$("#receiptsForm").submit();
But I also want send across a parameter myparam as well with the request which I'll be retrieving in my spring controller using httpServletRequest.getParameter("myparam"):
var myparam = "abc";
$("#receiptsForm").submit();
What's the best I can do?
try this
function form_submit()
{
//var myparam = "abc";
// add hidden field to your form name="myparam" and value="abc"
$('#receiptsForm').append('<input type="hidden" name="myparam " value="abc" />');
$("#receiptsForm").submit();
}
Try this,
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "mydata").val("bla");
$('#receiptsForm').append($(input));
$('#receiptsForm').submit();
Try using serializeArray
var data = $('#receiptsForm').serializeArray();
data.push({name: 'myparam', value: 'MyParamValue'});
You can send the data like:
$.ajax({
...
data: data,
...
});
Looks like you are using jquery..there are a couple of ways this can be done..either you can make it a object and then pass it as data in an ajaxrequest
var myparam = "abc";
var data_to_be_sent = {"myparam":myparam};
then in the data field of the ajax request, you can
data : data_to_be_sent.
Or you simply have a hidden field in the form and then on submit you can give it a value of myparam
There are two ways that spring to mind
a) include a hidden form field called myparam in your form, and the use jquery to populate it with abc before submitting.
b) use Jquery's ajax to call a ajax post, and before doing this set the data parameter.
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});

Javascript/Ajax/Json: Sending objects and arrays

I have a form where people enter their clients into.
This form allows the user to add as many phone numbers, emails, and addresses as they want.
Phone and email have type and data fields for each added row (phone_type, phone_data) while Address has type, street, city, state, and zip fields for each row (address_type, address_street, address_city, address_state, address_zip).
So for example, when the user adds a phone field it adds:
<input type="text" name="phone_type[]" />
<input type="text" name="phone_data[]" />
I need to send the form data over Ajax to a PHP to process and store in database.
I've thought of storing it in array within an object.
phone = new Object();
var phone.data = new Array(),
phone.type = new Array();
$("input[name='phone_data[]']").each(function() {
if($(this).val() != '') {
phone.data.push($(this).val());
phone.type.push($('select[name="phone_type[]"]').val());
})
This doesn't seem to work. Am I even approaching this correctly?
Also, once I get it into an object that I send over Ajax to a PHP page, how do I grab the values?
serialize your form... use data of ajax to sent the serialize data to the server...
data:$('#YourFORMID').serialize();
here is the documentaiotn have alook to the examples...
http://api.jquery.com/jQuery.post/
and to grab the data in your PHP (if you are using ajax type as post)
$data=$_POST['phone_data'];
$type=$_POST['phone_type'];
if ajax type : GET
$data=$_GET['phone_data'];
$type=$_GET['phone_type'];
Are you trying to reinvent jQuery's serialize()
var frm = $("#myForm");
var values = frm.serialize();
//make Ajax call
$.post("someUrl", values, function(){} );
http://jsfiddle.net/BZcja/
You can most definitely use jQuery serialize(). In your event which triggers the processing you can do the following:
$.ajax({
type: "POST",
url: "your_php_processing_page.php",
data: $("#FormID").serialize(),
dataType: "json",
success: function(data){
// do stuff here
},
error: function() {
// do stuff here
}
});
In your_php_processing_page.php you can get the values as follows:
$phone_types = $_POST["phone_type"];
$phone_data = $_POST["phone_data"];

Categories

Resources