Unable to Post Data in my JSON File - javascript

Unable to Perform Post method on my JSON File
My JSON File is
[{
"name": "Help",
"description": "Deletion not allowed for products!?",
"price": 100000.0 }]
<html>
<head>
<title>Product Management</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/default.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"</script>
<script src="js/bootstrap.min.js"></script>
Function for Getting the Values
<script>
$(document).ready(function() {
$(window).load(function() {
$.ajax({
type: 'GET',
url: 'test.json',
dataType: 'json',
success: function(data) {
$.each(data, function(index, element) {
$("#abc").append($('<li>', {
text: element.name
}))
});
}
});
});
});
</script>
Function for Posting the Values in the JSON file
<script>
function sumbitForm(){
var x=document.getElementById("#name");
var y=document.getElementById("#description");
var z=document.getElementById("#price");
var Product={"name":x, "description":y, "price":z };
$.ajax({
url: "test.json",
type: "POST",
contentType: "application/json",
data: JSON.stringify(Product)
});
}
</script>
</head>
<body>
<div>
<ol id="abc">
</ol>
</div>
<div class="container">
Input Form for posting the Data
<form name="PForm" action="" method="POST">
<div class="form-group">
<label>Name:</label>
<input type="text" class="form-control" id="name" placeholder="Product Name">
</div>
<div class="form-group">
<label>Description:</label>
<textarea class="form-control" id="description" placeholder="Descrpition" rows="8"></textarea>
</div>
<div class="form-group">
<label>Price:</label>
<input type="text" class="form-control" id="price" placeholder="Price">
</div>
<button type="submit" class="btn btn-primary Right" onClick="submitForm()">Submit</button>
</form>
</div>
</body>
</html>

You need to get the value of the elements, like
var x=document.getElementById("#name").value;
Else you would send the DOM elements (which, converted to a string, would only be 'object')

Related

Form data doesnt't get sent by id via AJAX

