Update input fields one at a time without page refresh - javascript

I have a mixture of input fields, textareas and combo boxes which I would like to be able to update one at a time (without page refresh) but I am not quite sure how to approach this. When update is clicked it should update the MySQL Database respectively. I know how to update all of them at the same time but I am trying to avoid using this method. Every input, textarea, combo has a input type submit next to them to get me started.
This is part of the html file that I am referring too.
<form action="" class="customform" method="post" id="file-upload-form" enctype="multipart/form-data">
<h5>Set competition name</h5>
<input type="text" id="Gamename" name="Gamename" value="<?php echo $GameName; ?>" size="400" style="max-width: 410px"> <input name="Update1" type="submit" value="Update" style="width: auto;">
<h5>Set competition date & time</h5>
<input type="text" id="demo" name="timedate" value="<?php echo $sdate; ?>" size="200" style="max-width: 210px"> <input name="Update2" type="submit" value="Update" style="width: auto;">
What would be the best way to achieve this? Would I need to use Ajax, Javascript or Jquery? I am not asking for all the code to be written for me, just some guidance on how to approach it. thanks

Try:
HTML
<div id="output"></div> // This is where response (res/err) will be showed
JS
var form = document.getElementById("file-upload-form");
var output = document.getElementById("output");
form.onsubmit = () => {
fetch("your_page.php", {
method: "POST",
body: new FormData(form)
})
.then(res => res.text())
.then(res => {
output.innerHTML = res;
})
.catch((err) => output.innerHTML = err);
return false;
};
You don't need jQuery for such a simple task.

this was done by ajax full code is here with all guidance.
https://steemit.com/utopian-io/#sogata/how-to-update-data-mysql-from-php-without-reload-page-using-jquery-ajax
$.ajax({
url:'update.php',
method:'POST',
data:{
name:name,
ctgr:ctgr
},
success:function(response){
alert(response);
}
});

Related

Can't write AJAX output variable in html form

I need to print inside a span tag ("estimation2") the result of a calculation (for now, just a simple sum of the two input boxes "SHm2" and "STm2"). I'm using an AJAX call to perform that task. It seems to work perfectly until the alert, which shows the correct result, but for some reasons I can't write that result in my html form. I've been looking around and tried several things, yet none of them worked. For instance I've tried using the write method but it didn't work or stuff like $("#estimation2").html(estimation); or
document.getElementById("estimation2").innerHTML = estimation;
The only way I managed to get it written was by using window.onload, but this generates the calculation when the page loads, and I don't want that. I only want the AJAX code to be triggered when I click on my button.
Also, just for info, the calculation is made in my django view, even though I don't think it's relevant here as it looks to work properly. I'm really lost here, could you please help?
Here is my html code and the AJAX script:
<input type="text" id="SHm2" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" onclick="calculate()">Estimation</button>
<label>Result:</label>
<span id="estimation2"></span>
<script type="text/javascript">
function calculate () {
var SHm2 = $('#SHm2').val();
var STm2 = $('#STm2').val();
$.ajax({
url: '/myApp/templates/homepage/',
type: 'POST',
data: {
'SHm2':SHm2,
'STm2':STm2,
estimation: 'estimation',
},
success: function(estimation) {
alert(estimation);
document.getElementById("estimation2").innerHTML = estimation;
}
});
}
</script>
so what you wanna do is run the JS after the HTML document has loaded, and as mentioned in the comment section you need to add type="button" to estimation button
HTML
<input type="text" id="SHm2" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" type="button" onclick="calculate()" >Estimation</button>
<label>Result:</label>
<span id="estimation2"></span>
JS
$(document).ready(function() {
function calculate() {
var SHm2 = $("#SHm2").val();
var STm2 = $("#STm2").val();
$.ajax({
url: "/myApp/templates/homepage/",
type: "POST",
data: {
SHm2: SHm2,
STm2: STm2,
estimation: "estimation"
},
success: function(estimation) {
console.log(estimation);
document.getElementById("estimation2").innerHTML = estimation;
}
});
}
});

Javascript from processor - unable to debug issues

I have a form that I'm trying to submit and process with javascript using the code outlined below:
Form:
<form id="my_form_id" method="POST" action="my_processor_script.php">
<input type="text" id="form_id_1" name="form_field_1">
<input type="text" id="form_id_2" name="form_field_2">
<input type="text" id="form_id_3" name="form_field_3">
<input class="cbp-mc-submit" type="submit" name="save_settings_button" id="save_settings" value="Save Settings" />
</form>
Script:
<script>
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
alert("Form Processed");
},'json');
return false;
});
});
</script>
Processor:
<?php if (isset($post_data['save_settings_button']))
{
$form_field_1 = $_POST['form_field_1'];}
$form_field_2 = $_POST['form_field_2'];}
$form_field_3 = $_POST['form_field_3'];}
}
?>
Once I have the variables I then store them in a database.
The form works great if I just post from the form to the processor script without using the javascript however when I use the javascript nothing happens. I'm obviously doing something very wrong but can work this out at all as I cant see what is being received by the processor. Has anyone got any ideas on how i can get this to work?
It would also be great if I can return the data so that I can see what is being passed to the script as this would help me to debug any issues?

Using AJAX to submit form

