send json form data to server - javascript

I am trying to take data from a form and send it to remote server :
The code is:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<h2>Create Sensor</h2>
<form id="form">
<form enctype='application/json'>
<input name='version' value='1.0.1'>
<input name='sensors[0][sensor]' value=''>
<input name='sensors[0][output][0][name]' value=''>
<input name='sensors[0][output][0][type]' value=''>
<br>
<input id="input" type="submit" name="submit" value="Create Sensor" />
</form>
<script>
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
$(document).ready(function() {
$('#input').click(function() {
var send = $("#form");
$.ajax({
url: "http://posttestserver.com/post.php",
type: "POST",
data: send,
success: function (sreg, status, jqXHR) {
alert(JSON.stringify(sreg));
},
error: function (jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
});
});
</script>
</body>
</html>
But the JSON is not properly formed as I am returning by alert. Can anyone please help me out? I am not good at coding just trying to learn
This is the expected JSON:
{
"version": "1.0.1",
"sensors": [
{
"sensor": "",
"output": [
{
"name": "",
"type": ""
}
]
}
]
}
Another query is : is there any online platform through which I can get expected JSON by inputing JSON form like this? Please help me out

Your script at: post.php should work with form data and return a JSON Object.
To send array data to your script you should use.
var send = $("#form").serializeArray();
You can easy check if your JSON is valid here:
http://jsoneditoronline.com/

Related

Ajax call and PHP form submission not working together?

I am facing an issue while sending the data through the PHP script, in Index.php there is a form with some field values and a JavaScript script included in the Index.php which posts an image after I submit the form in Index.php with help of ajax, but Image is not posting/sending through ajax, only form field submission works.
If I call only Ajax during the time of form submission that is working or if I submit the form value all alone working, but if I call together the image is not working.
Index.php
<form enctype="multipart/form-data" method="post" action="saveRecord.php">
<?php include ('imagecropinterface/index.html'); ?>
<div>
<input autocomplete="off" type="text" maxlength="90" placeholder="HeadLine" id="headline" name="headline" style="width:386px;">
</div>
<div class="mt-2">
<input autocomplete="off" type="text" maxlength="90" name="subtitle" placeholder="Sub Title" style="width:386px;">
</div>
<div>
<input id='jour' type='text' value="" class=''>
</div>
<div>
<textarea name="fullText" placeholder="Synopsis" style="width:386px;"></textarea>
</div>
<input class="btn btn-secondary" name="save" id="btnid" value="Save" type="submit">
</form>
index.html
const downloadAllBtn = document.getElementById("btnid");
downloadAllBtn.addEventListener("click", downloadAll);
function downloadAll() {
$.ajax({
type: "POST",
url: "/ap-beta2/saveRecord.php",
data: {
data: imagesBase64,
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
console.log(data);
},
});
}
saveRecord.php
if (isset($_POST['save']) && isset($_POST['data'])) {
echo ($_POST[data]);
echo ($_POST['headline']);
echo ($_POST['subtitle']);
}
How can I submit the form so that form value and ajax call POST together to the PHP page?
As suggested by #ADyson I have updated Ajax script, unfortunately, no progress!!
In the form, I put the id saveform
<form enctype="multipart/form-data" id = "saveform" method="post" action="saveRecord.php">
function downloadAll() {
$("#saveform").click(function (e) {
$.ajax({
type: "POST",
url: "https://myimpact.in/ap-beta2/saveRecord.php",
data: {
data: imagesBase64,
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
console.log(data);
},
});
e.preventDefault();
});
}

Why method not allowed http exception?

I have a form in laravel.
I want to send the data to server using ajax post request.
The laravel give me error. I dont know why?
My view source url is : http://localhost/lily/public/search
(1/1) MethodNotAllowedHttpException
in RouteCollection.php (line 251)
at RouteCollection->methodNotAllowed(array('GET', 'HEAD'))
in RouteCollection.php (line 238)
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready( function () {
$("#submit").submit( function(){
var name = $("#name").val();
console.log(name);
$.ajax({
type: "POST",
url : "{{url('/search')}}",
data : name ,
success : function(data)
{
console.log(data)
},
error : function(error)
{
console.log(error)
}
});
});
});
</script>
<div class="col-md-6 offset-3">
<form id="submit" method="POST">
<input type="name" name="name" id="name">
<button type="submit" class="btn btn-success">search</button>
</form>
</div>
</body>
</html>
Route::post('/search/{name}', 'HomeController#in');
public function in() {
return json("fdfdfdfdfdf");
}
You defined a a route for /search/parameter, but your action is only '/search'.
Remove the useless {name} part in the route. Or make it optional with {name?}
Pass the CSRF token along with the request, after changing your route definition to either remove {name} or making it optional {name?} then change your data to
$(document).ready(function() {
$("#submit").submit(function() {
e.preventDefault(); // Prevent the Default Form Submission
var name = $("#name").val();
console.log(name);
$.ajax({
type: "POST",
url: "{{ url('/search') }}",
data: {
name: name,
_token: "{{ csrf_token() }}"
},
success: function(data) {
console.log(data)
},
error: function(error) {
console.log(error)
}
});
});
});
The input type should be text instead of name in the form
<input type="text" name="name" id="name">
Because you did not add CSRF token value as a hidden type.
You must add CSRF hidden input to Form.
<input type="hidden" name="_token" value="{{ csrf_token() }}" />

How to send image file from local machine to server using jquery ajax request

I have an html form with input type = file, I have a link to API to store images to cloud. In this feature, a user can upload a file from his local machine and upload it to the server. The server returns the cloud url of the uploaded image. In postman it is working fine, but when using with jquery I am not able to figure out how to accomplish this. In postman There are several parameters set like filename, tag and employeeID. In file name field there is choose file button and form-data radio button is checked.
This is my jquery code so far
$("#test-btn").on("click", function() {
$.ajax({
url: 'myURL/external/upload',
type: 'POST',
headers: {
"appID": "some value",
"version": "some value",
"empID": "some value",
"contentType": "application/x-www-form-urlencoded"
},
data: new FormData($("#test-form")),
processData: false,
contentType: false,
success: function() {
console.log(data)
},
error: function(e) {
console.log(e)
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post" name="upload-image" id="test-form">
<input type="file" name="filename" />
<input type="text" name="tag" value="some value" />
<input type="text" name="empID" value="some value" />
</form>
<button id="test-btn">make</button>
I've replaced the confidential fields with dummy values.
$("form#test-form").submit(function(){
var formData = new FormData(this);
$.ajax({
url : 'myURL/external/upload',
type : 'POST',
data: formData,
async: false,
// your other config, params
success : function(){console.log(data)},
error : function(e){console.log(e)}
});
return false;
});
or you can try:
<form enctype="multipart/form-data" method="post" name="upload-image" id="test-form" action="myURL/external/upload">
<input type="file" name="filename" />
<input type="text" name="tag" value="some value" />
<input type="text" name="empID" value="some value" />
</form>
<button id="test-btn">make</button>
$("form#test-form").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});

Send form data with jquery ajax json

I'm new in PHP/jquery
I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.
Is there anyway to do that?
Thanks for the help!
Edit:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
You can use serialize() like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
Why use JQuery?
Javascript provides FormData api and fetch to perform this easily.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then(…);
//Dont submit the form.
return false;
}
Reference:
https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe#gmail.com" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.

Jquery Datatables populate after form post

I'm trying to do a form submit (POST) with some parameters and based on the parameters I want to populate my datatable. But I'm not very good with Javascript (My language is Java), so I'm trying to do it with an Ajax call. But it won't work for me. Everything works for me, except doing a POST with parameters to the servlet. The datatable always populate automatically, but it should populate after the form submit.
Does someone know an example of my case? I read a lot of form posts here and tutorials, but none of this case (?).
My code is now as follows, this works for me. Except I can't sort or search anymore in this table. What is missing?
Thank you.
<script type="text/javascript" language="javascript" src="/global/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript" src="/global/js/jquery.dataTables.min.js"></script>
<form name="myform" id="myform" action="" method="POST">
<label for="season">Season:</label>
<input type="text" name="season" id="season" value=""/> <br />
<label for="type">Type:</label>
<input type="text" name="type" id="type" value=""/> <br/>
<input type="button" id="btnSubmit" name="btnSubmit" value="Search">
</form>
<table class="display" id="example">
<thead>
<tr>
<th>Name</th>
<th>NationId</th>
<th>RegionId</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
<!-- data goes here -->
</tbody>
</table>
<script>
$("#btnSubmit").click( function() {
var formData = "season=" + $("input#season").val() + "&type=" + $("input#type").val();
$('#example').dataTable( {
"bJQueryUI": true,
"bProcessing": true,
"bDestroy": true,
"sAjaxSource": "/servlets/service/competitions/",
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
oSettings.jqXHR = ${esc.d}.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": formData,
"success": fnCallback
} );
}
} );
} );
</script>
Ok, this is the full answer for you question
You need to make three events, the first load the database information in your datatable, the second event inserts the new information on the database, and the third refresh the datatable content.
<html>
<head>
<script type="text/javascript" language="javascript" src="/global/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript" src="/global/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
//Global variables
var otable;
var dataTab;
$(document).ready(function () {
chargeData();
$('#btnSubmit').click(function () {
insertData();
});
});
// 1. charge all data
function chargeData() {
$.ajax({
type: "POST",
//create a method for search the data and show in datatable
url: "/servlets/service/competitions/",
contentType: "application/json; charset=utf-8",
data: '{ }',
dataType: "json",
success: AjaxGetFieldDataSucceeded,
error: AjaxGetFieldDataFailed
});
}
function AjaxGetFieldDataSucceeded(result) {
if (result != "[]") {
dataTab = $.parseJSON(result);
//instance of datatable
oTable = $('#example').dataTable({
"bProcessing": true,
"aaData": dataTab,
//important -- headers of the json
"aoColumns": [{ "mDataProp": "season" }, { "mDataProp": "type" }],
"sPaginationType": "full_numbers",
"aaSorting": [[0, "asc"]],
"bJQueryUI": true,
});
}
}
function AjaxGetFieldDataFailed(result) {
alert(result.status + ' ' + result.statusText);
}
// 2. this function only insert the data in your database
function insertData() {
var email = $("#season").val();
var evento = $("#type").val();
$.ajax({
type: "POST",
//in this method insert the data in your database
url: "/servlets/service/competitions/",
contentType: "application/json; charset=utf-8",
data: '{ season : "' + season + '", type : "' + type + '"}',
dataType: "json",
success: AjaxUpdateDataSucceeded,
error: AjaxUpdateDataFailed
});
}
function AjaxUpdateDataSucceeded(result) {
if (result != "[]") {
alert("update ok");
refreshDatatable();
}
}
function AjaxUpdateDataFailed(result) {
alert(result.status + ' ' + result.statusText);
}
// 3. This function refresh only the datatable not all page in varius events you can call like INSERT,UPDATE,DELETE ;D
function refreshDatatable() {
$.ajax({
type: "POST",
//same event used in chargeData function
url: "/servlets/service/competitions/",
contentType: "application/json; charset=utf-8",
data: '{ }',
dataType: "json",
success: AjaxRefreshDataSucceeded,
error: AjaxRefreshDataFailed
});
}
function AjaxRefreshDataSucceeded(result) {
if (result.d != "[]") {
var jposts = result;
dataTab = $.parseJSON(jposts);
//when the instance of datatable exists, only pass the data :D
oTable.fnClearTable();
oTable.fnAddData(dataTab);
}
}
function AjaxRefreshDataFailed(result) {
alert(result.status + ' ' + result.statusText);
}
<script>
</head>
<body>
<form name="myform" id="myform" action="">
<label for="season">Season:</label>
<input type="text" name="season" id="season" value=""/> <br />
<label for="type">Type:</label>
<input type="text" name="type" id="type" value=""/> <br/>
<input type="button" id="btnSubmit" name="btnSubmit" value="Search">
</form>
<table class="display" id="example">
<thead>
<tr>
<th>SEASON</th>
<th>TYPE</th>
</tr>
</thead>
<tbody>
<!-- data goes here -->
</tbody>
</table>
</body>
</html>
Here the data is passed as string(formData) in ajax function and by default ajax expect the json object. Passing data in string can be done in two ways
1) Append the generated query string to the url
oSettings.jqXHR = ${esc.d}.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource + "?" + formData, /* here url need be proper, as url can have some query string params in that case it shoukd be join with "&" not "?" */
/* "data": formData, no need to have data config then */
"success": fnCallback,
"processData": false
} );
2) when data is already serialized into string then set processData flag to false in ajax
oSettings.jqXHR = ${esc.d}.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": formData,
"success": fnCallback,
"processData": false
} );
I have the same functionality as you. The way I approach things though is a little bit different.
What I do ...
<input type="text" id="searchCondition"/>
<div id="container">
<div id="ajaxDataTable"></div>
</div>
On document.ready I call the ajax function to get me the datatable passing the value of searchCondition to my servlet. The result (THIS IS JUST THE TABLE) is put in the ajaxDataTable div. On success of the ajax command, I do the normal initializations on the datatable.
Now on any search, I call the same ajax command and pass again the search condition.
Works fine for me!

Categories

Resources