How to POST this Output to the API - javascript

Hi i have create a JSON object getting data from a form and now i want to POST that into redmine API. This is what i have done so far.
<script>
// This is the creation of JSON object
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return {"project":o};
};
// This is the API linking and POSTING
$(document).ready(function(){
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'http://localhost/redmine/projects.json', // url where to submit the request
type : "post", // type of action POST || GET
dataType : 'jsonp',
headers: { 'X-Redmine-API-Key': 'admin' },
data : JSON.stringify($('form').serializeObject()), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
alert("Sucess");
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
<form action="" method="post">
First Name:<input type="text" name="name" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="identifier" maxlength="36" size="12"/> <br/>
<!-- number:<input type="number" name="number" maxlength="36" size="12"/> <br/> -->
<textarea wrap="physical" cols="20" name="description" rows="5">Enter your favorite quote!</textarea><br/>
<p><input type="submit" /></p>
</form>
The post doesn't work. JSON object is created well, Passing that to API is the problem. I think problem is here,
data : JSON.stringify($('form').serializeObject()),
How do i pass the created JSON Object above to data. Thanks

You can not use POST and custom headers with jsonp. What jsonp does to work across different domains is basically inserting a <script> tag that calls a callback when finished, e.g.
<script src="different.domain/api/projects.json?callback=done123"></script>
function done123 (result) {
// do something with result
}
The server (if it supports a jsonp call) then returns JavaScript (not JSON!) that looks like this:
done123({"name1":"val1","name2":{"name3":true,"name4":5}})
Which calls your function when done and works cross-domain because it uses a script tag.
If you run the script from the same domain that redmine is running, change the dataType: 'jsonp' to json. Depending on how redmine expects you to send the data (JSON-body vs. form-data), you might need to change the data value:
// When redmine API expects JSON post body
data : JSON.stringify($('form').serializeObject()),
// When redmine API expects multipart POST data
data : $('form').serializeObject()

Related

How to read post url request from javascript in PHP

I have form with inputs in html.
Then I added this javascript (jquery) stroke to read and collect all value or data from form.
var formData = $("#form").serialize();
When I
console.log(formData);
Output will show:
calc-ownership=ooo&calc-activity=restaurant&calc-tax=usn&calc-tax-2=charge&calc-bank=partners&calc-who-payments=client&operations_count=0&calc-nomenclature=slim&documents_count=0&calc-who-docs=client&staff_count=0&calc-more%5B%5D=patent&calc-more%5B%5D=alcohol&period=&price=&price_sber=&rate-name=&email-to=
Then I found function in jquery called post
$.post(path, formData, success, "json");
Request look like:
do.php?bank=partners
As you see it makes post request to my do.php.
Now how I can read this query and work with this data?
I found analog to $.post in jquery. It is $.ajax
Full code:
$.ajax({ url: path, method: "POST", data: {formData: formData} });
It works well.
But I want to work with $.post
I am looking at my url at the moment. And it looks : https://stackoverflow.com?ask=32321
I need something similar to read my query from javascript this url with php
Ok I will explain with example,
If you want to get url parameter values to you have to use,
<script>
let my_variable='<?php echo $_GET['url_param_name'];?>';
</script>
above for more help and understanding. Now you want to send form data to php for processing as I got your answer.
This is sample form.
<form id="my_form" name"my_form" method="POST" onsubmit="return send();">
First name:<br>
<input type="text" name="first_name" value="Mickey">
<br>
Last name:<br>
<input type="text" name="last_name" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
To post above form I will use javascript function,
<script>
function send() {
$.ajax
({
type: 'POST',
url: './path/your_php_file_where_form_data_processed.php',
data:$('#my_form').serialize(),
success: function () {
// do what you need to do on succeess
},
error: function (x, e) {
// for error handling
if (x.status == 0) {
console.log('You are offline!! - Please Check Your Network.');
} else if (x.status == 404) {
console.log('Requested URL not found.');
} else if (x.status == 500) {
console.log('Internal Server Error.');
} else if (e == 'parsererror') {
console.log('Error. - Parsing JSON Request failed.');
} else if (e == 'timeout') {
console.log('Request Time out.');
} else {
console.log('Unknown Error. - ' + x.responseText);
}
}
});
return false;
}
</<script>
Now you need to check carefully your form element names. In php file. Let's look it.
<?php
//include_once './../../classes/Database.php'; import if you have database configurations
//session_start(); make sure to use sessions if your site using sessions
if(isset($_POST))
{
var_dump($_POST); //this will echo your form inputed data.
//if you want use one by one posted data
echo $_POST['first_name'];
echo $_POST['last_name'];
}
else
{
echo 'Data not comes here';
}
?>
Thought this might help your task.
When you see the form elements as a query string, you're not making a POST request, but a GET request.
Change your Ajax code to:
$.ajax({
url: path,
type: "POST",
data: formData
});
What's changed:
I've changed method: 'POST' to the correct attribute: type: 'POST', which will make the Ajax request to make a POST request instead of the default GET.
Changed data: {formData: formData} to just data: formData. There's no need to post it as json when you've already serialized the data.
If you rather want to use $.post, then use:
$.post(path, formData);
Just to be clear, both the $.ajax and $.post-requests above will make identical requests.
Now, in your PHP-code, you can access the values like this:
$calcOwnership = $_POST['calc-ownership'];
...to get the posted data.
I would recommend that you read the documentation about the methods you're using:
jQuery Ajax
Dealing with forms in PHP
I may have misunderstood your question, but in php you can take values from post using $_POST['variable_name'].
<?php
$documents_count = $_POST['documents_count']
?>
In fact this, in your url is not a query, are variables. sorry if it's not what you asked.

Laravel: no data being sent via ajax

I made a custom Jquery plugin to help me easily send data via Ajax to the server that has been tailored to suit laravel, but apparently I am not able to send any data. when I use dd($request->all()) to check what has been sent to the laravel server, I receive an empty array in console implying that I have not sent anything. Below is my code
JS
(function($){
'use strict'
$.fn.lajax=function(options){
//overwrite options
var optns=$.extend({
dataType: 'json',
debug:false,
processData: true,
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
acceptedInputFile:'/*/',
//functions that are very similar to the ajax optns but differ a little
//as the paramters give easy access to the ajax form element
lajaxBeforeSend: function(form,formData,jqXHR,settings){},
lajaxSuccess: function(form,formData,data,textStatus,jqXHR){},
lajaxError: function(form,formData,jqXHR,textStatus,errorThrown){},
},options);
//loop through every form, 'this' refers to the jquery object (which should be a list of from elements)
this.each(function(index,el){
$(el).submit(function(e){
//prevent submission
e.preventDefault();
//form jquery instance & form data
var $form=$(this);
var formData = new FormData($form[0]);
//catch url where the ajax function is supposed to go
var url=$form.attr('action');
//check if REST based method is assigned
if($form.find('input[name="_method"]').length)
{
var method=$(this).find(':input[name="_method"]').val().toUpperCase();
if(optns.debug)
console.log("'"+method+"' method registered for form submission");
}
//If no REST method is assigned, then check method attr
else if($form.attr('method'))
{
var method=$form.attr('method').toUpperCase();
if(optns.debug)
console.log("'"+method+"' method registered for form submission");
}
//method is not assigned
else
{
var method='GET';
if(optns.debug)
console.log('The form that submitted has no method type assigned. GET method will be assigned as default');
}
//object that will be fed into jquerys ajax method
var ajax_options={
url: url,
method: method,
beforeSend: function(jqXHR,settings){
console.log(jqXHR);
console.log(settings);
if(optns.debug)
console.log('executing beforeSend function');
optns.lajaxBeforeSend($form,formData,jqXHR,settings);
},
success: function(data,textStatus,jqXHR){
if(optns.debug)
console.log('executing success function');
optns.lajaxSuccess($form,formData,data,textStatus,jqXHR)
},
error: function(jqXHR,textStatus,errorThrown){
if(optns.debug)
console.log('error encountered. ajax error function procked');
optns.lajaxError($form,formData,jqXHR,textStatus,errorThrown);
var errors = jqXHR.responseJSON;
console.log(errors);
},
}
//check if files are included in the submitted form if the method is not GET
if($form.find('input:file').length && method!='GET'){
ajax_options.processData=false;
ajax_options.contentType=false;
ajax_options.cache=false;
ajax_options.data=formData;
}
if(optns.debug)
console.log('About to send ajax request');
//sending request here
$.ajax(ajax_options);
if(optns.debug)
console.log('finished with form '+$form+'. Looping to next form if exists');
return false;
});
});
return this;
}
}(jQuery));
HTML
<form class="lajax" action="{{ action('AlbumController#store') }}" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Album Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="coverFile">Album Cover Image</label>
<input name="cover" type="file" id="coverFile">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="form-group">
<label for="albumFiles">Album Images</label>
<input type="file" name="photos[]" multiple>
</div>
<button type="submit" class="btn btn-primary">Create Album</button>
</form>
I think my JS is not sending my data over to the server but im not sure why. Please help
Did you define a Post route in your route file that exactly point to AlbumController#store Controller method

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.

How to send a JSON object using html form data

So I've got this HTML form:
<html>
<head><title>test</title></head>
<body>
<form action="myurl" method="POST" name="myForm">
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="lname"></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
</html>
Which would be the easiest way to send this form's data as a JSON object to my server when a user clicks on submit?
UPDATE:
I've gone as far as this but it doesn't seem to work:
<script type="text/javascript">
function submitform(){
alert("Sending Json");
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
var j = {
"first_name":"binchen",
"last_name":"heris",
};
xhr.send(JSON.stringify(j));
What am I doing wrong?
Get complete form data as array and json stringify it.
var formData = JSON.stringify($("#myForm").serializeArray());
You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it. You'll then get all data in an array.
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
HTML provides no way to generate JSON from form data.
If you really want to handle it from the client, then you would have to resort to using JavaScript to:
gather your data from the form via DOM
organise it in an object or array
generate JSON with JSON.stringify
POST it with XMLHttpRequest
You'd probably be better off sticking to application/x-www-form-urlencoded data and processing that on the server instead of JSON. Your form doesn't have any complicated hierarchy that would benefit from a JSON data structure.
Update in response to major rewrite of the question…
Your JS has no readystatechange handler, so you do nothing with the response
You trigger the JS when the submit button is clicked without cancelling the default behaviour. The browser will submit the form (in the regular way) as soon as the JS function is complete.
Use FormData API
Capture the form data using FormData API formData= new FormData(form)
Convert it into JSON using JSON.stringify(Object.fromEntries(formData))
Send this strigified json as ajax payload
var form = document.getElementById('myForm');
form.onsubmit = function(event){
var xhr = new XMLHttpRequest();
var formData = new FormData(form);
//open the request
xhr.open('POST','http://localhost:7000/tests/v1.0/form')
xhr.setRequestHeader("Content-Type", "application/json");
//send the form data
xhr.send(JSON.stringify(Object.fromEntries(formData)));
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
form.reset(); //reset form after AJAX success or do something else
}
}
//Fail the onsubmit to avoid page refresh.
return false;
}
Taken from an article I wrote here: https://metamug.com/article/html5/ajax-form-submit.html
You can try something like:
<html>
<head>
<title>test</title>
</head>
<body>
<form id="formElem">
<input type="text" name="firstname" value="Karam">
<input type="text" name="lastname" value="Yousef">
<input type="submit">
</form>
<div id="decoded"></div>
<button id="encode">Encode</button>
<div id="encoded"></div>
</body>
<script>
encode.onclick = async (e) => {
let response = await fetch('http://localhost:8482/encode', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
let text = await response.text(); // read response body as text
data = JSON.parse(text);
document.querySelector("#encoded").innerHTML = text;
// document.querySelector("#encoded").innerHTML = `First name = ${data.firstname} <br/>
// Last name = ${data.lastname} <br/>
// Age = ${data.age}`
};
formElem.onsubmit = async (e) => {
e.preventDefault();
var form = document.querySelector("#formElem");
// var form = document.forms[0];
data = {
firstname : form.querySelector('input[name="firstname"]').value,
lastname : form.querySelector('input[name="lastname"]').value,
age : 5
}
let response = await fetch('http://localhost:8482/decode', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
let text = await response.text(); // read response body as text
document.querySelector("#decoded").innerHTML = text;
};
</script>
</html>
you code is fine but never executed, cause of submit button [type="submit"]
just replace it by type=button
<input value="Submit" type="button" onclick="submitform()">
inside your script;
form is not declared.
let form = document.forms[0];
xhr.open(form.method, form.action, true);
I'm late but I need to say for those who need an object, using only html, there's a way. In some server side frameworks like PHP you can write the follow code:
<form action="myurl" method="POST" name="myForm">
<p><label for="first_name">First Name:</label>
<input type="text" name="name[first]" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="name[last]" id="lname"></p>
<input value="Submit" type="submit">
</form>
So, we need setup the name of the input as object[property] for got an object. In the above example, we got a data with the follow JSON:
{
"name": {
"first": "some data",
"last": "some data"
}
}
If you want to use pure javascript in 2022...
const ajax = async (config) => {
const request = await fetch(config.url, {
method: config.method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(config.payload)
});
response = await request.json();
console.log('response', response)
return response
}
// usage
response = ajax({
method: 'POST',
url: 'example.com',
payload: {"name": "Stackoverflow"}
})
The micro-library field-assist does exactly that: collectValues(formElement) will return a normalized json from the input fields (that means, also, checkboxes as booleans, selects as strings,etc).
I found a way to pass a JSON message using only a HTML form.
This example is for GraphQL but it will work for any endpoint that is expecting a JSON message.
GrapqhQL by default expects a parameter called operations where you can add your query or mutation in JSON format. In this specific case I am invoking this query which is requesting to get allUsers and return the userId of each user.
{
allUsers
{
userId
}
}
I am using a text input to demonstrate how to use it, but you can change it for a hidden input to hide the query from the user.
<html>
<body>
<form method="post" action="http://localhost:8080/graphql">
<input type="text" name="operations" value="{"query": "{ allUsers { userId } }", "variables": {}}"/>
<input type="submit" />
</form>
</body>
</html>
In order to make this dynamic you will need JS to transport the values of the text fields to the query string before submitting your form. Anyway I found this approach very interesting. Hope it helps.

post method not working

I want to submit form data using post using ajax because in form post after submit it is redirected to a new page.
<form id="myContactForm">
<p>
<label for="byour_name">Your name</label><input type="text" name="byour_name" value="" id="byour_name">
</p>
<p>
<label for="byour_email_address">Your email address</label><input type="text" name="byour_email_address" value="" id="byour_email_address">
</p>
<p>
What's on your mind?<br>
<textarea name="Message" rows="10" cols="25"></textarea>
</p>
<p>
<input type="submit" value="Send it!" onClick="sendMail()">
</p>
</form>
function sendMail() {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),
success: function( response) {
alert(response);
},
error: function() {
alert('failure');
}
});
}
Every time I make request error function is executing.I am writing app on google app engine. I am keep getting this error:
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
My post request handler is:
def post(self):
Content = self.request.get("Message")
byName = self.request.get("byour_name")
byEmailAddress = self.request.get("byour_email_address")
gmailUser = 'id#gmail.com'
gmailPassword = 'password'
dataSend = byName
mail.send_mail(sender = gmailUser,
to = gmailUser,
subject ="Email Sent By : "+ byName + "#" + byEmailAddress,
body = Content)
self.response.out.write(byEmailAddress)
And after I click submit button URl changes to:
http://localhost:8080/?byour_name=username&byour_email_address=userEmail#gmail.com%40gmail.com&Message=mlm%0D%0A#contact
as I am making a get request can someone help me..But how post request changes to get request.
You're not preventing the default submit. Either return false from your sendMail function, or take the event as a parameter and call preventDefault() on it.
Please remove form tag and the get the desired values by id and then use ajax method. Because may be ajax post and form request method are conflicting. I think form has default get method as you said earlier may be that's the reason whenever you click on submit first ajax post make request soon after form get method and may be that's the reason the error is thrown by your server.
I think I know what your trying to do , to fix this you can do the following:
remove onclick="sendMail()"
and change your JavaScript function to something like:
$('#myContactForm').submit(function () {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),success:
function( response) {
alert(response);
},
error: function(){
alert('failure');
}
});
});

Categories

Resources