I want the following ajax request to process form data from form with "#next" id:
$(function () {
$("#next").on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'check_user.php',
dataType: 'json',
data: $('form').serialize(),
success: function (response) {
if(response['found'] === 'true') {
location.href = 'index.php';
} else {
alert('Incorrect username or password');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
And here's the file that contains the form:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/auth_style.css">
<title>Authentication</title>
<script src="https://code.jquery.com/jquery-3.6.1.js"></script>
<script src="js/authentication_ajax.js"></script>
<noscript>JS is disabled. Enable js to continue</noscript>
</head>
<body>
<h1 id="header">Enter your data here</h1>
<form id="#next">
<label for="login">Login</label>
<input type="text" id="login" name="login" placeholder="Enter your login here" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password here" required><br>
<input type="submit" value="Log in">
</form>
<form id="#log_out" action="log_out.php" method="post">
<button type="submit">Log out</button>
</form>
</body>
What's interesting is that when I used just $('form').on('submit', function (e) { it worked just fine.
You have two error the first one is how to use ids, in the id don't use # instead use just the name, and into the selector you can use $('#name').
The second problem is about selector of serialize(), in this case you can use directly e.target like:
$(function() {
$("#next").on('submit', function(e) {
e.preventDefault();
console.log($(e.target).serialize());
/*
$.ajax({
type: 'post',
url: 'check_user.php',
dataType: 'json',
data: $(e.target).serialize(),
success: function (response) {
if(response['found'] === 'true') {
location.href = 'index.php';
} else {
alert('Incorrect username or password');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="header">Enter your data here</h1>
<form id="next">
<label for="login">Login</label>
<input type="text" id="login" name="login" placeholder="Enter your login here" required><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter your password here" required><br>
<input type="submit" value="Log in">
</form>
<form id="log_out" action="log_out.php" method="post">
<button type="submit">Log out</button>
</form>

Your session has expired. on ajax form post laravel

I have the following html snippit from my view and js code to handel the form request.
$('#quick-enquiry').on('submit', function(e) {
e.preventDefault();
$(".submit").prop("disabled", true);
data = $(this).serialize();
action = $(this).attr('action');
$.ajax({
type: 'POST',
url: action,
data: data,
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
success: function(data) {
if ($.isEmptyObject(data.error)) {
$("#quick-enquiry").trigger("reset");
$('.print-error-msg').find('ul').empty();
$('.print-error-msg').css('display', 'block');
$("#response-msg").toggleClass('uk-alert-danger uk-alert-success');
$('.print-error-msg').find('ul').append("<li>" + data.success + "</li>");
setTimeout(function() {
$('.print-error-msg').fadeOut();
$(".submit").prop("disabled", false);
UIkit.modal("#modal-quick-enquiry").hide();
}, 3000);
} else {
printMessageErrors(data.error);
}
}
});
});
function printMessageErrors(msg) {
$('.print-error-msg').find('ul').empty();
$('.print-error-msg').css('display', 'block');
$.each(msg, function(key, value) {
$('.print-error-msg').find('ul').append("<li>" + value + "</li>");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.26/js/uikit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.26/css/uikit.min.css" rel="stylesheet" />
<form action="{{ route('frontend-postEnquiry') }}" method="POST" id="quick-enquiry">
<input type="hidden" id="tour-id" value="1">
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Full Name</label>
<div class="uk-form-controls">
<input class="uk-input uk-form-width-large" type="text" placeholder="Full Name" id="fullName" name="fullName">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Email</label>
<div class="uk-form-controls">
<input class="uk-input uk-form-width-large" type="email" placeholder="Email" id="email" name="email">
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label" for="form-stacked-text">Message</label>
<div class="uk-form-controls">
<textarea class="uk-textarea uk-form-width-large" rows="4" placeholder="Some Message...." id="enquiryMessage" name="enquiryMessage"></textarea>
</div>
</div>
<p class="uk-text-right">
<button class="uk-modal-close-default" type="button" uk-close></button>
<button class="uk-button uk-button-primary submit uk-width-1-1" type="submit">Send</button>
</p>
</form>
With the above code I'm getting
419
Sorry, your session has expired. Please refresh and try again.
I've set CSRF-TOKEN in ajax and in head section also, but seems like my js code is not picking up csrf token.
I would be very thankful if anyone could highlight the mistake I've made above.
Try using this:
{{ csrf_field() }} instead of #csrf
419 error is mostly because of CSRF token issues.

Javascript code never loaded

I have a javascript code that I have hardcoded into my html file, but it never seems to load. My form sends data to a php file via post immediately without every going through javascript verification. Any ideas? Thanks!
<!DOCTYPE html>
<html>
<head>
<!-- Stylesheets - boostrap and get-shit-done, a free UI -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="styelsheet" type="text/css" href="css/get-shit-done.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
<h1>Registration</h1>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$('#registration').on('submit', function(e){
var usernameValue = $("#username").val();
var passwordValue = $("#password").val();
var confirmationValue = $("#confirmation").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ usernameValue + '&password1='+ passwordValue + '&confirmation1='+ confirmationValue;
if(usernameValue==''||passwordValue==''||confirmationValue=='') {
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
</script>
</head>
<body>
<form id ="registration" action="register.php" method="post">
<fieldset>
<legend>Registration Details</legend>
<form class="form-inline">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" id="username" placeholder="Username" type="text"/>
</div>
<div class="form-group">
<input class="form-control" id="password" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<input class="form-control" id="confirmation" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<button class="btn btn-default btn-round" type="submit" id="submit">
<span aria-hidden="true" class="glyphicon glyphicon-log-in"></span>
Log In
</button>
</div>
</form>
</fieldset>
</form>
<div>
<p class="text-center">or login</p>
</div>
</body>
</html>
You need to wrap your $('#registration').on('submit', function(e){ }); with in a $(function(){ }); (or $(document).ready()) as it is currently binding before the document is ready -
<script>
$(function(){
$('#registration').on('submit', function(e){
...
[rest of your code]
...
});
});
</script>
Please try adding your script inside jquery document ready . Example
$( document ).ready(function() {
$('#registration').on('submit', function(e){
var usernameValue = $("#username").val();
var passwordValue = $("#password").val();
var confirmationValue = $("#confirmation").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ usernameValue + '&password1='+ passwordValue + '&confirmation1='+ confirmationValue;
if(usernameValue==''||passwordValue==''||confirmationValue=='') {
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});

how to call json object on popup?

I am trying to call the json object on pop-up but unable to make it happen....!
please suggest me if i am wrong somewhere.
My html file is here:
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/ui-darkness/jquery-ui.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script type="text/javascript">
function advanceSearch() {
$("#test").dialog({
width: '90%',
modal: true
});
}
function getInformation() {
alert("hello");
$.ajax({
url: "/response.json",
dataType: "json",
type: "GET",
success: function(response) {
alert("hello2");
$.each(response.BankAccounts, function(item) {
informationArray.push(item);
alert(data[0].bank)
});
informationArray.push("success");
}
});
}
</script>
</head>
<body>
<form id="BankAccounts" name="BankAccounts">
Sort Code :
<input type="text" name="sortCode1" />
<br>
<input type="text" name="sortCode2" />
<br>
<input type="text" name="sortCode3" />
<br>
<input type="button" id="search" value="Search" onclick="getInformation()"> Bank Name :
<input type="text" name="bank" />
<br> Branch Name :
<input type="text" name="branch" />
<br>
</form>
<div id="test" style="display: none;">
This is a sample content
</div>
</body>
</html>
and my json is here:
{
"BankAccounts": [{
"bank": "HSBC"
"branch": "nlbc road"
}, {
"bank": "BOA"
"branch": "New York"
}
]
}
on click i want to call the bank-name on popup

Get value of input without submitted form

I need to make my jsp page work without reloading page using jquery.
$(".btn.btn-default.btn-lg").click(function( event ) {
event.preventDefault();
$.post(main.jsp,{operand1: request.getParameter("operand1")});
alert(<%= request.getParameter("operand1") %>);
});
I'm trying to post parameter to the page and alert it. Nothing happens.
However function works fine.
what's my mistake?
Here is full jsp code.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.min.css" rel="stylesheet">
<title>Insert title here</title>
</head>
<body>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<form class="form-horizontal" role="form" method="get">
<div class="form-group">
<div class="col-lg-10">
<input name="operand1" id="operand1" class="values"></input>
<input name="operand2" id="operand2" class="values"></input>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<select name="operation" id="operation" class="values">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="multiply">*</option>
<option value="divide">/</option>
<option value="mod">mod</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<input type="submit" class="btn btn-default btn-lg" value="Submit"></input>
</div>
</div>
</form>
<script>
$(".btn.btn-default.btn-lg").click(function( event ) {
event.preventDefault();
$.ajax({
method:"POST",
url: "main.jsp",
data: {operand1: document.getElementById("operand1").value, operand2: document.getElementById("operand2").value, operation: document.getElementById("operation")}
}).done(function (result) {
alert(result);
});
alert($('input.values').val());
});
</script>
<%
Double operand1=0.0;
Double operand2=0.0;
String operation=new String();
if ((request.getParameter("operand1")!=null)&&(request.getParameter("operand2")!=null)&&(request.getParameter("operation")!=null)){
operand1 = Double.parseDouble(request.getParameter("operand1"));
operand2 = Double.parseDouble(request.getParameter("operand2"));
operation=request.getParameter("operation");
}
Double result=0.0;
if (operation.equals("plus")){
result=operand1+operand2;
}
if (operation.equals("minus")){
result=operand1-operand2;
}
if (operation.equals("divide")){
result=operand1/operand2;
}
if (operation.equals("multiply")){
result=operand1*operand2;
}
if (operation.equals("mod")){
result=operand1%operand2;
}
if ((request.getParameter("operand1")!=null)&&(request.getParameter("operand2")!=null)&&(request.getParameter("operation")!=null)){
String resultString="Result:";
out.println(resultString+result);
}
%>
</body>
</html>
Any suggestions?
You should use ajax something like this:
$(".btn.btn-default.btn-lg").click(function( event ) {
$.ajax({
method:"POST",
url: "main.jsp",
data: {operand1: document.getElementById("operand1").value}
}).done(function (result) {
alert(result)
});
});
request is a JSP implicit object which will not work in javascript. Instead you can use following to get the value.
$('#operand1').val(); //operand1 is an id of the element
Use the success callback :
$(".btn.btn-default.btn-lg").click(function( event )
{
$.ajax(
{
method:"POST",
url: "main.jsp",
data: {operand1: document.getElementById("operand1").value},
success: function(result)
{
alert(result);
}
})
});

Categories