How come my AJAX post request is not working? - javascript

I am trying to click on the "Change" button and send the form data to another JSP page in order to perform an UPDATE statement in the database. For some reason I cannot get the "update" id button to execute the click() function with the AJAX call in it as the "ham" alert does not pop up. Sorry I have multiple commented out approaches to this in the script tags since I tried out multiple things. Would someone be able to help me out with this? The current jsp page looks as follows:
<!DOCTYPE html>
<head>
<script src="/.jquery-1.9.1.js" type="text/javascript" charset="utf-8"></script>
<script src="http://code.jquery.com/jquery=latest.min.js" type="text/javascript">
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1] == undefined ? true : sParameterName[1];
}
}
};
$(document).ready(function() {
var key = getUrlParameter("key");
});
$(form).submit(function() {
if (-1 == this.action.indexOf('register')) {
var jForm = $(this);
$.post(this.action, $(this).serialize(), function(data) {
if (data.status == 'SUCCESS') {
jForm[0].action = data.redirectUrl;
jForm.submit();
}
return false;
}
}
});
window.onload = function() {
document.getElementById("submit").onclick = function() {
location.href = "/View.jsp";
}
}
window.onload = function() {
document.getElementById("update").onclick = function() {
location.href = "/View.jsp";
}
}
$(document).ready(function() {
$('#update').on('click', function(e) {
alert('ham');
$.ajax({
type: "post",
url: "change.jsp",
data: $("#form").serialize(),
success: function(msg) {
alert(msg.data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
$(document).ready(function() {
function click() {
alert('ham');
$.ajax({
type: "post",
url: "change.jsp",
data: $("#form").serialize(),
success: function(msg) {
alert(msg.data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
window.location.href = "change.jsp";
return false;
}
});
/*function validateForm(){
var x=document.forms["insert"]["ID"].value;
alert(x.len());
if(x==null||x==""){
alert("ID must be filled out");
return false;
}
}*/
</script>
</head>
<body>
...
<form id="myForm" action="register" method="post" name="insert">
ID:
<input type="text" name="ID" required value="<%=id%>" />
<br/> RHINO:
<input type="text" name="rhino" required value="<%=rhino%>" />
<br/> OX:
<input type="text" name="ox" required value="<%=ox%>" />
<br/> HORSE:
<input type="text" name="horse" required value="<%=horse%>" />
<br/>
<input type="submit" value="Submit" id="submit" />
<!--<input type="submit" value="Update" id="change"/>-->
<button id="update" onclick="return click()">Change</button>
</form>
...
</body>
</html>

You're defining the function in a closed scope:
$(document).ready(function() {
function click() {
//...
}
});
So it only exists within that anonymous function being used as the ready handler. Once that function terminates, anything defined in that scope is no longer used if nothing references it.
Then you try to invoke the function from global scope:
<button id="update" onclick="return click()">Change</button>
So the function can't be found.
Instead of trying to invoke it from inline code in the HTML, use the jQuery library that you're already using and attach the handler to the click event:
$(document).ready(function() {
$('#update').click(function () {
// the code in your click() function goes here
}
});
And remove that inline handler:
<button id="update">Change</button>
(Note: There may very well be other problems in this code. It's actually quite difficult to follow without any indentation at all. But at the very least this problem seems the most immediate upon clicking that button. It needs to be able to find the function in order to execute it.)
Update: Another user has formatted the code in your question, and there do appear to be other problems. Specifically, you are making multiple simultaneous attempts to attach very different behaviors to the click of that button. One of those events appears to even be a redirect, which would simply cancel any other operations because the page is reloading. Simplify your code. Perform exactly and only the operation you want on that button click.

Related

How can I extract values in html loop(mustache) when using jquery

all I want to do is make a call by using "idx".
something like this.. alerts/1 alerts/2 alerts/3.....
{{#alerts}}
<tr name = "alerts">
<input name = "idx" style="display : None" value="{{id}}">
<td><input type="submit" value="start alert" name="alert-start"/></td>
<td>ticker : {{ticker}}</td>
<td>price : {{price}}</td>
</tr>
{{/alerts}}
So I made a Jquery
$('input[name=alert-start]').on('click', function() {
_this.alertStart();
});
},
alertStart : function() {
var idx = $('input[name=idx]').val();
$.ajax({
type: 'GET',
url: '/alerts/'+idx,
}).done(function() {
alert('start alert');
}).fail(function (error) {
alert(JSON.stringify(error));
});
},
But... with this code, I can only call "alerts/1". No matter how many alerts are there...
What can I do?? Please someone help.. I'm really struggling with this..
Look into followings
<input name = "idx" type="hidden" value="{{id}}"> is the correct way of hiding any imput from appearing on page
$('input[name="idx"]').val(); is correct way to read the idx value
rest seems to be fine look for any error in console
What you could do is pass the input you click on to the alertStart function. Then use the object to find the input[name=idx] related to the clicked input.
$('input[name=alert-start]').on('click', function() {
_this.alertStart(this);
});
alertStart: function(obj) {
var idx = $(obj).closest("tr").find('input[name=idx]').val();
$.ajax({
type: 'GET',
url: '/alerts/' + idx,
}).done(function() {
alert('start alert');
}).fail(function(error) {
alert(JSON.stringify(error));
});
}

Ajax not Writing to Database

I have an HTML form that I'm trying to read data from and write into a database. A sample of the HTML for the form is shown below:
<div id="form">
<div class="container-tabby1">
<div class="wrap-tabby1">
<form class="tabby1-form validate-form">
<span class="tabby1-form-title">
New Form
</span>
<div class="wrap-inputtabby validate-input bg1" data-validate="Internal Error">
<span class="label-inputtabby">Change Request Number</span>
<input id="ChangeRequestNo" class="inputtabby" type="text" name="ChangeRequestNo" onload="onLoad" readonly>
</div>
<div class="container-contact100-form-btn">
<input id="submitRequest" type="button" class="contacttabby-form-btn" value="Submit Request" onclick="SaveChangeRequest()"/>
</div>
The ajax used to write this to the database is as follows:
function SaveChangeRequest() {
var o = form.getData();
var errorMsg = "";
msg = mini.loading("Submit...");
var jsonform = mini.encode(o);
debugger;
$.ajax({
url: urlCR,
type: "post",
data: { CR: jsonCR },
cache: false,
success: function (text) {
debugger;
if (text != null && text != '') {
mini.hideMessageBox(msg);
onOk();
}
else {
jAlert("Submit failed", "Error Message");
}
},
error: function (jqXHR, textStatus, errorThrown) {
mini.hideMessageBox(msg);
alert(jqXHR.responseText);
}
})
Every time I attempt to submit to the database I get the "Submit failed" error message. I have another form as shown below that works perfectly fine:
<div id="form" style="margin-left:5px;margin-right:5px;">
<table width="100%;" align="center">
<tr>
<td width="100px;"><label>Applicant:</label></td>
<td width="300px;"><input id="ApplicantEmail" name="ApplicantEmail" class="mini-textbox" allowinput="false" style="width: 290px;" /></td>
<td align="center">
<input type="button" class="searchsubmit" value="Submit" onclick="SaveForm()" style="width:120px;" />
<script type="text/javascript">
mini.parse();
SecurityLog_PageLoad();
var urlPersonInfo = "data/AjaxSecurityService.aspx?method=Sec_CurUserLoginInfo";
var urlFormGetItem = "Data/ajaxservice.aspx?method=CSC_Form_GetWholeFormo&FormID=";
var urlFormUpdateWithNotice = "Data/ajaxService.aspx?method=CSC_Form_UpdateChanges";
var form = new mini.Form("#form");
var searchGrid = mini.get("dgSearchResult");
var applyGrid = mini.get("dgApplyResult")
function SaveForm() {
var o = form.getData();
form.validate();
if (form.isValid() == false) return;
var errMsg = '';
if (o.RequestComments == null || o.RequestComments == '')
errMsg=".Justification is empty.\n";
if (applyGrid.data.length < 1)
errMsg+= ".At least apply one report before you submit.\n";
if (errMsg != '')
{
jAlert(errMsg, "Validate Error");
return;
}
$.ajax({
url: urlFormUpdateWithNotice,
type: "post",
data: { dataForm: jsonClaim, dataList: jsonList },
cache: false,
success: function (text) {
var impactID = mini.decode(text);
if (impactID != null && impactID != "") {
SecurityLog_Submit('Submit',impactID);
CloseWindow("ok");
};
},
error: function (jqXHR, textStatus, errorThrown) {
mini.hideMessageBox(msg);
alert(jqXHR.responseText);
}
});
</script>
Why does the latter form work while the first form does not?
This is not a answer as such at this stage, but a few points of note that might help reach an answer:
the code that displays the "Submit failed" message is actually in the success response section. It shows the message if there is a non-null, non-empty string returned by the AJAX call. It would help if the string was output to help debug if it's an actual failure to save the data, or not
following on from the above, check if the data submitted has been saved or not - that will help establish what is actually happening
In the second form, we can see the URL (urlFormUpdateWithNotice) but in the first we can't, so it's hard to tell if that is a problem (e.g. there could be a typo in the URL)
Ideally you need to include as much detail as possible, including any critical data, so that diagnosing the problem is easier and quicker.
In any case the best place to start is to see what text is in success: function (text) {... and take it from there.

onsubmit return false is not working

The following script shows the error message correctly, but the form always submits whether confirm_shop_code() returns true or false. I tried in many ways to solve the bug but it still persists. I have to stop the form from submitting when it returns false, but allow it to submit when it returns true. Please can any one help me to solve this?
<h2 id="shop_data"></h2>
<!-- form -->
<form action="" class="form-horizontal form-label-left input_mask" method="post" onsubmit="return confirm_shop_code();">
<div class="col-md-4 col-sm-4 col-xs-8 form-group">
<input type="text" class="form-control" id="shop" name="code" value="<?php echo $account->code; ?>" placeholder="Enter Shop Code">
</div>
</form>
<!-- validation script -->
<script>
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
return true;
} else {
return false;
}
}
});
} else {
$( '#shop_data' ).html("");
return false;
}
}
</script>
<!-- php code -->
<?php
include "system_load.php";
$code = $_POST['shop_code'];
global $db;
$query = "SELECT code from accounts WHERE code='".$code."'";
$result = $db->query($query) or die($db->error);
$count = $result->num_rows;
if($count > 0) {
echo "SHOP CODE already Exists";
} else {
echo "OK";
}
exit;
?>
The reason it is submitting is because AJAX calls are asynchronous by default. I wouldn't suggest making it synchronous because this will block the rest of the javascript execution. Also, you are returning false from the success method of $.ajax. This is not in the same scope as the parent function and therefore does not also cause the parent function to return false. So in fact, your confirm_shop_code() function is not returning anything unless code is false and that's why your form is always being submitted, no matter what happens with the AJAX call.
I would recommend using jQuery to bind to the form's submit event and just disable form submitting with preventDefault(). First, just add an id attribute to the form (e.g. "yourform") and do something like:
$("form#yourform").submit(function(e) {
e.preventDefault();
var form = $(this);
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
form.unbind('submit').submit()
}
}
});
} else {
$( '#shop_data' ).html("");
}
});
You need to add async:false to your ajax code
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
var stopSubmit = false;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
async:false,
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
stopSubmit = false;
} else {
stopSubmit = true;
}
}
});
} else {
$( '#shop_data' ).html("");
stopSubmit = true;
}
if(stopSubmit){
return;
}
}
You should call return false; function on the click event of the submit button.
<button type="submit" id="submit" onclick="return false;" class="btn btn-primary col-4">Proceed</button>
or you can use:
document.getElementById("submit").addEventListener("click", function (e) {
//your logic here
//this return false will not work here
return false;
//this will work
e.preventDefault();
});

prompt confirmation box, cancel should stop execution

I have a prompt box, which when i click on delete user, should ask to confirm if he wants to delete the user,
HTML
<form name="myform" id="myform" action="/AWSCustomerJavaWebFinal/DeleteUser" method="POST" onSubmit="myFunction()">
Choose User:
<br>
<select name="selectUser" multiple style="width: 200px !important; min-width: 200px; max-width: 200px;">
<c:forEach var="user" items="${listUsers.rows}">
<option value="${user.id}">
<c:out value="${user.userId}" />
</c:forEach>
</select>
<input type="submit" value="Delete User" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn btn-primary" id=button1>
</form>
javascript
function myFunction() {
var confirm = prompt("Do you want to continue", "yes");
if (confirm == yes) {
var form = $('#myform');
form.submit(function() {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function(data) {
var result2 = data;
alert("deleted")
}
});
return false;
});
$(document).ready(function() {
$(document).ajaxStart(function() {
$("#wait").css("display", "block");
});
$(document).ajaxComplete(function() {
$("#wait").css("display", "none");
});
});
return false;
} else {
alert("User not deleted")
return false;
}
return false;
}
It asks to confirm, and if I press ok after writing yes in the textbox, it goes to the servlet, and does not give the alert("deleted"), and I have returned false, it still refreshes after pressing submit, also, if i press cancel, it still executes and deletes the user. I tried a lot of different approaches but nothing seems to work here. Thanks in advance.
Try using confirm rather than prompt
var r = confirm("Continue delete?");
if (r == true) {
//your logic to delete
} else {
//alert('user dint delete')
}
A nice one-liner :
if( !confirm("Do you want to continue?") ) return alert("User was not deleted.")
return will stop the execution of the function.
You have a form.submit(function() { $.ajax... that will always trigger your ajax call whenever the form is submitted, regardless of any validation mechanism you set up.
Here is a clean, rewritten version of your code :
in HTML : <form onSubmit="confirmSubmission()"> (a bit more explicit than myFunction() ;)
$(document).ready(function() {
var $wait = $("#wait");
$(document).ajaxStart(function() {
$wait.hide();
}).ajaxComplete(function() {
$wait.show();
});
});
function confirmSubmission() {
if ( !confirm("Do you want to continue")) return alert("Submission has been canceled.")
submit();
}
function submit(){
var $form = $('#myform');
$.ajax({
type : $form.attr('method'),
url : $form.attr('action'),
data : $form.serialize(),
success: function(data) {
var result2 = data;
alert("deleted")
}
});
}

LogIn Page Using JQuery

Before 3 days the code was working fine. But now its not.
please point out my mistake as i am new to JQuery.
I debugged it, and found out that debugger is not entering inside success method of ajax. and not even going to CS file.
Code of Jquery-
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
alert('b');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "admin.aspx/LogIn",
dataType: "json",
data: "{'name':'" + $('#txtfn').val() + "','password':'" +$('#txtln').val() + "'}",
success: function (data) {
alert(data);
var obj = data.d;
alert(obj);
alert(data.d);
if (obj == 'true') {
$('#txtfn').val('');
$('#txtln').val('');
alert("dasdsad");
window.location = "home.aspx";
alert("success");
}
else if (obj == 'false')
{ alert("errorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"); }
},
error: function (result) {
alert(data);
alert("aaaaaaafgdgfdfgsfgfhffghgfhgfhfghfghfhfghfhfghgfhgfhgfhgfhfghfghgfhgfhgf");
alert(result);
}
});
});
});
</script>
</head>
<body>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form id="f1" runat="server">
<input type="text" id="txtfn" placeholder="name" />
<input type="text" id="txtln" placeholder="Password" />
<input type="submit" id="btnSubmit" value="Log in" />
</form>
</div>
</body>
Code-
[WebMethod]
public static string LogIn(string name, string password)
{
string retMessage = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["oltest_conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string Query = "select * from profile where name=#pname and password=#pwd";
using (SqlCommand cmd = new SqlCommand(Query, con))
{
cmd.Parameters.AddWithValue("#pname", name);
cmd.Parameters.AddWithValue("#pwd", password);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
//retMessage = "home.aspx";
retMessage = "true";
}
else
{
retMessage = "false";
}
}
return retMessage;
}
}
You just need to remove
alert('b');``
on your jquery code
try adding a
return false
at the end of the ajax call
Hi change your submit button to button.
<input type="button" id="btnSubmit" value="Log in" />
data: {name: $('#txtfn').val() ,password: $('#txtln').val()},
I updated my answer:
your ajax call is not executed because form is submitted, this code will prevent submission
$("#f1").submit(function (e) {e.preventDefault();})
place it before $('#btnSubmit').click(function () {
better way will be place your code inside
$("#f1").submit(function (e) {
e.preventDefault();
// here place content of $('#btnSubmit').click(function () {( )}
})
Please ensure JSON data /parameters accepted by your web method and it returning proper true/false without any exception/error.
You can do it by debugging in firebug and Visual Studio.

Categories

Resources