Get value from document.querySelector and insert into localhost database - javascript

I want to get the value from document.querySelector and save the data into the database via form with ajax and php, but the code I wrote did not run well / could not display the result, if there was an error in writing my code
<script>
//on the click of the submit button
$(document).ready(function () {
$("#submit").click(function () {
//get the form value
let no = document.querySelector('i[data-name="no"]').value;
let question = document.querySelector('i[data-name="question"]').value;
let countdown = document.querySelector('i[data-name="countdown"]').value;
let answer = document.querySelector('i[data-name="answer"]').value;
//make the postdata
var postData = 'no=' + no + '&question=' + question + '&countdown=' + countdown +
'&answer=' + answer;
if (no == '' || question == '' || countdown == '' || answer == '') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "post-answer.php",
data: postData,
cache: false,
success: function (result) {
alert(result);
}
});
}
return false;
});
});
</script>
this is the form I created
<form class="glass userform" method="post" data-ajax="false">
<i data-name='countdown'></i><i data-name='answer'></i>
<i data-name='no'></i>
<a href=""
style="float:right;font-size: 30px;width: 50px;margin-right:50px;margin-top:30px;display:
inline-block;"><i>Next</i></a>
<i data-name='question'></i>
<br>
<a href="#" onclick="checkboxtrue();"
style="width:100%;text-align: center;font-size: 30px;display: inline-block;"><i>Benar
</i></a><br>
<a href="#" onclick="checkboxfalse();"
style="width:100%;text-align: center;font-size: 30px;display: inline-block;"><i>Salah</i></a>
<br><br>
<input type="hidden" id="checkboxtotext" name="checkboxtotext" onkeyup="valueoftrueanswer()" />
<input id="submit" type="button" value="Submit">
</form>

Related

Sending two forms after button click and run php in background

I have created this site and integrated with payfast, it works well. but now i want to execute another php script on place order button which gets details into the db
here is my code quite long.... I no nothing about Ajax or javascript!! Please help
<form id="form1" action="payment.php" method="POST">
some stuff...
</form>
<?php
$htmlForm = '<form action="https://'.$pfHost.'/eng/process" method="post" id="form2">';
$htmlForm .= '<input type="submit" id="submit" name="submit" class="btn btn-primary btn-lg btn-flat" value="PLace Order" onclick="submitForms()"></form>';
?>
<?php
echo"
".$htmlForm."
</div>";
}
else{
echo '...';
}
?>
<script>
submitForms = function() {
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
</script>
$(function() {
$(".submit").click(function() {
var uid = $("#uid").val();
var prodtls = $("#prodtls").val();
var fname = $("#fname").val();
var amnt = $("#amnt").val();
var mail = $("#mail").val();
var dataString = 'uid='+ uid + '&prodtls=' + prodtls + '&fname' +fname + '&amnt' + amnt + '&mail' + mail;
if(time=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "payment.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
I tried the ajax i found but, it never worked. Check at the end of my code!
What i need is payment.php will execute in the background while it directs user to payfast
I want to submit only the first one via AJAX.
Your attempt doesn't make much sense because it doesn't appear to target the first form (which you say you want) and may not prevent the default postback behaviour.
As I understand it, you want that whichever form the user clicks on to submit, the code will actually then submit the first form via AJAX, and then the second one via standard postback.
This should do the job:
HTML:
<form id="form1" class="doubleForm" action="payment.php" method="post">
<input type="submit" id="submit1" name="submit" class="btn btn-primary btn-lg btn-flat" value="Submit">
</form>
<form id="form2" class="doubleForm" action="https://example.com/eng/process" method="post">';
<input type="submit" id="submit2" name="submit" class="btn btn-primary btn-lg btn-flat" value="Place Order">
</form>
JavaScript:
//handle submission of both forms
$(".doubleForm").submit(function(event) {
event.preventDefault(); //stop standard postback
var uid = $("#uid").val();
var prodtls = $("#prodtls").val();
var fname = $("#fname").val();
var amnt = $("#amnt").val();
var mail = $("#mail").val();
var dataString = 'uid='+ uid + '&prodtls=' + prodtls + '&fname' +fname + '&amnt' + amnt + '&mail' + mail;
if(time == '' || date == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
//submit first form via AJAX
var request = $.ajax({
type: "POST",
url: "payment.php",
data: dataString
});
request.done(function(response) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
//now the first form is submitted and server has responded, we can trigger "normal" (non-AJAX) submission of second form
document.querySelector("#form2").submit();
});
}
});
So this actually worked well using .serialize(). Thanks #ADyson for the headsup just had to tweak it a little bit, though i'm not experienced in js
<script type="text/javascript">
$(function(){
$("#submit2").click(function(){
var dataString = $("#form1").serialize();
$.ajax({
type: "POST",
url: "payment.php",
data: dataString,
success: function(data)
{
alert('Success!');
$("#form1")[0].reset();
}
});
});
});
</script>

The response received in AJAX call is shown in another HTML page

I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.
Form HTML
<form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">
<div class="form-group">
<input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
<button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>
</div>
</form>
AJAX
<script>
$("#AssociateForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var local_id = $('input[name=J_ID]').attr('id');
var formData = {
'J_ID' : $('input[name=J_ID]').val()
};
console.log(formData)
$.ajax({
url: url,
data: formData,
dataType: 'json',
success: function (datas) {
var data = JSON.parse(datas);
if(datas.status){
alert(datas);
//$('#Failure_'+local_id).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')'
}
},
error: function(jqXHR, textStatus){
alert("In error")
}
})
.done(function(data){
alert(data)
});
});
</script>
for some reason, the above code is not printing the console log as well.
But,
When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.
JSON Response
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
below is from View-Page-source
<html>
<head></head>
<body data-gr-c-s-loaded="true">
<pre style="word-wrap: break-word; white-space: pre-wrap;">
{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}
</pre>
</body>
</html>
This is possibly because you are submitting a form, and after submitting it will open a new tab, as Form is submitted.
To resolve this, you can probably use the below code:
<form action="..." method="POST" target="_blank">
<input type="submit" id="btn-form-submit"/>
</form>
<script>
$('#btn-submit').click( function(){ $('#btn-form-submit').click(); } );
</script>
success: function (datas) {
if (datas.status) {
alert(datas);
$('pre#<ID>').html(datas.category + ' issue: ' + datas.j_id + ' (' + datas.j_status + ')');
}
}
This worked for me, I removed the form completely.
Code in-place of Form
<div class="form-group AssociateForm" style="float:right">
<input type="text" name="J_ID" style="width:150px;float:left" class="form-control has-success">
<button name="button" type="submit" id="{{TR.id}}" class="Associater btn btn-primary">Associate</button>
</div>
AJAX
<script>
$('.Associater').on('click', function () {
var local_id = $(this).attr('id');
var j_id = $(this).closest("div.AssociateForm").find('input[name=J_ID]').val();
if (j_id === "") {
alert("JID cannot be empty")
return false
}
var url = "{% url 'Project:View' 0 %}".replace('0', local_id);
var formData = {
'J_ID' : j_id,
'csrfmiddlewaretoken': '{{ csrf_token }}'
};
console.log(local_id);
console.log(j_id);
console.log(url);
console.log(formData);
$.ajax({
type: 'POST',
url: url,
data: formData,
dataType: 'json',
success: function (data) {
if (data.status) {
ele = 'Failure_'+local_id;
document.getElementById(ele).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')';
}
},
error: function (jqXHR, textStatus ) {
alert("For some reason im here");
}
});
});
</script>

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.

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>

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")
}
});
}

Categories

Resources