I have developed a Python API and am now integrating it with a HTML template I have downloaded. It is a simple one page HTML template with a form to accept a album name and artist name. I am looking to process the form using AJAX. So once the form has been successfully submitted, it is replaced with a message returned by the API.
The (simplified) html snippet is:
<div class="form">
<form role="form" action="form.php" id="signup">
<div class="form-group">
<label>Artist Name</label>
<input type="text" name="artist" id="artist">
</div>
<div class="form-group">
<label>Tracking Number</label>
<input type="text" name="album" class="album">
</div>
<button type="submit" class="btn">Submit!</button>
</form>
</div>
Then I have a JS file I import at the beginning of the html file. Below is the JS file.
$(function() {
var form = $('#signup');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = {
'artist' : $('input[name=artist]').val(),
'album' : $('input[name=album]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'form.php',
data : formData,
dataType : 'json'
})
.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
I think the issue is with the .done(function(data)) however, the website I found the code on wasn't clear.
form.php returns a JSON string. At the moment when I use the form, it sends the information to the Python API and the Python API returns a JSON message. But I cannot access the JSON message. It is in contains
'code': X, 'message':'returned messaged...'
ideally I would like to do a if/else statement. So
if code = 1:
display: Success
etc but I have no idea where to start with it in PHP/JS.
I was able to get it working eventually after seeing a few other stack overflow answers and another website.
I added one div to the html file under the button before the end of the form to make:
<form>
...
...
<button type="submit" class="btn">Submit!</button>
<div id="thanks" style="display:none;"></div>
</form>
Then, in the JS file I amended .done(function(data)) to be:
.done(function(data) {
if (data.result == '1') {
$('#thanks').show().text("Success!");
$('input[type="text"],text').val('');
} else if (data.result == '2') {
$('#thanks').show().text("Album and Artist already exists");
} else {
$('#thanks').show().text("Uh Oh. Something has gone wrong. Please try again later or contact me for more help");
}
});

Using results from a post request in a javascript variable

I have a very basic question (I'm sure) - I have an Zoho application and I'm using their REST API to recover a single result from a table.
I want to use that result in a javascript variable - the form request is here:
<form id="Latest" method="POST" action="https://creator.zoho.com/api/xml/my-company-culture/view/PageFeed_Report">
<input type="hidden" name ="authtoken" value="**********************">
<input type="hidden" name ="scope" id="scope" value="creatorapi">
<input type="submit" value="View Records">
</form>
I can auto submit the form using this
<script type="text/javascript">
document.getElementById("Latest").submit();
</script>
Which recovers a the result - but I want to assign this result to a javascript variable and use it in a following piece of code (within the same frame).
I am new to this, so please be gentle! Any help appreciated.
This is easily done with jQuery:
<form id="Latest">
<input type="hidden" name ="authtoken" value="**********************">
<input type="hidden" name ="scope" id="scope" value="creatorapi">
<input type="submit" value="View Records">
</form>
<div id="result"></div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('#Latest').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var url = "https://creator.zoho.com/api/xml/my-company-culture/view/PageFeed_Report";
// Get some values from elements on the page:
var $form = $( this );
var authtokenData = $('#authtoken').attr('value');
var scopeData = $('#scope').attr('value');
// Send the data using post
var posting = $.post( url,
{
authtoken: authtokenData,
scope: scopeData
}
);
// Put the results in a div
posting.done(function( data ) {
// empty results div
$("#result").empty()
// write POST result to results div
$("#result").append("<p>" + data + "</p>);
});
});
</script>

Alloy UI problems with javascript function

I'm breaking my head trying to call a js function from a button element inside a form, here is my code:
<%
PortletPreferences prefs = renderRequest.getPreferences();
String employee = (String)prefs.getValue("name", "New Employee");
%>
<portlet:actionURL var="callURL" windowState="<%=LiferayWindowState.EXCLUSIVE.toString() %>" />
<script type="text/javascript">
Liferay.provide(window, 'insertEmployee',
function ()
{
var A = AUI();
var url = 'http://localhost:8080/c/portal/json_Service';
A.io.request(url,
{
method:'POST',
data:
{
serviceClassName: 'com.liferay.test.service.TrabajadorServiceUtil',
serviceMethodName: 'create',
servletContextName: 'TrabajadorPlugin-portlet',
serviceParameters: '[param]',
},
headers: {'Content-Type':'charset=utf-8'},
on:
{
success: function()
{
alert("success " + responseData.name);
}
},
form: {id: 'postForm'},
xdr: {dataType: 'json'}
});
},
['aui-io']
);
</script>
<div>
<aui:form name="postForm" id="postForm" method="post" onSubmit="insertEmployee();">
<input type="text" name="param" value="<%=employee %>"/>
<input type="submit" value="Submit"/>
</aui:form>
</div>
I'm not using an java class, thus I'm not using the portlet:actionURL either.
My intention is to call "insertEmployee()" when clicking the 'Submit' button, but it's only sending the param inserted by the user inside the text field. I've tried to put the 'onsubmit' also in the submit input, but the same result is given.
If you could help me or guide me to solve issue it would be so great! I'm not finding good information/tuts on the internet and I'm not sure where is the problem or what else I need to know.
Thanks a lot in advance!
I just need:
<aui:script>
window.functionName = function ()
{
//code
};
</aui:script>
and call it from:
<aui:form name="myform" action="javascript:functionName();">
<aui:input type="submit" name="Submit" value="Update"/>
</aui:form>
and the function is being called from the form tag.

Categories