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);
});
})
Related
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();
});
});
I am trying to get the todo titles from jsonplaceholder.typicode.com JSON. I have three buttons and each botton has and id, that id is related to the json todo. When you click on a botton you see the title of that json todo.
Button 1 = jsonplaceholder.typicode.com/todos/1 Button 2 =
jsonplaceholder.typicode.com/todos/2 etc..
$('button').click(function (event) {
var id = event.target.id;
console.log(id);
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/" + id,
type: "GET"
}).done(function (data) {
$('#result').append('<div class="todo"></div>');
$.each(data, function (key, value) {
if (key == "title") {
$('.todo').append('<p>' + key + ': ' + value + '</p>');
}
});
}).fail(function (event) {
alert(event.status);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1">A</button>
<button id="2">B</button>
<button id="3">C</button>
<div id="result">
</div>
The problem is that titles repeat each time I click on a button. Why this occurs?
Why? Because you append another <div class="todo"></div> each time button is clicked and then append the content to every one that exists
You can isolate the new <div class="todo"> and only append the new content to that
var $todo = '<div class="todo"></div>'
$('#result').append($todo);
$.each(data, function(key, value) {
if (key == "title") {
$todo.append('<p>' + key + ': ' + value + '</p>');
}
});
Or empty the $('#result') before you add the new content if you don't want to see the first set by changing:
$('#result').append('<div class="todo"></div>');
To
$('#result').html('<div class="todo"></div>');
On each ajax done callback you first create a new todo div:
$('#result').append('<div class="todo"></div>');`
and after that, you add the result to all elements with a todo class:
$('.todo').append('<p>' + key + ': ' + value + '</p>');
I'd suggest removing the first line and changing the second to $('#result')
I have a couple of inputs like so:
<input name="education[1][yearbegin]" type="date" class="form-control">
<input name="education[2][yearbegin]" type="date" class="form-control">
The data is sent to my server to be verified, and if it's invalid it sends back data like so:
{
"education.0.institution":["The education.0.institution field is required."],
"education.0.degree":["The education.0.degree field is required."]
}
I don't always get more than 1 back, sometimes it could be many I am trying to loop over to append an error to the input like so:
var errors = $.parseJSON(data.responseText);
alertHtml += '<ul>';
$.each(errors, function (key, value) {
$('.form-control[name=' + key + ']').closest('.form-group').addClass('has-error');
alertHtml += '<li>' + value + '</li>';
});
alertHtml += "</ul>";
This doesn't work though, because it's trying to find the input name of:
education.1.yearbegin
Rather than
education[1]yearbegin
My inputs won't always be arrayed, but the ones that are don't append How can I append the error message to the input by changing the javascript? The json is being sent back by Laravel's array validation
It's unfortunate that the server accepts the names in one form but sends them back in another.
If we assume that dot syntax should always be converted to brackets syntax, it's fairly straightforward to update the keys:
var updated = key.split(".");
if (updated.length == 1) {
updated = updated[0];
} else {
updated = updated[0] + "[" + updated.slice(1).join("][") + "]";
}
For multi-part keys, that inserts [ before the second and ][ in-between the second and third, third and fourth, etc.; and adds ] at the end.
Example:
var errors = [
{"education.1.yearbegin":["The education.1.yearbegin field is required."]},
{"education.2.yearbegin":["The education.2.yearbegin field is required."]}
];
errors.forEach(function(error) {
Object.keys(error).forEach(function(key) {
var updated = key.split(".");
if (updated.length == 1) {
updated = updated[0];
} else {
updated = updated[0] + "[" + updated.slice(1).join("][") + "]";
}
console.log("Original: " + key + ", updated: " + updated);
});
});
If you're also struggling with showing all of the errors in the array next to the form control, you just loop through them. You're receiving an object where the property names in the object are the form control names, and the values are arrays of error messages. So we
Loop through the property names of that object, and for each property name:
Mark the relevant control, and
Loop through that entry's array of errors to append them to alertHtml.
Something long these lines:
var errors = {
"education.1.yearbegin":["The education.1.yearbegin field is required."],
"education.2.yearbegin":["The education.2.yearbegin field is required."]
};
function fixKey(key) {
var updated = key.split(".");
if (updated.length == 1) {
updated = updated[0];
} else {
updated = updated[0] + "[" + updated.slice(1).join("][") + "]";
}
return updated;
}
var alertHtml = '<ul>';
// #1: Loop through the object's property names
Object.keys(errors).forEach(function(key) {
// #2: Mark the control, using the corrected name
$('.form-control[name="' + fixKey(key) + '"]').closest('.form-group').addClass('has-error');
// #3: Loop through the errors
errors[key].forEach(function(msg) {
alertHtml += '<li>' + msg + '</li>';
});
});
alertHtml += "</ul>";
$(document.body).append(alertHtml);
.has-error {
border: 1px solid red;
}
<div class="form-group">
<input name="education[1][yearbegin]" type="date" class="form-control">
</div>
<div class="form-group">
<input name="education[2][yearbegin]" type="date" class="form-control">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The first issue with the name:
I would just change the name to something that's a bit easier to read rather then having it like:
name="education[1][yearbegin]"
Maybe have it like:
name="EducationYearBegin1"
For the second issue:
You could check if the property is an array, so like this:
if (value instanceof Array) {
value.forEach(function (item) {
alertHtml += '<li>' + item + '</li>';
})
} else {
alertHtml += '<li>' + value + '</li>';
}
Maybe something like that?
The foreach would cover you if you ever had multiple errors in your array too.
You can use String#replace to convert education.1.yearbegin to be education[1][yearbegin]
See fixName function in this code.
function fixName(name) {
var newName = name.replace(/\.\d\./, function ($1) {
return "[" + $1.replace(/\./g, "") + "]"
}).replace(/\].+/, function ($1) {
return $1.replace(/\]/, "][") + "]"
});
return newName;
}
var errors = [{"education.1.yearbegin":["The education.1.yearbegin field is required."]},
{"education.2.yearbegin":["The education.2.yearbegin field is required."]}]; //$.parseJSON(data.responseText);
var alertHtml = document.querySelector("#alert");
alertHtml.innerHTML += '<ul>';
$.each(errors, function (key, obj) {
var realKey = fixName(Object.keys(obj)[0]);
$('.form-control[name="'+ realKey +'"]').addClass('has-error');
alertHtml.innerHTML += '<li>' + obj[Object.keys(obj)[0]][0] + '</li>';
});
alertHtml.innerHTML += "</ul>";
.has-error {
color: red;
}
li {
color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="education[1][yearbegin]" type="date" class="form-control">
<input name="education[2][yearbegin]" type="date" class="form-control">
<div id="alert"></div>
I need to build a search form with Select2 but I have problems getting it to work right.
The user enters the search term into the field which populates suggestions via AJAX. A click on the suggestions brings him to the page. Otherwise he needs to click on the submit button / or press enter, to get to the extended search. The last point (click on the submit button) doesn't work.
<form action="/search" method="get" class="form-search" id="global_search_form">
<div class="input">
<input type="text" name="q" class="search-query" id="global_search" placeholder="Enter search term ...">
<button type="submit" class="btn">Search</button>
</div>
</form>
<script type="text/javascript">
jQuery("#global_search").select2({
placeholder: "Enter search term ...",
minimumInputLength: 2,
multiple: 1,
containerCssClass: 'search-query',
ajax: {
url: 'remoteGlobalSearch',
dataType: 'jsonp',
quietMillis: 100,
data: function (term, page) {
return {
q: term,
per_page: 10,
page: page
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {
results: data.items,
more: more
};
}
},
formatResult: itemFormatResult,
formatSelection: itemFormatSelection,
escapeMarkup: function (m) {
return m;
}
});
function itemFormatResult(item) {
var markup = '<table class="item-result"><tr>';
if (item.image !== undefined) {
markup += '<td class="item-image"><img src="' + item.image + '" /></td>';
}
markup += '<td class="item-info"><div class="item-type">' + item.type_string + '</div>';
markup += '<div class="item-title">' + item.title + '</div>';
markup += '<div class="item-description">' + item.description + '</div>';
markup += '</td></tr></table>';
return markup;
}
function itemFormatSelection(item) {
location.href = item.url;
}
</script>
Cheers
I think there is a compatibility issue with button, type=submit and how various browsers interpret it.
Have you tried to use
<input type="submit" value="Search">
instead of the button tag?
Or, if you really need to use the button tag, then I would recommend having something as:
<button type="button" class="btn" onclick="this.form.submit()">Search</button>
Did this solve your problem?
Cheers!
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/