Send form data with jquery ajax json - javascript

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.

Related

i want to send file to api url and get the response without redirecting to it using ajax

the code below is form with action api link
and thats my ajax request
$('#form1').submit(function(e) {
$.ajax({
type: "POST",
url: "http://www.example.com/uploader",
data: formdata,
success: function(data) {
alert(data);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://www.example.com/uploader" id="myForm" method="post" name="myForm">
NDA DOC: <input type="file" name="file1">
<input type="submit" id="submit">
</form>
when i send a file to that api it respond with data i want to get this data without redirecting to it this code in wordpress site
You need to add enctype in form tag and use preventDefault to prevent the refresh of page.
You need to serialize the data and send in data.
On the success area you need to deal with response.
HTML
<form action="http://www.example.com/uploader" id="form1" method="post" name="myForm" enctype="multipart/form-data">
NDA DOC: <input type="file" name="file1">
<input type="submit" id="submit">
</form>
JS
$('#form1').submit(function(e){
e.preventDefault();
let data = $( this ).serialize()
$.ajax({
type: "POST",
url: "http://www.example.com/uploader",
data: data,
success: function(response){
// success action here
},
error: function(response) {
// error action here
}
});
});
You just need to add the following code to your function in your submit event.
e.preventDefault();
because, normally it would submit the form.

form data upload multiple files through ajax together with text fields

Good day all,
I have a form wil multiple fields in it. Also, the form is being submitted through form data method using ajax to a php file.
The following is the javascript code submitting the form data.
$(".update").click(function(){
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('image',$('#picture').get(0).files[0]);
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
And, the following is the actual form:
<textarea name=body id=body class=texarea placeholder='type your message here'></textarea>
<input type=file name=image id=picture >
<input name=update value=Send type=submit class=update id=update />
This form and javascript work good as they are. However, I am trying to be able to upload multiple files to the php file using this one single type=file field attribute. As it is now, it can only take one file at a time. How do I adjust both the form and the javascript code to be able to handle multiple files uploads?
Any help would be greatly appreciated.
Thanks!
Here is ajax, html and php global you can access. Let me know if it works for you.
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Updated HTML:
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
Now, in PHP, you should be able to access your files:
// i.e.
$_FILES['file-0']
Here's another way.
Assuming your HTML is like this:
<form id="theform">
<textarea name="body" id="body" class="texarea" placeholder="type your message here"></textarea>
<!-- note the use of [] and multiple -->
<input type="file" name="image[]" id="picture" multiple>
<input name="update" value="Send" type="submit" class="update" id="update">
</form>
You could simply do
$("#theform").submit(function(e){
// prevent the form from submitting
e.preventDefault();
$.ajax({
url: 'post_reply.php',
type: 'POST',
contentType:false,
processData: false,
// pass the form in the FormData constructor to send all the data inside the form
data: new FormData(this),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
Because we used [], you would be accessing the files as an array in the PHP.
<?php
print_r($_POST);
print_r($_FILES['image']); // should be an array i.e. $_FILES['image'][0] is 1st image, $_FILES['image'][1] is the 2nd, etc
?>
More information:
FormData constructor
Multiple file input

Image Upload at Google Appengine using AJAX and PHP

I'm trying to upload an image on Google appengine hosting using ajax and php and I always get server error 500
My approach is create upload url which will be later used to submit the form to:
<?php
$upload_url = CloudStorageTools::createUploadUrl('/upload_script', $options);
The form which will be submitted as soon as any change is made to the input type file:
<form <?php echo 'action="$upload_url"'; ?> enctype="multipart/form-data" method="post">
Files to upload: <br>
<input type="file" name="uploaded_files" size="40">
<input type="submit" value="Send">
</form>
Since I'm doing it using AJAX here is the ajax code:
$(document).ready(function () {
$('#form').on('submit',(function(event) {
event.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(){
console.log("success");
},
error: function(){
console.log("error");
}
});
}));
$("#browse").on("change", function() {
$("#form").submit();
});
});
This produces server error 500 when looking on it in console does anyone know where might be the problem?

How to replace or update existing content in textarea by using http.post method?

I plan to POST my text content to http://language.cs.usm.my/synthesis/read.php form's textarea which is third party web page, below is the form that i get from the URL.
<form method="post" action="">
<p>Key in sentences in Malay. </p>
<textarea name="malayText" rows="4" cols="100">Malaysia ialah sebuah negara raja berperlembagaan persekutuan di Asia Tenggara yang terdiri daripada 13 negeri dan tiga wilayah persekutuan. Ia menduduki bumi berkeluasan 329,847 kilometer persegi.</textarea>
<input type="submit" value="OK" name="submit" />
</form>
The method i use to post data as below:
$scope.AudioCont = function(){
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test:"Nama saya ialah Ali"
}
})
.then(
function (response) {
alert("The data has been posted");
console.log(response);
},
function () {
alert("Failed to post!");
})
}
How can i replace the content in the existing textarea with my data?
Thanks
you have to add ng-model on the input or textarea
<form method="post" action="">
<p>Key in sentences in Malay. </p>
<textarea name="malayText" rows="4" cols="100" ng-model="yourtextarea"></textarea>
<input type="submit" value="OK" name="submit" />
</form>
and in the controller get him with $scope.yourVarName
$scope.yourtextarea ;
$scope.AudioCont = function(){
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test:$scope.yourtextarea
}
})
.then(
function (response) {
alert("The data has been posted");
console.log(response);
},
function () {
alert("Failed to post!");
})
}
You need to use ng-model
<textarea name="malayText" rows="4" cols="100" ng-model="malayText">
and then you can readily access it in your controller
var req = $http({
method: 'POST',
url: 'http://language.cs.usm.my/synthesis/read.php',
data:{
test: $scope.malayText
}
I used ajax method to solve this problem with auto submit the form when i perform the POST action. Below is my code and solution:
$.ajax({
type: 'POST',
url: 'your url',
data: {'submit': 'submit', 'malayText' : "data that wish to POST"}, // you can use as much as data you want to send,
dataType: 'JSON' // so you can use the json_encode php function
});

Submit form using JS and AJAX

I have little problem with JS and AJAX, i dont know this languages. I know php and i have applied for position php developer, now i have some tasks to do and i stucked at one. It is simple task, form, submit, process information, store in DB, and send. Only problem is i have to use AJAX to submit form, i done little research and somehow i made wrote this code but it doesnt work.
<div>
<form method="POST" action="add.php" id="form">
<input type="email" name="email" id="email" value="Email">
<textarea name="content" id ="content">Message</textarea>
<input type="submit" value="Submit" id="submit">
</form>
Send messages from database
</div>
<script>
$(document).ready(function() {
// When click on button store values from form fields into variables
$("form").submit(function(event) {
event.preventDefault();
var email = $("#email").val();
var content = $("#content").val();
// Check if fields are empty
if (email=="" || content="") {
alert("Please fill all fields");
}
// AJAX code to submit form
else {
$.ajax ({
type: "POST",
url: ("#form").attr('action');
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
}
return false;
});
});
</script>
</body>
IN form can i use input type button instead of submit (so no need for preventDefault in JS) and in JS i do it
$("#submit").click(function.....
I think i have tried all combinations and when form is submited it goes with default, no JS activated...
SOLVED: problem was in IF statment, content="" instead of content=="", OMG how i overlooked that...
To answer your questions, yes you are right, you can use an input of type button and you don't necessary need to depend on submitting the form. Here is how you'd write it without form submission:
<div>
<form method="POST" action="add.php" id="form">
<input type="email" name="email" id="email" value="Email">
<textarea name="content" id ="content">Message</textarea>
<input type="button" value="Submit" id="submit" onclick="SendAjax();">
</form>
Send messages from database
</div>
<script>
// When click on button store values from form fields into variables
function SendAjax() {
var email = $("#email").val();
var content = $("#content").val();
// Check if fields are empty
if (email=="" || content=="") {
alert("Please fill all fields");
}
// AJAX code to submit form
else {
$.ajax ({
type: "POST",
url: "type your URL here",
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
}
}
</script>
As you can see, I prefer to specify the URL in AJAX instead of taking it from the form's action which I sometimes have it set to a different URL from the AJAX. However, if you want to take the URL from the form's action, then fix that line in your code to be:
url: $("#form").attr('action'),
Use the serialize() method (described bellow) instead of manually getting the value of each field of your form in order to build the JSON object.
$('#form').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function() {
alert("Data successfully forwarded to add.php");
}
});
return false;
});
You have a syntax error in your ajax call.
$.ajax ({
type: "POST",
url: ("#form").attr('action'); // This is bad JSON
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
Replace that line with:
url: $("#form").attr('action'),

Categories

Resources