Jquery .post() not calling script - javascript

I am trying to pass the data from a form to an insertion script without having the form data cleared. I am using this function to act on the press of the submit button but I get nothing. It is even set to throw an error if the form is missing data but it doesn't even get that far. I can only assume I am not calling it properly.
$(function() {
$(".submit").click(function() {
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity=' + facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
if (facility == '' || riskclient == '' || riskdate == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "insertriskass.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
<div class="body">
<div align='center'>
<div class="tablebackground">
<form method ="post" name= "form" id="form">
<table border='1' >
<tr>
<td>Facility</>
<td><input type="text" name= "riskFacility" id="facility"></td>
<td rowspan='4'><input type="submit" name="submit" value="New Client" class="submit"/</td>
</tr>
<tr>
<td>Client</td>
<td><input required type="text" name="riskClientId" id="riskclient" value="<?php echo htmlspecialchars($_POST['riskClientId']); ?>"></td>
</tr>
<tr>
<td>Audit Date</td><td> <input required type="text" id="datepicker" name="riskauddate" id="riskdate"></td>
</tr>
</table>
</form>
It is definitely not passing anything to the insertion script. So again, I think I am calling it incorrectly.

I see your html tags are not closed properly
<div class="body">
<form method="post" name="form" id="form">
<table border='1'>
<tr>
<td>Facility</td>
<td>
<input type="text" name="riskFacility" id="facility">
</td>
<td rowspan='4'>
<input type="submit" name="submit" value="New Client" class="submit" /> </td>
</tr>
<tr>
<td>Client</td>
<td>
<input required type="text" name="riskClientId" id="riskclient" value="">
</td>
</tr>
<tr>
<td>Audit Date</td>
<td>
<input required type="text" id="datepicker" name="riskauddate" id="riskdate">
</td>
</tr>
</table>
</form>
and check if it comes to error call back

I think it's useful..
$(document).ready(function () {
$('#submit').on('click', function (event) {
event.preventDefault();
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity='+ facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
or
// var datastring = $("#form").serialize();
if(facility=='' || riskclient=='' || riskdate=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "insertriskass.php",
data: dataString,
success: function (msg) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
})
event.preventDefault used to stop submit and page reload.
datastring = $("#form").serialize(); used to submit all data values so no need to take each and every variable assign value.

You can refactor a little the code like this, revise your html tags. You have a double id property in an input, and missing clousure tags.
$(document).ready(function() {
$(".submit").click(function(event) {
event.PreventDefault();
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity=' + facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
if (!facility || !riskclient || !riskdate) {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
//send ajax post
}
});
});

Related

Jquery closest function with class not alerting in javascript code become undefined value

I have a code that waste my few hours. Here jquery closest with class not working in html table and not passing value. I use html, javascript, jquery and php here. Can anyone rewrite the code freshly.
<script>
$(document).ready(function () {
$(".senddata").on("click", function () {
var subans =
$(this).closest(".datadivision").find("input[name='subans']").val();
var data = 'subans=' + subans;
$.ajax({
type: "POST",
url: "test.php",
data: data,
cache: false,
success: function (html) {
alert(html);
}
});
});
});
</script>
<table>
<tr class="datadivision">
<input type="hidden" name="subans" value="A" >
<td class= "senddata">
<label><input type="radio" name="subans" value="something"> This is a
line</label>
</td>
</tr>
</table>
<?php
if (isset($_POST['subans'])) {
$subans = $_POST['subans'];
if (!empty($subans)) {
echo $subans;
}
}
?>
Assuming that you want the alert to show the value "A", JavaScript is not the issue. The problem is that you are printing the whole page, even when the request is POST.
Instead, you should conditionally print the page only when the request is not POST, or when it does not contain subans property. Like this:
<?php
if (isset($_POST['subans'])) {
$subans = $_POST['subans'];
if (!empty($subans)) {
echo $subans;
}
} else {
?>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function () {
$(".senddata").on("click", function () {
console.log(this)
var subans =
$(this).closest(".datadivision").find("input[name='subans']").val();
var data = 'subans=' + subans;
$.ajax({
type: "POST",
url: "stack.php",
data: data,
cache: false,
success: function (html) {
alert(html);
}
});
});
});
</script>
<table>
<tr class="datadivision">
<input type="hidden" name="subans" value="A" >
<td class= "senddata">
<label><input type="radio" name="subans" value="something"> This is a
line</label>
</td>
</tr>
</table>
<?php
}
?>

How can i get into the value inside of an html <tr> object

So i have this code. I want to send the data inside of my html inputs to the controllers parameters. In my jquery i have a line that looks like this
var currentRow = $(this).closest("tr");
But i have no clue how to get into the values of each input inside the currentRow Object how can i do that or do you maybe know a better way to do this?
// my html
#foreach (var discount in Model.DiscountList)
{
<tr>
<td>#Html.TextBox("codeTextBox", discount.Code) </td>
<td><input type="checkbox" name="freeShippingCheckBox" id="freeShippingCheckBox" checked="#discount.FreeShipping" /> </td>
#if (discount.isTwoForThree == true)
{
<td><input type="tel" value="Ta 3 betala för 2" readonly /></td>
}
else
{
<td><input type="number" value="#discount.PercentOffPrice"/></td>
}
<td><input type="checkbox" id="activeCheckBox" name="activeCheckBox" checked="#discount.Active" /></td>
<td><input type="datetime" value="#discount.CreatedDate" readonly /></td>
<td>
<input type="button" value="Radera" class="fa fa-remove" data-url="#Url.Action("DeleteDiscountCode","Discount",new { id= discount.Id})" />
<input type="button" value="Uppdatera" class="fa fa-update" data-url="#Url.Action("UpdateDiscount","Discount",new { id= discount.Id, })" />
<input type="button" value="Produkter" class="fa fa-products" />
</td>
<input id="#discount.Id.ToString()" type="hidden" value="#discount.Id" />
</tr>
}
//my jquery
$(".fa-update").on("click", function () {
var currentRow = $(this).closest("tr");
console.log(currentRow.children("#freeShippingCheckBox").val());
if (confirm("Are you sure you want to edit this discount code?"))
{
$.post($(this).data("url"), function (data) {
$.ajax({
url: '#Url.Action("DeleteUser","Discount")',
type: "POST",
data: "freeShipping=..........???????????",
success: function (data) {
if (data) {
}
location.reload();
}
});
location.reload();
alert("Deleted");
})
}
});
//my controller
[HttpPost]
public void UpdateDiscount(int id, bool freeShipping, int percentOfPrice, bool active)
{
Service.DiscountService.UpdateDiscount(id, freeShipping, percentOfPrice, active);
}
My proposal is:
$(function () {
$(".fa-update").on("click", function (e) {
var data = {};
var currentRowParams = $(this).closest("tr").find('input').each(function(index, element) {
var name = element.name ? element.name : 'undefined' + index;
data[name] = element.value || '';
});
var x = JSON.stringify(data);
console.log(x);
//
// If instead you want the params in a traditional GET
//
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<table>
<tbody>
<tr>
<td>#Html.TextBox("codeTextBox", discount.Code) </td>
<td><input type="checkbox" name="freeShippingCheckBox" id="freeShippingCheckBox" checked="#discount.FreeShipping" /> </td>
<td><input type="tel" value="Ta 3 betala for 2" readonly /></td>
<td><input type="checkbox" id="activeCheckBox" name="activeCheckBox" checked="#discount.Active" /></td>
<td><input type="datetime" value="#discount.CreatedDate" readonly /></td>
<td>
<input type="button" value="Radera" class="fa fa-remove" data-url="#Url.Action("DeleteDiscountCode","Discount",new { id= discount.Id})" />
<input type="button" value="Uppdatera" class="fa fa-update" data-url="#Url.Action("UpdateDiscount","Discount",new { id= discount.Id, })" />
<input type="button" value="Produkter" class="fa fa-products" />
</td>
<input id="#discount.Id.ToString()" type="hidden" value="#discount.Id" />
</tr>
</tbody>
</table>
You can access a value via .html(). As Vijai said, you can use serialize to make it a POST array like (&=, etc) format assuming you have a structured form. Or, to stay similar to your original code, you can just pass as usual JSON. like
data:{shippingInfo: "value", moreInfo: "blahblah"}
It is recommended to use a <form id="formID" ...> tag around yours inputs and use $("#formID").serialize() in the Ajax method if you are not doing processing of the input value in the View. Refer this sample link : Submit form using AJAX and jQuery
$.post($(this).data("url"), function (data) {
$.ajax({
url: '#Url.Action("DeleteUser","Discount")',
type: "POST",
data: $("#formID").serialize(),
success: function (data) {
if (data) {
}
location.reload();
}
});

Need to inject client-side js validation before jquery ajax validation

I'm having trouble getting my validate(form) function to run "before" my ajax function. Any recommendations on how to tie the two together and have them run in order when the form is submitted would be most helpful.. thanks!
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript" src="includes/JSValidation.js"></script>
<script type="text/javascript">
// These first three lines of code compensate for Javascript being turned on and off.
// It simply changes the submit input field from a type of "submit" to a type of "button".
var paraTag = $('input#submit').parent('p');
$(paraTag).children('input').remove();
$(paraTag).append('<input type="button" name="submit" id="submit" value="Contact Us!" />');
$(function() {
$('#contactForm input#submit').click(function() {
$('#contactForm').append('<img src="ajax-loader.gif" class="loaderIcon" alt="Loading..." />');
var firstname = $('input#firstname').val();
var lastname = $('input#lastname').val();
var email = $('input#email').val();
var message = $('textarea#message').val();
$.ajax({
type: 'post',
url: 'email.php',
data: 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&message=' + message,
success: function(results) {
$('#contactform img.loaderIcon').fadeOut(1000);
$('td#response').html(results);
}
}); //end ajax
});
});
//Validation
function validate(form){
var firstName = form.firstname.value;
var lastName = form.lastname.value;
var email = form.email.value;
var subject = form.subject.value;
var message = form.message.value;
var errors = [];
if (!reProperName.test(firstName)) {
errors[errors.length] = "You must enter a valid first name.";
}
if (!reProperName.test(lastName)) {
errors[errors.length] = "You must enter a valid last name.";
}
if (!reEmail.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (checkTextArea(message,1000)) {
errors[errors.length] = "Your message is too long. It must be less than 100 characters.";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
submitForm(contactForm);
return true;
}
function reportErrors(errors){
var msg = "There were some problems...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
</head>
<body>
<div id="wrap">
<?php
require 'includes/header.php';
?>
<div id="main">
<h1 align="center">Contact Form:</h1>
<div>
<form method="post" id="contactForm" autocomplete="on" onclick="return validate(this);" action="includes/email.php">
<table width="350" border="0" align="center" cellpadding="4" cellspacing="0">
<tr>
<td><label>Your First Name:</label></td>
<td><input type="text" name="firstname" id="firstname" style="width:100%" /> </td>
</tr>
<tr>
<td><label>Your Last Name:</label></td>
<td><input type="text" name="lastname" id="lastname" style="width:100%" /></td>
</tr>
<tr>
<td><label>Your Email:</label></td>
<td><input type="text" name="email" id="email" style="width:100%" /></td>
</tr>
<tr>
<td colspan="2">
<label>Your Message:</label><br /><br />
<textarea name="message" style="width:100%;height:160px" id="message"></textarea>
</td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" name="submit" value="Contact Us!" id="submit"></td>
</tr>
<tr align="center">
<td colspan="2" id="response" />
</tr>
</table>
</form>
</div>
<div class="push" />
</div>
<?php
require 'includes/footer.php';
?>
</body>
Change the validate function as following,
function validate() {
var firstName = $("#firstname").val();
var lastName = $("#lastname").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
***************
}
and change the jQuery event,
$(function () {
$('#contactForm #submit').click(function (e) {
e.preventDefault();
if (validate()) {
// Ajax code
}else{
// not valid
}
});
});

JQuery - Edit table, get data through serialize instead?

Here is my java code. I'd like to find a cleaner way to do this. How can I access the same data via serialize? I plan to have multiple forms on a single page that need processing. I'm looking to DRY up the code and not have to specifically name each field.
Thanks!
HTML:
ItemAmountDescription
<tr class="edit_tr" id="3">
<td class="edit_td">
<span class="text" id="name_3">Salary</span>
<input type="text" value="Salary" class="editbox" id="name_input_3"/>
</td> <td class="edit_td">
<span class="text" id="amount_3">100.00</span>
<input type="text" value="100.00" class="editbox" id="amount_input_3"/>
</td> <td class="edit_td">
<span class="text" id="description_3">Salary</span>
<input type="text" value="Salary" class="editbox" id="description_input_3"/>
</td> </tr>
</tbody>
</table>
Java code:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#name_"+ID).hide();
$("#amount_"+ID).hide();
$("#description_"+ID).hide();
$("#description_input_"+ID).show();
$("#name_input_"+ID).show();
$("#amount_input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var name=$("#name_input_"+ID).val();
var amount=$("#amount_input_"+ID).val();
var description=$("#description_input_"+ID).val();
var dataString = 'id='+ ID +'&name='+name+'&amount='+amount+'&description='+description;
$("#name_"+ID).html('<img src="load.gif" />'); // Loading image
if(name.length>0 && amount.length>0)
{
$.ajax({
type: "POST",
url: "{{url('budget/edit-income')}}",
data: dataString,
cache: false,
success: function(html)
{
$("#name_"+ID).html(name);
$("#amount_"+ID).html(amount);
$("#description_"+ID).html(description);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
You mentioned serialize... use $('form').serialize(); to create a string ready for the ajax data

How can I enter data from clintside using webservice in asp.net?

I am trying this :
this my javascript code :
function insertVisitor() {
var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>'
$.ajax({
type: "POST",
url: pageUrl + "/insert_Visitor",
data: "{'name':'" + $("#txtName").val() + "','phoneno':'" +
$("#txtPhone").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall,
error: OnErrorCall
});
return false();
}
function OnSuccessCall(response) {
window.open("about.html");
}
function OnErrorCall(response) {
alert(response.status + " " + response.statusText);
}
</script>
this the html :
<form action="" method="post">
<table>
<tr>
<th>
<label>
please enter your Name :
</label>
</th>
<td>
<input id="txtName" type="text" value="" placeholder="Name" />
</td>
</tr>
<tr>
<th>
please enter your Phone No :
</th>
<td>
<input id="txtPhone" type="text" value="" placeholder="Phone No" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<!--<input id="btnEnter" type="button" style="background-image:~/images/pop_up/enter.png; height:40px; width:120px" />-->
<!--<input type="submit" name="button" id="button" value="enter" onClick="window.location='about.html'" />-->
<!--<a href="about.html" style="display: block">-->
<img src="images/pop_up/enter.png" width="120" height="40" alt="img" style="width: 120px;
height: 40px; position: relative; right: 0;" onclick="return insertVisitor()" />
<!--</a>-->
</td>
</tr>
</table>
</form>
and this is the webservice code :
[WebMethod]
public string insert_Visitor(string name, string phoneno)
{
string returnvalue = "";
if (name != "" && phoneno != "")
{
cmd.Parameters.Clear();
cmd.Connection = connection;
cmd.CommandText = "Insert_Into_VisitorLog";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", name);
cmd.Parameters.AddWithValue("#Phone", phoneno);
Object obj = cmd.ExecuteScalar();
if (obj != "0" || obj != "Unexpected error occurred!!")
{
returnvalue = Convert.ToString(obj);
}
else
{
returnvalue = Convert.ToString(obj);
}
}
return returnvalue;
}
the problem that i am facing is getting an error like this
400 Bad Request
how to solve this please help
The data part in jQuery is wrong
data: "{'name':'" + $("#txtName").val() + "','phoneno':'" +
$("#txtPhone").val() + "'}",
it should be
data: {'name': $("#txtName").val() ,'phoneno': $("#txtPhone").val() },
Edit 1
Also as you are returning string from you service so dataType is also wrong in you jquery call.
Differences between contentType and dataType in jQuery ajax function
Edit 2
var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>'+"/insert_Visitor?name="+ $("#txtName").val()+"&phoneno="+ $("#txtPhone").val() ;
$.ajax({
type: "POST",
url: pageUrl,
success: OnSuccessCall,
error: OnErrorCall
});
Edit 3
Get more about error detail use the following
function OnErrorCall(xhr, ajaxOptions, thrownError)
{
alert(xhr.responseText);
}

Categories