JSON get data using post-method - javascript

I want to get a JSON file from another server xyz.com (not writhing here original site name for safety) for my HTML page but the problem is that the website xyz.com only supports HTTP POST requests.
To check if my HTML code is working fine I use HTTP GET method and upload JSON data on another site that supports HTTP GET request. And I found that it is working fine. But when I try for HTTP POST method it is not working. Can you help me?
I am using currently and working fine
<script>
$(function() {
var people = [];
$.get('https://api.myjson.com/bins/c307c',function(data) {
$.each(data.video, function(i, f) {
HTML CODE FOR xyz.com and it also return a .json file
<html>
<head>
<form action="https://www.xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="Passkey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="Passkey" required>
<button type="submit" >GET Json File From Server</button>
</div>
</form>
This is i tried but not working
<script>
$(function() {
var people = [];
$.post('https://xyz.php', usedId=5&passkey=55, function(data) {
$.each(data.video, function(i, f) {

Try this way code
$.post( "https://xyz.php", { usedId: 5, passkey: 55},
function(data) {
//your code
} );

Please make necessery change so that when i click on button it take data from server and show in a table format
<html>
<head>
<form action="https://xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="passKey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="passKey" required>
<button type="submit" >GET DATA</button>
</div>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.post( "xyz.php",function(data) {
$.each(data.video, function(i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
var tblRows = "<tr>" +
"<td>" + f.videoName + "</td>" + "<td>" + f.date + "</td>" + "<td>" + f.time + "</td>" +
"<td>" + f.videoDuration + "</td>" + "<td>" + f.liveStatus + "</td>" + "<td><a target='_blank' href='"+link+"'>"+link+"</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" width="50%" border="2">
<thead>
<th>VIDEO NAME</th>
<th>DATE</th>
<th>TIME</th>
<th>DURACTION</th>
<th>LIVE STATUS</th>
<th>LINK</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</html>

Some changes I suggest:
Give the form an ID, in this case login seems like an appropriate ID
Standardize your capitalization for form fields
Here's some code to get you started. You'll notice I'm creating your data twice. Decide if you want to build your data by hand or use jQuery's serialization to do it for you. Since this is a simple form, the latter is probably fine.
I'm also getting the AJAX endpoint right from the form so you aren't repeating yourself there.
// when the document has loaded...
$(document).ready(function () {
// if the user is already logging in
var login = false;
// when the form is submitted...
$('#login').on('submit', function (event) {
// block the form if it's already been submitted
if (login) {
event.stopPropagation();
event.preventDefault();
return;
}
// lock the form
login = true;
// get a handle on the form
// I use $ as a prefix to differentiate jQuery objects
// currentTarget is the subject of the event
var $form = $(event.currentTarget);
var url = $form.prop('action');
/*
* MANUAL
*/
// form fields are added to the form object as properties by name attribute
// note that they are not jQuery objects
var data = {
userId: $form.userId.value,
passKey: $form.passKey.value
};
/*
* AUTOMATIC
*/
// uses jQuery's form serialization to automatically create an object mapping names to values
var data = $form.serialize();
$.post(url, data)
// on success
.done(function (data, status, request) {
$.each(data.video, function (i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
// backslash at the end of a string means to continue the string on the next line
var $row = $('<tr>\
<td>' + f.videoName + '</td>\
<td>' + f.date + '</td>\
<td>' + f.time + '</td>\
<td>' + f.liveStatus + '</td>\
<td><a target="_blank" href="' + link + '">' + link + '</a></td>\
</tr>');
$row.appendTo('#userdata tbody');
})
// on failure
.fail(function (request, status, error) {
window.alert('Failed with a status of ' + status + ': ' + error);
})
// executes after either of the above
// parameters are inconsistent and use either done's or fail's
.always(function () {
// do cleanup, i.e. unlock form submission, close modal dialogs, etc.
login = false
});
// stop default form submission
event.stopPropagation();
event.preventDefault();
});
});

Related

Dynamic Javascript output in templated HTML

I am trying to build a Javascript class which takes some options and returns builds a form. I would like the submit function to be determined by the options passed to the class. All of the HTML is output as expected, but I don't think the javascript that is being output is being parsed. When the HTML renders I get a syntax error -
"Unexpected token function"
and when I try to submit the form I get a
Reference error - "{functionName} is not defined."
Here is the class so far:
var ClassOptionsForm = function(options) {
this.options = options
this.getSubmissionFunction = function() {
switch (this.options.type) {
case 'standard':
return this.standardSubmit;
break;
case 'extendable':
return this.extendableSubmit;
break;
}
}
this.successHandler = "function (data, form) {\
$(form).find('.result').text('Success!').css('color', 'green');\
}"
this.failureHandler = "function (data, form) { \
$(form).find('.result').text('Something went wrong.').css('color', 'red');\
}"
this.submitFunctionName = this.options.optionName + "Submit";
this.standardSubmit = "function " + this.options.optionName + "Submit(form) {\
google.script.run\
.withSuccessHandler(" + this.successHandler + ")\
.withFailureHandler(" + this.failureHandler + ")\
.withUserObject(form)\
.setUserOption('" + this.options.optionName + "', form)\
}"
this.extendableSubmit = "function(this) {\
// Extendable Form Submit
}"
this.buildForm = function() {
var value = this.options.value;
return '\
<script type="text/javascript">\
' + this.getSubmissionFunction() + '\
</script>\
<h3>' + this.options.formTitle + '</h3>\
<form id="' + this.options.optionName + '" onsubmit="' + this.submitFunctionName + '(this)">\
' + Object.keys(value).reduce(function(list, key) {
return list + '<input name="' + key + '" value="' + value[key] + '"/>';
}, '') + '\
<button type="submit">Save</button>\
</form>\
'
}
}
And here is how form render function is called in the HTML file:
<?!= GoogleAnalytics().optionsForm.buildForm(); ?>
And here is the final HTML output:
<script type="text/javascript">
function UAIDSubmit(form) {
google.script.run
.withSuccessHandler(function (data, form) {
$(form).find('.result').text('Success!').css('color', 'green');
})
.withFailureHandler(function (data, form) {
$(form).find('.result').text('Something went wrong.').css('color', 'red');
})
.withUserObject(form)
.setUserOption('UAID', form)
}
</script>
<h3>UAID</h3>
<form id="UAID" onsubmit="UAIDSubmit(this)">
<input name="id" value="********">
<button type="submit">Save</button>
</form>
I am pretty sure that this has something to do with the way that App Script sanitizes HTML, and I know there are a million ways I could accomplish submitting the form without dynamic JS. I am just trying to keep my code as dry as possible, and also I'm curious. Any workarounds that keep that don't involve doing away with templated JS?
When you try to submit the form it won't work because you can use a form object as parameter in a Google Script function but the form object must be the only parameter in that function. Read here[1]
[1] https://developers.google.com/apps-script/guides/html/reference/run

Asp.net MVC, how to avoid slashes(/) in parameter in javascript

Picture above shows snippets of Furnitures table. The user will key-in their desired reference number in ReferenceNum field. The problem is, the data itself have slash(/). Everytime the user try to submit the value, my url became MyWebsite.com/Furniture/PriceList/Ref/3/Case2, thus the website couldnt find the website.
View
<div class="form-group row">
<label class="control-label col-md-2">Reference Number</label>
<div class="col-md-8">
<input type="text" class="form-control" id="RefNum" />
</div>
<div class="col-md-2">
<input class="btn btn-success" id="getReference" value="Find"/>
</div>
</div>
<p id="rData">
</p>
JS
<script type="text/jscript">
$('#getReference').click(function () {
$.getJSON('/Furniture/PriceList/' + $('#RefNum').val(), function (data) {
var items = '<table><tr><th>Name</th><th>Reference Number</th></tr>';
$.each(data, function (i, lists) {
items += "<tr><td>" + lists.ItemName + "</td><td>" + lists.ReferenceNum + "</td></tr>";
});
items += "</table>";
$('#rData').html(items);
});
})
Controller
public JsonResult PriceList(string id)
{
var result = db.Furnitures.Where(x => x.ReferenceNum == id);
return Json(result, JsonRequestBehavior.AllowGet);
}
You can add the result as a query string value, rather than a route value
$('#getReference').click(function () {
$.getJSON('/Furniture/PriceList?id=' + $('#RefNum').val(), function (data) {
or
$('#getReference').click(function () {
$.getJSON('#Url.Action("PriceList", "Furniture")', { id: $('#RefNum').val() }, function (data) {
You can use %2F to escape slash(/) character in URL.
So updated JS code will be:
<script type="text/jscript">
$('#getReference').click(function () {
$.getJSON('/Furniture/PriceList/' + $('#RefNum').val().replace(/\//g,'%2F'), function (data) { //<--- Fix
var items = '<table><tr><th>Name</th><th>Reference Number</th></tr>';
$.each(data, function (i, lists) {
items += "<tr><td>" + lists.ItemName + "</td><td>" + lists.ReferenceNum + "</td></tr>";
});
items += "</table>";
$('#rData').html(items);
});
})

jQuery Mobile dynamic content -cannot select tag

I'm working with jQuery Mobile in a google web app and just having some issues selecting a tag. More specifically, I have content that is loaded from an external source so need to have a loading page initially. Once the external source is available I then update the page with the content using jQuery. Included in this content is an input tag. The issue is when I update the page, I cannot then cannot find the value of this input tag.
Here is my code below:
(intial html - Before content is loaded)
<div class="ui-body ui-body-a">
<div id="googleList" >
<fieldset data-role="controlgroup" data-mini="true" >
<input type="checkbox" name="checkbox-v-6a" id="checkbox-1-a">
<label for="checkbox-v-6a">Loading . . . </label>
</fieldset>
</div>
</div>
Here is my jQuery to update the code above when the new content comes in:
function showTaskList(tasks)
{
//Generate HTML
var htmlToInsert = "<fieldset data-role=\"controlgroup\" data-mini=\"true\" >";
for(var i = 0; i < tasks.length; i++)
{
htmlToInsert += "<input type=\"checkbox\" data-id=\"" + tasks[i][1] + "\" name=\"checkbox-" + i + "-a\" id=\"checkbox-" + i + "-a\" class=\"custom taskCheckBox\" ";
if(tasks[i][2] != undefined)
htmlToInsert += "checked=\"checked\"";
htmlToInsert += " />";
htmlToInsert += "<input id=\"currency-controlgroup1\" data-id=\"" + tasks[i][1] + "\" type=\"text\" value=\"" + tasks[i][0] + "\" data-wrapper-class=\"controlgroup-textinput ui-btn\" class=\"taskinputBox\">";
}
//Insert HTML into site
$("#googleList").html(htmlToInsert + "</fieldset>");
//Refresh List
$("#googleList").trigger("create");
}
Here is my code to get the input tag value
$(document).ready(function(){
function processTaskList()
{
console.log("Test");
$(document).on('click', '.taskCheckBox', function (event, ui) {
var checkBoxId = $(this).data("data-id");
console.log("CheckBox:" + checkBoxId );
});
}
});
CheckBoxId keeps coming back undefined when I click on one of the checkboxes. I want to be able to read the data-id value. I'm not sure how to fix this? Any help is appreciated.
I tested the code below again, and it works - Thanks for your help
$(document).on('click', '.taskCheckBox', function (event, ui) {
var checkBoxId = $(this).data("id");
console.log("CheckBox:" + checkBoxId );
});

Handling post on dynamic row on a html table with jquery

I have a dynamic table that I will be submitted to database.
The html is looked like this :
<form id="upload">
<div class="box-body">
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="tableReport">
<thead>
<th>TYPE</th>
<th>ITEM</th>
<th>DAMAGE</th>
<th>REPAIR</th>
<th>REMARKS</th>
<th>MANHOUR</th>
<th><button class="btn btn-block btn-primary" id="addRow" type="button">ADD</button></th>
</thead>
<tbody>
<!--GENERATED BY JQUERY-->
</tbody>
</table>
</div>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-info" type="submit">Upload</button>
</div>
</form>
See, on my <th>, I have a button with id addRow that have a function to add a row on a last row.
This is the code :
$(document).on('click', '#addRow', function () {
var selType = '<select class="form-control" name="type">';
var selItem = '<select class="form-control" name="item">';
var selDamage = '<select class="form-control" name="damage">';
var selRepair = '<select class="form-control" name="repair">';
$.each(<?php echo json_encode($type); ?>, function (i, elem) {
selType += '<option>' + elem.NAMA_TYPE + '</option>';
});
$.each(<?php echo json_encode($item); ?>, function (i, elem) {
selItem += '<option>' + elem.NAMA_ITEM + '</option>';
});
$.each(<?php echo json_encode($damage_codes); ?>, function (i, elem) {
selDamage += '<option>' + elem.NAMA_DAMAGE + '</option>';
});
$.each(<?php echo json_encode($repair_codes); ?>, function (i, elem) {
selRepair += '<option>' + elem.NAMA_REPAIR + '</option>';
});
selType += '</select>';
selItem += '</select>';
selDamage += '</select>';
selRepair += '</select>';
$("#tableReport").find('tbody').append('<tr><td>' + selType +
'</td><td>' + selItem +
'</td><td>' + selDamage +
'</td><td>' + selRepair +
'</td><td><input type="text" class="form-control name="remarks" placeholder="Describe it..">' +
'</td><td><input type="text" class="form-control time" name="manhour">' +
'</td><td><button class="btn btn-block btn-danger">Delete</button>' +
'</td></tr>');
$(".time").inputmask("hh:mm");
});
Now, this is the problem. How to handling the form. When <button class="btn btn-info" type="submit">Upload</button> is clicked to submit, I will handled it use jquery ajax. The code looked like this
$(document).on('submit', '#upload', function(){
/*First, How to handled the dynamic row ?? */
/* Commonly, I use var aVar = $('selector').val(); */
/* Ex, I have two rows, How bout to handle two select option in different row ?*/
$.ajax({
url: 'LINK TO CHECK THE POST if has SUBMITTED',
type: 'POST',
data : {/*dynamic row that will be passed : data*/}
dataType: 'json',
success: function(obj) {
})
return false;
});
How can I handle that dynamic row, and how can I debug if the post have success ?
UPDATED
This code to check the condition of a ship container. If a container have many damage, it will be representated with one row as one damage. If the container have 3 damage, it will be have 3 rows. I want to submit it on a table in my database in tbl_damage_detail. I have plan to multiple insert. So, I Imagine to store that rows into an array. with foreach, I will be inserted them.
JSFIDDLE
If the inputs are added correctly to the form you just need to submit the form with AJAX, no need for anything special, one way is to use the jQuery serialize() method like this.
$(document).on('submit', '#upload', function(event){
$.ajax({
url: 'LINK TO CHECK THE POST if has SUBMITTED',
type: 'POST',
data : $(this).serialize(),
dataType: 'json',
success: function(obj) {
})
event.preventDefault();
});
with your code,i really don't know what you want to do .
first, "on" is used to bind event with dynamic dom ,but id=addRow is not a dynamic dom,it is unnecessary to use on
"$(document).on('click', '#addRow', function () {"
just use $("#addRow").click( function () {...})
and then, <form id="upload">, i am not sure you have decide to post date to service with submit, in fact ,here is a dynamic table ,if you use submit to post your data ,it may complex with your whole table data .(using submit , input must set the name tag)
i suggest you should handle each row data
//get every row data
var tableData = [] ;
$("#tableReport tbody tr").each( function(){
var tr = &(this);
var text2 = tr.find(".time").val(); //should use more clean tag
var data = {test2:test2}//...
tableData.push(data)
//use ajax with the data
});
//next handle the tableData with ajax
this scene is very fat to mvvm like: angular , vue.js or avalon.js ,use one of them,with more clean but less code .

JQuery POSTing with buttons values, returning input?

Hey guys and gals I'm having some major issues trying to get my application to work. I've been trying to hack through this and am missing the very first part which is sending the correct input value (button value) to get the ball rolling, I'm sure this is something simple but I've been having an issue getting it working. I'd appreciate it if someone could pick out the error(s) to help me along.
This is extremely easy to do in PHP, but since this is a standalone offline
app I cannot use PHP =( I need to do all my fetching and parsing in JQuery
or Javascript....
We start with a very basic form with some buttons that have unique values.
<form>
<fieldset>
<legend>Select Orders</legend>
<table id='master'></table>
</div> <!-- end input1 -->
<div>
<button name="select" type="submit" id="btnLoad" value="load">Refresh</button>
<button name="select" type="submit" id="btnJson" value="down">Download JSON</button>
<button name="select" type="submit" id="btnView" value="view">View/Enter</button>
</div>
</fieldset>
</form>
which triggers this function
$(function() {
$("form").submit(function() {
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
// $this.button.val() never makes it through?
queryJsonServer($(this), "class/");
return false;
});
});
I've tried things like
var button = $(this).attr("value");
var button = $('button').attr("value"); // ends up with the first buttons value,
// but never the selected or $(this).val()
$('button').click(function() { // which WILL console.log the buttons val,
console.log($(this).val()); // but will not let me turn it into a var?
return false; // ALSO this looks like it only reads the
}); // value the SECOND click?
The Mission here is to send the buttons value as a $_POST type over to a parser which will return the appropriate JSON array to be parsed, or to be stored in a Local SQLite DB.
Either way, here's the full code of the page, could someone please give me a hand, or if I need to clarify please let me know.
<?php
ini_set('display_errors', 1);
error_reporting(E_ERROR | E_PARSE);
var_export($_POST);
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title> </title>
<script src='http://www.google.com/jsapi'></script>
<script> google.load('jquery', '1.7.1'); </script>
<script>
$(function(){
$("form").submit(function()
{
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
$('button').click(function() {
var state = $(this).val();
return true;
});
// state is undefined. L29
console.log(state);
// $this.button.val() never makes it through?
queryJsonServer($(this), state, "class/");
return false;
});
// query json server for
function queryJsonServer(form, state, path)
{
// on first return or refresh inputs will be returrned
var view = $('input[name="orders"]:checked').val();
var url = path + "json.php?" + state; // status = button.val()
var state = $(this).attr("value"); // ends up class/json.php?undefined
// we have data, lets post to json parser and
$.getJSON(url, view, function(data)
{
$('form').unbind('submit').trigger('submit');
var items = [];
switch(state)
{
case 'load' :
$.each(data, function(index, obj) {
items.push('<tr>');
$.each(obj, function(key, val) {
items.push((key == "report_number")
? '<td class="check" ><input type="checkbox" name="' + val + '" /></td><td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>'
: '<td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>')
});
items.push('</tr>');
});
$('<div/>', {
'class': 'jsonOutput',
html: items.join('')
}).appendTo('#master');
break;
case 'down' :
// populate SQLite Database
break;
case 'view' :
$.each(data, function(index, obj) {
items.push('<tr>');
$.each(obj, function(key, val) {
items.push('<td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>')
});
items.push('</tr>');
});
$('<div/>', {
'class': 'jsonOutput',
html: items.join('')
}).appendTo('#master');
break;
default:
return false;
break;
}
});
}
});
</script>
<style type="text/css">
p, ul {width:100%; text-align:left;font-size:80%;}
.reports_box {width:auto; padding:25px 20px 20px 20px;border:1px solid #91bce6;background-color:#eff5fb;}
.inputs {width:300px; font-size:15px;padding:5px;}
.check input {padding:0 !important;}
.caps {text-transform:capitalize;}
#reports_list td, #reports_list tr {padding:10px 0 10px 2px;color:#34567b;}
</style>
</head>
<body>
<div class="reports_box">
<form id='submit'>
<fieldset>
<legend>Select Orders</legend>
<table id='master'></table>
</div> <!-- end input1 -->
<div>
<button name="select" type="submit" id="btnLoad" value="load">Refresh</button>
<button name="select" type="submit" id="btnJson" value="down">Download JSON</button>
<button name="select" type="submit" id="btnView" value="view">View/Enter</button>
</div>
</fieldset>
</form>
</div> <!-- end reports_box -->
</body>
</html>
Block form submission unless triggered by a button.
When form submission is triggered by a button:
Use $(form).serialize() to serialize the form
add "&select=ButtonValue" to the serialized string
Use $.getJSON to send a get request to your server page and get a JSON object back.
FINAL EDIT: Here's a working fiddle where I use serialize correctly: http://jsfiddle.net/YYZGG/5/
(When using the code change the form action to your correct page)
$(function(){
$("form").submit(function()
{
var state;
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
$('button').click(function() {
state = $(this).val();
return true;
});
// state is NOW DEFINED
console.log(state);
// $this.button.val() never makes it through?
queryJsonServer($(this), state, "class/");
return false;
.......................
Also, if having trouble getting the right values, try:
$('button').on('click', function(e) {
console.log(e.target.value);
});
EDIT:
Are you sure it should'nt just be:
$("form").submit(function(e) {
var state = e.target.value;
console.log(state);
---------
Why does your submit not include a post inside it? The method your using is GET that's why it's not a POST, either use .submit() and .post() together or just use an entire different approach working all together using GET and .click() functions, but here's an example of what using .post() looks like:
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post and put the results in a div */
$.post( url, { s: term },
function( data ) {
var content = $( data ).find( '#content' );
$( "#result" ).empty().append( content );
}
);
});
</script>
http://api.jquery.com/jQuery.post/

Categories

Resources