How to turn HTML POST data into JSON? - javascript

'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.

Related

Javascript typeahead after 3 characters

I want to send a query string to back end after 3 characters, and have the results used for typeahead.
Currently the I get the data back, no error on console, but there is no suggestions in the type ahead. The back end is spring-boot.
It might be something to do with scope of data array but I am not sure.
CODE:
// doc ready....
$('#queryStation').keyup(function() {
var stationName = $(this).val();
if(stationName.length==3){
ajax_search(stationName);
}
});
function ajax_search(stationName){
var stationJson = '{ "name":"' +stationName+ '"}'
$.ajax ({
url: "/station",
type: "POST",
data: stationJson,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){
$('#queryStation').typeahead({
source: data
});
}
});
}
and html snip:
<div class="col-md-5">
<label class="control-label control-label-left">Station</label>
<input type="text" class="form-control typeahead" name="query" id="queryStation" placeholder="Type Station" data-provide="typeahead" autcomplete="off">
</div>
The array of objects being sent back in data look like [ {id:237, name:"LAX"},{id:155,name:"SFO"}....
It was working when I used $.get instead of ajax POST:
$.get("/station", function(data) {
console.log(data);
$("[name='query']").typeahead({
source: data,
minLength: 3
});
}, 'json');
The data returned when using $.get looked like [{"id":1,"name":"LAX","}... - I see that the key names now are enclosed in " .
UPDATE
It appears the problem is to do with the way the data is returned from the server:
data = [{"id":113,"name":"LAX"}] // Works - $.get
data = [{id:113,name:"LAX"}] // Does not work - $.ajax with POST
data = "[{"id":113,"name":"LAX"}]" // Does not work - JSON.stringify result
So to get it to work it seems the spring-boot object sent back needs the keys wrapped in quotes. How do do this?

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

Wp_admin ajax request returns with response "0"

I am new to code, and trying to learn things by doing them.
Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.
I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.
But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?
I have the following code at the moment.
//Button
<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">
//Ajax Call
$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');
var adminAjaxRequest = function(formData, myaction) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
},
success: function(response) {
if (true === response.success) {
alert('success');
} else {
alert(response);
}
}
});
};
userSubmitButton.addEventListener('click', function(event) {
event.preventDefault();
var formData = {
'name': document.getElementById('name').value
};
adminAjaxRequest(formData, 'data_submission');
});
});
And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.
function data_submission(){
wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );
Could not locate where the faulty is. Some help would be appriciated
tks
Use add_action(' wp_ajax_myaction', 'yours_callback_fanc');
wp_ajax_
Remain part is yours action name that is defined into yours ajax call. In yours case it's myaction.
First this is not a standard way to use ajax in wordpress,
use wp_localize_script for embedding the global ajax_url variable,
wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));
Now as url in ajax you can add my_ajax_url.ajax_url,
this will send a request to admin-ajax.php.
Now coming to your question
you are returning an wp_json_error so the result is 0,
use this and return whatever data you wants in ajax success,
$responce['result'] = 1
wp_send_json( $response );

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

submitting form and variables together through jquery

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

Categories

Resources