i want to access a form with mootools.
My html code looks like:
<table border="0">
<tr>
<td>username</td>
<td><input type="text" id="username" value="bla "/></td>
</tr>
<tr>
<td>password</td>
<td><input type="password" id="password"/></td>
</tr>
<tr>
<td>project</td>
<td><input type="text" id="project"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" id="login" value="login"/></td>
</tr>
</table>
my JavaScript like:
window.addEvent('domready', function() {
//We are going to fill this with Mootools goodness
var jsonReq = new Request.JSON({
url: 'test.php',
method: 'post',
data: {
username: $('username').value,
password: $('password').value,
project : $('project').value
},
onSuccess: function( response )
{
if ( response.status )
{
document.location = "home.html"
}
else
{
$('response').addClass('error');
$('response').set('html', response.message);
alert( "Msg" + response.message );
}
},
// onRequest: function() { alert('Request made. Please wait...'); },
onError: function( response, err ) { alert('Faiure' + response + err); },
onFailure: function( response ) { alert('Faiure' + response); },
});
$('login').addEvent('click',function( event ){
event.stop();
jsonReq.send();
});
});
the problem is, if the value attribute is set, i can retriev this in my php script, but no changes.
so i alwayes see username=bla but no changes...
could someone help me ?
because the data object gets populated at domready state. at that time, there is no value.
you can do in the submit handler:
jsonReq.setOptions({
data: document.id('someform')
}).send();
you can pass an actual form element to data and it will serialize it for you. else, do what you did above
Related
I have never integrated an API into any of my app's before. I want to integrate a basic VIN decoder API, that will provide basic vehicle information after a vehicle's VIN is submitted. I want to use the NHTSA Vehicle API as it is free and simple. I am most familiar with Javascript and they provide a code example which I will provide below. How do I integrate this API into my simple HTML form? Thanks for your help!
Link to VIN Decoder: NHTSA VIN Decoder API
HTML:
<!DOCTYPE html>
<html>
<head>
<title>VIN Decoder API Test</title>
<style type="text/css">
input {width: 200px;}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<table align="center">
<tr>
<td align="center">
<input type="text" id="b12" placeholder="VIN - 17 Digits" name="name" maxlength="100">
</td>
</tr>
<tr>
<td align="center">
<button>Submit</button>
</td>
</tr>
<tr>
<td>
<textarea rows="15" cols="100" placeholder="Vehicle Data Presented Here"></textarea>
</td>
</tr>
</table>
</body>
</html>
"Javascript with jQuery, Get Example":
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/GetModelsForMakeId/440?format=json",
type: "GET",
dataType: "json",
success: function(result)
{
console.log(result);
},
error: function(xhr, ajaxOptions, thrownError)
{
console.log(xhr.status);
console.log(thrownError);
}
});
"Javascript with jQuery, Post Example":
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
data: { format: "json", data: "3GNDA13D76S000000;5XYKT3A12CG000000;"},
dataType: "json",
success: function(result)
{
console.log(result);
},
error: function(xhr, ajaxOptions, thrownError)
{
console.log(xhr.status);
console.log(thrownError);
}
});
HTML:
<table align="center">
<tr>
<td align="center">
<input type="text" id="b12" placeholder="Enter VINs-separated by ;" name="b12" maxlength="100"/>
</td>
</tr>
<tr>
<td align="center">
<button id="submit_btn">Submit</button>
</td>
</tr>
<tr>
<td>
<textarea rows="15" cols="100" id="results" placeholder="Vehicle Data Presented Here"></textarea>
</td>
</tr>
</table>
Javascript:
$("#submit_btn").click(function () {
var val = $("#b12").val();
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
data: { format: "json", data: val},
dataType: "json",
success: function(result)
{
$("#results").val(JSON.stringify(result));
},
error: function(xhr, ajaxOptions, thrownError)
{
console.log(xhr.status);
console.log(thrownError);
}
});
})
I'll leave it up to you to parse the results into what you want to present...
A few different things here. You should read up on how to use APIs using jQuery. Here's a quick but effective example I found elsewhere:
https://www.yogihosting.com/example-jquery-ajax-call-api/
First, set up your HTML to be easy to interact with JavaScript by adding an id to your button and your textarea elements:
<button id="btn_submit">Submit</button>
<textarea id="txt_results" rows="15" cols="100" placeholder="Vehicle Data Presented Here"></textarea>
Next, add an event listener for when the Submit button is clicked:
document.getElementById("btn_submit").onclick = function () {
var vin;
vin = document.getElementById("b12").value;
if (vin.length === 17) {
getNHTSADataByVIN(vin);
}
};
Now the fun part. In jQuery's AJAX calls, you get to decide what happens with the data you recieve from the call in the success parameter. In the API's example usage, you are able to do whatever you want with the result parameter once it is returned. Here is a function that will pass the result object into a function that will display the results (that we are about to write):
function getNHTSADataByVIN (param_vin) {
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
data: { format: "json", data: param_vin },
dataType: "json",
success: function(result)
{
console.log(result);
displayNHTSAResults(result);
},
error: function(xhr, ajaxOptions, thrownError)
{
console.log(xhr.status);
console.log(thrownError);
}
});
};
Finally, we create a function that takes the properties inside of the result objects and writes them out to the text area if the property isn't empty:
function displayNHTSAResults (param_data) {
var output_text = "";
for (var i = 0; i < param_data.Results.length; i++) {
var result = param_data.Results[i];
for (var prop in result) {
if (result.hasOwnProperty(prop) && result[prop] !== "") {
output_text += prop + ": " + result[prop] + "\n";
}
}
}
document.getElementById("txt_results").value = output_text;
};
Of course, there are many ways to do this, but hopefully this serves as a good simple demonstration of API usage.
async function CheckVin(vin) {
var response = await fetch(`https://vpic.nhtsa.dot.gov/api/vehicles/decodevin/${vin}?format=json`);
let result = await response.json();
result = result.Results.reduce((accumulator, crr) => {
if (crr.Value && crr.Value != 'Not Applicable') {
accumulator[crr.VariableId] = {
variable: crr.Variable,
value: crr.Value
}
}
return accumulator;
}, {})
if(result['143'].value !== '0'){
throw result['191'].value;
}
return result;
}
I have a table containing this kind of information
I am using knockout js and putting all data on a array and putting it on this table like this.
self.allchildrendata = ko.observableArray();
self.viewAllUserChildrenCard = function () {
$.ajax({
type: 'POST',
url: BASEURL + '/index.php/main/childrenCardInfo',
contentType: 'application/json; charset=utf-8',
dataType :'json'
})
.done(function(childrencards) {
self.allchildrendata.removeAll();
$.each(childrencards, function (index, childrencard) {
self.allchildrendata.push(childrencard);
console.log(self.allchildrendata());
});
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
self.viewAllUserChildrenCard();
So next I want to click the add money button for rebecca and want to send the orig id of only rebecca so I can use it to find her in the database and add money, But i am not sure on how to send the orig_id, I tried this way.
self.giveCashtoChild = function(){
$.ajax({
type: 'POST',
url: BASEURL + '/index.php/main/addUserChildrenCash' + "/" + self.allchildrendata().orig_id ,
contentType: 'application/json; charset=utf-8'
})
.done(function() {
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
}
Here is the html code where I have a databind on each of the buttons so I can send the orig id .
<tbody data-bind="foreach: allchildrendata">
<tr>
<td class="text-center"><span data-bind="text : $data.children_name"></span></td>
<td class="text-center"><span data-bind="text : $data.daugther_son"></span></td>
<td class="text-center"><span data-bind="text : $data.amount"></span> $</td>
<td class="text-center"><span class=" glyphicon glyphicon-send"></span></td>
<td class="text-center"><span class=" glyphicon glyphicon-trash"></span></td>
</tr>
</tbody>
So basically I need help to identify which family memeber I am clicking and sending that family memebers orig_id
Whenever you use a click binding, knockout passes the current binding's data and event.
So in your HTML:
<a href="#" data-bind="click : $root.giveCashtoChild">
It calls giveCashToChild with two arguments. Your giveCashToChild method should thus accept two arguments, of which the first will be the child to give cash to.
self.giveCashtoChild = function(data, event) {
var currentChildId = data.orig_id;
// the other stuff..
};
I'm making ajax table with Node.js. I can update the rows without refreshing whole page, and delete task also. it's not perfect because of below reason, please see the image.
When I update some row, and I click 'remove' button, it is not working. But after I refresh the whole page, it works well. Maybe this is very verbose question, If you have not enough time - please see js file, there is key of problem... Okay, then the codes are :
html : If I load page, the page will find database and show each one. No problem with this I think.
<table id="tb-docs">
<thead>
<tr>
<th width="50">Active</th>
<th width="300">Subject</th>
<th>Content</th>
<th width="110">Action</th>
</tr>
</thead>
<tbody>
<% posts.forEach( function ( post, index ){ %>
<tr>
<td><input type="checkbox"/></td>
<td><%= post.Subject %></td>
<td><%= post.Content %></td>
<td><button onclick="deleteRow(this,'<%= post._id %>')">Remove</button>
</td>
</tr>
<% }); %>
</tbody>
</table>
js : I strongly suspect 'append()' in updateRow function. maybe there is something wrong,
function updateRow(subject, content){
$.ajax({
url: "/",
type: "POST",
data: { 'subject': subject, 'content': content },
success: function(data){
$('#tb-docs').append('<tr>' +
'<td><input type="checkbox" checked/></td>' +
'<td>'+subject+'</td>' +
'<td>'+content+'</td>' +
// *** Here Appended button is not worked !!!! ***
'<td><button onclick="deleteRow('+this+','+data+')">Remove</button></td>' +
'</tr>');
}
});
}
function deleteRow(obj, id) {
$.ajax({
url: "/dbs/destroy/"+id,
type: "POST",
data: { 'id': id },
success: function(data){
$(obj).closest('tr').fadeOut(300,function(){
$(obj).closest('tr').remove();
});
},
});
}
server (node.js)
// update row handler ===============
app.post('/', function (req, res){
new posts({
Subject: req.body.subject,
Content: req.body.content,
Active: true
}).save(function (err, post) {
if (err) return next(err);
res.send(post._id);
});
});
// delete row handler ===============
app.post('/dbs/destroy/:id',function (req, res){
posts.findById(req.params.id, function (err, post){
if (err) res.send(err) ;
post.remove(function(err, todo, next){
if(err) return next(err);
res.sendStatus(200);
});
});
});
I struggled with it for 2 days. This appending row in table is just trick, right? So I think appended 'button' is not worked, but reloaded page 'button' is worked. Then, How can I do action with appended button?
I think a other way, separate this table html file and ajax get call. but I have a lot of tables, so this is very hard works and not efficient way. Could you tell me what is real problem? Sorry for no fiddle because it is related with database. Anyway Thanks for reading.!
Instead of using '+this+' just type this in the onclick function for the deleteRow button.
function updateRow(subject, content){
$.ajax({
url: "/",
type: "POST",
data: { 'subject': subject, 'content': content },
success: function(data){
$('#tb-docs').append('<tr>' +
'<td><input type="checkbox" checked/></td>' +
'<td>'+subject+'</td>' +
'<td>'+content+'</td>' +
// *** Here Appended button is not worked !!!! ***
'<td><button onclick="deleteRow(this,'+data+')">Remove</button></td>' +
'</tr>');
}
});
}
function deleteRow(obj, id) {
$.ajax({
url: "/dbs/destroy/"+id,
type: "POST",
data: { 'id': id },
success: function(data){
$(obj).closest('tr').fadeOut(300,function(){
$(obj).closest('tr').remove();
});
},
});
}
I'm trying to post 2 param from a view with JavaScript to Controler but i`m getting this error. Dont know why..
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
transfer.js
$(document).ready(function () {
$("#transferPlayerButton").click(function () {
var playerId = document.getElementById("id_player").value;
var teamId = document.getElementById("id_team").value;
$.ajax({
type: 'post',
url: '/Player/TransferPlayer',
data:
{
playerId: playerId,
newTeamId: teamId
},
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (data) {
alert("Success!");
}
});
});
});
controller
[HttpPost]
public ActionResult TransferPlayer(int playerId, int newTeamId)
{
return Content(string.Format("Player {0} it is now at team {1}.", playerId, newTeamId));
}
and this is my view. I'have been mapped object to database obj but i cand figure out why im getting this 500 error. Need some help. I`m a newbie in mvc/javascript
#model FotballTeamsProject.Models.PlayerModels.PlayerTransferModel
<script src="#Url.Content("~/Scripts/Player/Transfer.js")"></script>
<script type="text/javascript">
var transferUrl= "#Url.Action("TransferPlayer", "Player")";
</script>
<table>
<thead>
<tr>
<th>ID</th>
<th>Nume</th>
<th>Prenume</th>
<th></th>
<th>Skill</th>
<th>Valoare</th>
<th></th>
<th>Echipa Actuala</th>
<th style="margin-right: 10px;">Echipa Viitoare</th>
</tr>
</thead>
<tbody>
<tr>
<td id="id_player">#Model.Player.id_player</td>
<td>#Model.Player.player_firstname</td>
<td>#Model.Player.player_surname</td>
<td></td>
<td>#Model.Player.player_skill</td>
<td>#Model.Player.player_value</td>
<td></td>
<td>#Model.Player.name_team</td>
<td style="text-align: right;">
<select id="id_team">
<option selected="selected" value="0">Fara echipa</option>
#foreach (var teamInfo in Model.Teams)
{
<option value="#teamInfo.Key">#teamInfo.Value</option>
}
</select>
</td>
</tr>
</table>
</tbody>
<p>
<input id="transferPlayerButton" type="button" value="Transfera" />
</p>
In the AJAX call, pass the data like so:
data: JSON.stringify({ playerId: playerId, newTeamId: teamId }),
When posting the data as you are, it looks like this:
playerId=1&newTeamId=2
But in your AJAX setup the contentType is set to 'application/json;charset=utf-8' which means the data should be passed in JSON format. Because the data is not being passed in JSON format, the MVC model binder is unable to do it's job and get the data from the request body (since it thought there was JSON data coming along the wite, due to the contentType).
When you use JSON.stringify the data will be passed like this in the request body:
{
newTeamId: "2"
playerId: "1"
}
I'm trying to submit a new post using $http. it's not working. I tried the shore version and the long version, both fail. console:" Failed to load resource: the server responded with a status of 500 (Internal Server Error) "
This my code:
$scope.doAdd = function(){
$http({
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: 'api/addduans',
method: "POST",
})
.success(function(data) {
alert('OK');
});
}
My controller:
function addduans_post()
{
$id_duan = $this->post('id_duan');
$title = $this->post('title');
$addr = $this->post('addr');
$dis = $this->post('dis');
$img_duan = $this->post('img_duan');
$result = $this->admin_model->add_id_da($id_duan,$title,$addr,$dis,$img_duan);
if($result === FALSE)
{
$this->response(array('status' => 'failed'));
}
else
{
$this->response(array('status' => 'success'));
}
}
My Model:
public function add_id_da($id_duan,$title,$addr,$dis,$img_duan)
{
$data = array(
'id_duan' => $id_duan,
'title' => $title,
'addr' => $addr,
'dis' => $dis,
'img_duan' => $img_duan
);
$this->db->insert('duan_test', $data);
}
This my view :
<tr>
<td> <input name='id_duan' style='width: 50px' ng-model='id_duan'/> </td>
<td> <input name='title' ng-model='title'/> </td>
<td> <input name= 'addr' ng-model='addr'/> </td>
<td> <input name='dis' style='width: 60px' ng-model='dis'/> </td>
<td> <input name='img_duan' ng-model='file_name'/> </td>
<td> Add </td>
</tr>
Anyone got any idea on how to make this work? Thanks!
Step 1: Make your input fields into a form.
<form ng-submit='doAdd()'>
<tr>
<td> <input name='id_duan' style='width: 50px' ng-model='myForm.id_duan'/> </td>
<td> <input name='title' ng-model='myForm.title'/> </td>
<td> <input name= 'addr' ng-model='myForm.addr'/> </td>
<td> <input name='dis' style='width: 60px' ng-model='myForm.dis'/> </td>
<td> <input name='img_duan' ng-model='myForm.file_name'/> </td>
<td> <input type="submit" class="btn - btn-info" value="add"> </td>
</tr>
</form>
Step 2: Submit the form
$scope.formData = {};
$scope.doAdd = function(){
$http({
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: 'api/addduans',
method: "POST",
data : $.param($scope.formData)
})
.success(function(data) {
alert('OK');
});
}
Hope it helps. You seem to be switching from jQuery. Refer here for a simple tutorial.
I faced such condition. I have used custom serialize service as following . it may be use for your problem.
appCommonServiceModule.factory('SerialiazeService', function () {
function SeriliazeService() {
this.serialiaze = function (obj, prefix) {
var str = [];
for (var p in obj) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ? this.seriliaze(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
}
return new SeriliazeService();
});
it is used in $http.post like that (memberModel is javascript object data type):
$http.post(BASE_URL + 'index.php/signUp', SerialiazeService.serialiaze(memberModel), {responseType: 'json', headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
change this code
$http({
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: 'api/addduans',
method: "POST",
data : $.param($scope.formData)
})
to this:
var request = $http.post('api/addduans', $.param($scope.formData), {headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}});