Ajax not Writing to Database - javascript

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.

Related

Pushing array of values from a form into Google Spreadsheet comes through as 'undefined'

I have a form with text fields which the user can "Add New" by clicking a button. These fields share the same name. I'm trying pass the values into Google Spreadsheets, but the values all come through as 'undefined' with the following code, even though console.log prints the answers as strings which look okay to me.
So if the user for example submits 3 separate entries for SUNDAY_NOTES[], all 3 strings should end up in one cell broken up by new lines, but instead I'm just getting "undefined".
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // the user can create multiples of these ^ for each day of the week
<input type="submit" id="submit" />
</form>
<script>
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray().map((e) => {
return e.value
}).join('\n')
});
})
});
</script>
Your code works. In the snippet below I am storing the data split by \n in a variable and logging it. You can check the output.
Although your JS is correct, I suspect that you actually want to be using a different HTTP method. Perhaps POST or PUT? I can't be specific as you have not said which API endpoint you are using.
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var data = $form.serializeArray().map((e) => {
return e.value
}).join('\n');
console.log(data);
var jqxhr = $.ajax({
url: url,
method: "POST",
dataType: "json",
data: data
}).done(response => {
console.log(response);
}).fail((jqXHR, textStatus) => {
console.log("Request failed: " + textStatus);
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="submit" id="submit" />
</form>
remove the [] from your input's name as this is needed if you want to receive an array in the server side, then create a function that groups the values according to the inouts' keys :
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
and use it like :
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray()),
//... rest of your code
this will keep the original structure that works,
here's a snippet :
var $form = $('form#timesheet');
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
$form.submit(function(e) {
e.preventDefault();
var grouped = group($form.serializeArray());
console.log(JSON.stringify(grouped))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES"><br />
<input type="text" name="SUNDAY_NOTES"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES"> // and so forth
<input type="submit" id="submit" />
</form>

Form reloading page without sending the data on submit

here's my code.
In my .js file:
function Sendit()
{
bValidate = validateField();
if(bValidate)
{
var title = $("#title").val();
theUrl = 'index.php';
params = '';
params += 'action=Send';
params += '&title='+title;
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
//do smth
alert('went well');
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
}
function validateField()
{
var title = document.getElementById('title').value;
if(!title.match(/\S/))
{
//do some alerting
return false;
}
else
{
return true;
}
}
And in my index.php file:
<form action="" method="post" name="myform" id="myform"" >
Title: <input class="" type="text" name="title" value="" id="title"/> <br>
<input type="submit" value="Submit" onClick="javascript:Sendit();return false; ">
</form>
<?php
if ($_REQUEST["action"]=='Send')
{
$title = $_REQUEST["title"];
$sql = "INSERT INTO ...
$retval = $mysqli->query($sql, $conn);
if(! $retval ) {
echo('Could not enter data insert: ' . mysql_error());
}
else
{
//inform that everything went well
}
?>
This does not send a thing when the sunmit button is clicked. In fact, you can click the button until the end of the day that nothing happens (not even a message in the debugger)
If I delete the return false; from the onClick in the button, I click on the button and the page reloads even without filling in the title input which has to be filled in.
Ajax's success does not alert a thing and in both cases, nothing gets inserted in my database.
The insert query is correct, I've checked it.
Any ideas on how to send the data and validate?
Thanks
Use below Code to send req.
function Sendit()
{
bValidate = validateField();
if(bValidate)
{
var title = $("#title").val();
theUrl = 'index.php';
params = {};
params["action"] = 'Send';
params["title"] = title;
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
//do smth
alert('went well');
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
}
your validateField() function never returns true, so your if(bValidate) will never run. Javascript functions return undefined unless you explicitly return something, try this:
function validateField()
{
var title = document.getElementById('title').value;
if(!title.match(/\S/))
{
//do some alerting
return false;
} esle {
return true;
}
}

jQuery validation submitHandler not work in $.ajax post form data

I have Send data using $.ajax and validation with jQuery validation plugin like this :
<div class="" id="ajax-form-msg1"></div>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
JS:
jQuery(document).ready(function ($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [4, 20],
},
},
submitHandler: function (form) {
$("#ajax-1").click(function (e) {
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false
}).done(function (data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function (jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
});
}
});
});
In action my form validate using jQuery validation but after validation not submit and not send data.
how do fix this problem?!
DEMO HERE
The submitHandler is expecting a submit and you have a click event inside it and then an ajax call.
If you have a button type="submit" inside a form you don't even need a click event, the plugin will do the validation automatically. So just make the ajax call inside the submitHandler.
If you need to bind the action to a button using the click event, the proper approach should be something like this:
$('#button').click(function(){
var form = $('#myform').validate({...}); #store the validator obj
if (form.is_valid()){
// submit using ajax
} else {
// dont do anything
}
});
Call form.submit() at the end of your done function.
See: http://jqueryvalidation.org/validate/
Also, you do not need $("#ajax-1").click() because the submitHandler will be called automatically when you click on that button anyways. You can test this yourself by putting a console.log as the first line of submitHandler. Then fill out the form and press the button. See if it prints out your log message.
In submitHandler you are handling the submit , then again why did you write click event?
Here is the fix.
jQuery(document).ready(function($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [2, 20],
},
},
submitHandler: function(a, e) {
//a is form object and e is event
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false,
success: function(data) {
console.log(data)
},
error: function(err) {
console.log(err)
}
}).done(function(data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function(jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.min.js"></script>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
Use success and error call backs to get data or error messages.
Note: Here (In StackOverflow) you will get 404 Page Not Found error when you submit. So try in your local.

Can not get ajax callback to a function

I have a form for user to register new account. I use jquery + ajax to check availability of email address on form submission. In Jquery code I used e.preventDefault(); to prevent form submission if there is any error occurs. I tried the existed email address in the email input and click submit the form. It allows form to submit. It should not do this because ajax reponseText return true means that the email address is already existed in database.
Could anyone please tell me how to fix my code so that if ajax response returns true, it will prevent form submission and shows up errors.
I tried to read and follow this article but fails after so many attempts.
Here is my form:
<form role="form" method="post" id="signupForm" action="index.php?view=signup-gv">
<div class="col-xs-6 border-right">
<div class="form-group">
<label for="exampleInputEmail1">Full Name</label>
<input type="text" class="form-control" id="regname" name="regname" placeholder="Full Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label><span id="emailcheck"></span>
<input type="email" class="form-control" id="regemail" name="regemail" placeholder="Enter email">
</div>
</div>
<div class="form-group col-xs-6">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="regpass" name="regpass" placeholder="Password">
</div>
<button style="position:relative; left: 15px; top: 10px;" class="btn btn-default" name="register" id="register">Register</button>
</form>
Here my jquery code:
$(document).ready(function(){
$('#regname').focus();
$('#signupForm').submit(function(e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
if(regname.val() == ''){
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
e.preventDefault();
}
else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
e.preventDefault();
}
else if(regpass.val() == ''){
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
e.preventDefault();
}
emailCheck().done(function(r){
if(r){
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
e.preventDefault();
}
});
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {regemail:regemail.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'emailcheck.php',
success: function(responseText){
if(responseText == 0){
return false; // good to go
}
else{
emailcheck.html('<span class="errorss"> This email is existed.</span>');
return true; // This email is registered. Please try different one
}
}
});
}
First you are not returning anything from the emailCheck() function, but you are using it as if it is returning a promise object.
So
$(document).ready(function () {
$('#regname').focus();
$('#signupForm').submit(function (e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
//prevent the form submit
e.preventDefault();
if (regname.val() == '') {
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
} else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
} else if (regpass.val() == '') {
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
} else {
emailCheck().done(function (r) {
if (r) {
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
} else {
$('#signupForm')[0].submit();
}
});
}
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {
regemail: regemail.val()
};
var deferred = jQuery.Deferred();
$.ajax({
type: 'POST',
cache: false,
data: UrlToPass,
url: 'emailcheck.php',
success: function (responseText) {
if (responseText == 0) {
deferred.resolve(false);
} else {
emailcheck.html('<span class="errorss"> This email is existed.</span>');
deferred.resolve(true);
}
},
error: function () {
deferred.reject();
}
});
return deferred.promise();
}
You are confusing yourself with sync and async functions. An ajax function makes an Async call and returns output in its callback. You are trying to wrap an Async function inside a normal function and expecting it to behave synchronously.
Your function returns before the Ajax call receives its output. Use
async: false
$.ajax({
type : 'POST',
cache: false,
async: false,
data : UrlToPass,
Refer to following for dettails:
How to make JQuery-AJAX request synchronous

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