Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  112] [ 4]  / answers: 1 / hits: 142554  / 9 Years ago, sat, june 6, 2015, 12:00:00

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>

More From » php

 Answers
14

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


[#66305] Thursday, June 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
malaysias

Total Points: 619
Total Questions: 110
Total Answers: 107

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
malaysias questions
Wed, Jul 29, 20, 00:00, 4 Years ago
Fri, Jan 31, 20, 00:00, 4 Years ago
Fri, Dec 13, 19, 00:00, 5 Years ago
Thu, Dec 5, 19, 00:00, 5 Years ago
;