Javascript/Ajax/Json: Sending objects and arrays - javascript

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"];

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'];

Submit form data as JSON

I have to recreate a form that was originally created using Jotform - it is here. I am struggling in one area. It is a pretty simple form, the only caveat being the ability to duplicate a form field form multiple entries. That part can be seen here. When the form is duplicated, I need to submit the form data as a JSON array. In the fiddle, I didn't put the regular form fields, here is how they and the cloned field need to submit the data.
q2_fullName[first]:test
q2_fullName[last]:test
q1_currentCommission1:[{"Instruments":"a","Commissions":"1","Margins":"a"},{"Instruments":"b","Commissions":"2","Margins":"b"},{"Instruments":"c","Commissions":"3","Margins":"c"}]
normally in my $.ajax handler, I just serialize the data, but that doesn't work in creating the json array for the cloned fields. Normally like so:
submitHandler: function(form) {
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url: form.action,
data: dataString,
dataType: "json",
beforeSend: function(data){
//before send
},
success: function(data){
//success function
}
});
return false;
},
I need to somehow serialize the non cloned fields (I think) and create a json array out of the cloned values and assign them a key name
You can build the post data and the json string like this :
var data = {
// get/set the firstname etc
"q2_fullName":{
"first":"", // get firstname ie $("#first_2").val(),
"last":""
},
"q1_currentCommission1" :""
},
commisions = [];
$('.InsContain').each(function() {
var $inputs = $(this).find('input');
commisions.push({
"Instruments" : $inputs.eq(0).val(),
"Commissions" : $inputs.eq(1).val(),
"Margins" : $inputs.eq(2).val()
});
});
data.q1_currentCommission1 = JSON.stringify(commisions);
Posted data :
q2_fullName[first]:aaa
q2_fullName[last]:123
q1_currentCommission1:[{"Instruments":"1","Commissions":"1","Margins":"1"}]
Update fiddle here

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.

checking instantly php arrays using jquery / ajax

I want to be able to check whether values exist in the php array without having to click the submit button to do those checks using jquery/ajax.
when users enter an abbreviation in the text field want to be able to show that the brand exists (either vw or tyta) or not (as they type in the input box) and show the results in the carnamestatus div.
I was following a tutorial from youtube, however it queried against a mysql database.
I was wondering if this is possible using php arrays instead of mysql? I would be grateful if you could pick any faults in the code.
the code is as follows:
<?php
$car = array()
$car["vw"] = array( "name" => "volkswagen");
$car["tyta"] = array( "name => "toyota");
?>
the html code is as follows:
<label for="carname">Car Code:</label> <input type="text" onblur="checkcar()" value="" id="carname" />
<div id="carnamestatus"></div>
the checkcar()
function checkcar(){
var u = _("carname").value;
if(u != ""){
_("carname").innerHTML = 'checking ...';
var B = new XMLHttpRequest();
B.open("POST","check.php",true); /
B.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
B.onreadystatechange = function() {
if(B.readyState==4 && B.status== 200) {
_("carnamestatus").innerHTML = B.responseText;
}
}
var v = "carnamecheck="+u;
B.send(v);
}
}
</script>
Use Javascript keyboard event and then, send the value of the input into your php function.
For example:
$("#youInput").keyup(
function() {
$.ajax(
{
type: "post",
url: "your_url.php",
data: {params: $(this).val()},
success: function(data) {
console.log(data)
}
}
);
}
);
And in you php code, just retrieve the params value, $_POST['params']
Explain
When you press the keybord, your retrieve the value of the input ( here, it is $(this).val() where this represents #yourInput ), then you send the value via ajax (Here we use post type) with your url and the different params that you will send to the server side. If you post the value with $_POST['params'] you will get the value entered in the input. And if it's success, the callback function will retrieve the data returned by your server side.
Here, we just use, jQuery.ajax but you can find more about ajax here or here. Using library make it easy to work with.
Hope it helps you!

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

Categories

Resources