Reputation: 109
Actually I'm a PHP developer. I need a bit of Js in one of my projects. I have tried to search in google, but soon I found that I don't actually know what terms I should use. And learning entire Js is not possible now. What I need is, when user clicks a button, Js will send an API request, like http://example.com/?id=56, get the JSON encoded data and automatically insert them in a form with input fields, radio and check boxes. I think the code will be simple, if anyone can help, please do. Or if someone could at least point me to the right direction, like an article or a library it will be very helpful. Thanks in advance.
Upvotes: 1
Views: 199
Reputation: 980
You would want to use AJAX for this visit here. Here you would want to send the whole form from the requested page. But if you want to fetch the data in the form in the same page you would want to use AJAX with jQuery instead. You will get some introduction about it here.
Upvotes: 0
Reputation: 724
First of all, I think it would be better to have a proper understanding of javascript, instead of using the code without actually understanding what is going on.
One way of doing it using jQuery is the $.getJSON() method. You can download the jquery library here.
So the code to perform the action you are talking about would be something like this:
$.getJSON( "http://example.com?id=56", function( data ) {
// data contains the response from the server
// Assuming data contains:
// {
// "status": "success",
// "form_data": {
// "fname": "Kendrick",
// "lname": "Hanson",
// "age": "34",
// ...
// }
// }
// This assumes your form to be filled has a class of "js-filled" on it
$('form.js-filled').find('.first-name').val(data.form_data.fname); // Fill the input field with class "first-name" with the fname in the response
$('form.js-filled').find('.last-name').val(data.form_data.lname); // Fill the input field with class "last-name" with the lname in the response
});
Upvotes: 2