Display HTML Form Values in Same Page After Submit Using Ajax

How to display html form values in same page after submit?

If you want to use a form with submit button, then you need to use the submit action of the form, and prevent the default.

let form       = document.querySelector('form');let nameClinet = document.querySelector('#nameClient');let output     = document.querySelector('#output');
form.onsubmit = function(e){ e.preventDefault(); // stop the submit from actually happening console.log("Client Name:", nameClient.value); output.innerText = nameClient.value;}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/><form>  <div class="input-field col s6">    <i class="material-icons prefix">perm_identity</i>    <input placeholder="..." id="nameClient" name="nameClient" type="text" class="validate">    <label for="nameClient">Nome do cliente:</label>    <h2 id="output"></h2>  </div>
<button class="btn waves-effect waves-light indigo" id="publish-sell" type="submit"> <i class="material-icons left">attach_money</i>EFETUAR VENDA </button></form>

Using AJAX to submit to same page and show content if $_GET['submit'] is set

getfiles.php:

<?php 
$old_directory = 'oldeshots';
$scanned_old = array_diff(scandir($old_directory), array('..', '.'));
echo json_encode($scanned_old);

ajax code:

$('#submit').on('click', function(e){
e.preventDefault();
$.ajax({
url:'getfiles.php',
data: {myvar1: 'value', myvar2: 'value2'}, // You don't need this in this case. But this is how you use it.
dataType: 'json',
success:function(data) {
$.each(data, function(i,value){
$(".list-group").append('<li class="list-group-item"><a href="'+ value +'?old=true">'+value+'</a></li>');
});
}
});
});

Stay on same page after a form submit using ajax

run this file in seperate

index.php

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post</title>
</head>
<body>

<form class="postForm" id="postForm" method="post" action="addPost.php" enctype="multipart/form-data">

<fieldset>
<legend>Please add the details below </legend>
<p>
<label for="title">Title (required, at least 2 characters)</label>
<input id="title" name="title" minlength="2" type="text" required>
</p>

<p>
<label for="desc">Description (required, at least 2 characters)</label>
<input id="desc" name="desc" minlength="2" type="text" required>
</p>
<p>
<label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
<input id="keywords" name="keywords" minlength="2" type="text" required>
</p>

<select id="types" name="types" onchange="myFunction(this)">

<option value="">Select type</option>

<option value="2">Add Link</option>
<option value="0">Upload Image</option>
<option value="1">Upload Video</option>

</select><br><br>

<div id="link" style="display: none">

<p>
<label for="url">URL (required)</label>
<input id="url" type="url" name="url" required>
</p>

<p>
<label for="urlType">Select Url Type :(required)</label>
<select name="urlType" id="urlType">
<option value="">Select Url Type...</option>
<!-- <option value="0">Server Image</option>
<option value="1">Server Video</option>-->
<option value="2">YouTube Video</option>
<option value="3">Vimeo Video</option>
<option value="4">Facebook Image</option>
<option value="5">Facebook Video</option>
<option value="6">Instagram Image</option>
<option value="7">Instagram Video</option>
<option value="-1">Other</option>
</select>
</p>

</div>

<div id="filediv" style="display: none">

Select file to upload:
<br><br>
<input name="file1" type="file" id="fileToUpload"><br><br>

</div>


<p>
<label for="postType"> Select Post Type :(required)</label>
<select name="postType" id="postType">
<option value="">Select Post Type...</option>
<option value="0">Normal</option>
<option value="1">Featured</option>
<option value="2">Sponsored</option>
</select>
</p>
<p>
<label for="category"> Select Category :(required)</label>
<select name="category" id="category">
<option value="s">Select Category...</option>
</select>
</p>
<p>
<input type="hidden" name="action_type" id="action_type_id"/>
<input type="hidden" name="id" id="p_id"/>
<!-- <a href="javascript:void(0);" class="btn btn-warning" onclick="$('#postForm').slideUp();">Cancel</a>
<a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')">Add User</a>-->
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</fieldset>

<div class="result" id="result"></div>


</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>

<script>
window.onerror = function(error, url, line) {
controller.sendLog({acc:'error', data:'ERR:'+error+' URL:'+url+' L:'+line});
};

$(document).ready(function(){
getCategories();
/*

$("#postForm").submit(function(e){
e.preventDefault();
});
*/

$('#postForm').validate({ // initialize the plugin
rules: {
title: {
required: true,
minlength : 2
},
url: {
required: true
},
desc: {
required : true,
minlength : 2
},
keywords : {
required : true,
minlength : 2
},
urlType :
{
required : true
},
postType :
{
required : true
},
category :
{
required : true
},
file1 :
{
required : true
}
},
submitHandler: function (form) {


var url = document.getElementById('urlType').value;

if(validate_url(document.getElementById('url').value) == 'facebook' && url == 6)
{
alert('Please enter valid facebook image,video url or select valid url type.');
}
else if(validate_url(document.getElementById('url').value) == 'facebook' && url == 7)
{
alert('Please enter valid facebook image,video url or select valid url type.');
}
else if(validate_url(document.getElementById('url').value) == 'facebook' && url == 3)
{
alert('Please enter valid facebook image,video url or select valid url type.');
}
else if(validate_url(document.getElementById('url').value) == 'facebook' && url == 2)
{
alert('Please enter valid facebook image,video url or select valid url type.');
}
else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 3)
{
alert('Please enter valid instagram image,video url or select valid url type.');
}
else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 2)
{
alert('Please enter valid instagram image,video url or select valid url type.');
}
else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 4)
{
alert('Please enter valid instagram image,video url or select valid url type.');
}
else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 5)
{
alert('Please enter valid instagram image,video url or select valid url type.');
}
else if(validate_url(document.getElementById('url').value) == 'vimeo' && url != 3)
{
alert('Please enter valid vimeo video url or select valid url type.');
}
else if(validate_url(document.getElementById('url').value) == 'youtube' && url != 2)
{
alert('Please enter valid youtube video url or select valid url type.');
}
else {


userAction('add');

/* var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});

$.ajax({
type: "POST",
url: 'addPost.php',
dataType: 'text',
data: $('#postForm').serialize(),
async: false,
cache: false,
success: function (result) {
//alert(report);
$(".result").html(report);
$("#postForm").trigger('reset');
}
});
*/

/* jQuery.ajax({
url: 'addPost.php',
// data: data,
data: $('#postForm').serialize(),
cache: false,
contentType: false,
processData: false,
encctype: "multipart/form-data",
type: 'POST',
success: function(report){
alert(report);
// $(".result").html(report);
$("#postForm").trigger('reset');
}
});*/
// e.preventDefault();
}
}
});

});

function getCategories() {

$.ajax({
type: "POST",
url: 'getCategories.php',
dataType: 'text',
async: false,
cache: false,
success: function (result) {

$('#category').html(result);
}
});

}


function userAction(type,id){

/* var statusArr = {add:"added",edit:"updated",delete:"deleted"};

*/


var form = $('#postForm')[0];

// Create an FormData object
var data = new FormData(form);

if (type == 'add') {

$('#action_type_id').val(type);
$('#p_id').val(id);
}

$.ajax({
type: 'POST',
url: 'add.php',
processData: false,
contentType: false,
data : data,
success:function(report){
// replace data to report

$(".result").html(report);
$("#postForm").trigger('reset');
}
});
// e.preventDefault();

/*
$("form#data").submit(function(){

var formData = new FormData($(this)[0]);

$.ajax({
url: 'addPost.php',
type: 'POST',
data: formData,
success: function (data) {
$(".result").html(report);
$("#postForm").trigger('reset');
},
cache: false,
contentType: false,
processData: false
});*/

/* var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});


jQuery.ajax({
url: 'addPost.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(report){
$(".result").html(report);
$("#postForm").trigger('reset');
}
});*/

}

function myFunction(obj) {

var type = obj.value;
var x = document.getElementById('link');
var y = document.getElementById('filediv');


if(type == "2")
{
x.style.display = 'block';
y.style.display = 'none';
}
else {
x.style.display = 'none';
y.style.display = 'block';
}

}

function validate_url(url)
{
if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
return 'facebook';

if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
return 'facebook';

if (/^(https?:\/\/)?((w{3}\.)?)instagram.com\/.*/i.test(url))
return 'instagram';

if (/^(https?:\/\/)?((w{3}\.)?)vimeo.com\/.*/i.test(url))
return 'vimeo';

if (/^(https?:\/\/)?((w{3}\.)?)youtube.com\/.*/i.test(url))
return 'youtube';

return 'unknown';
}

</script>

</body>
</html>

add.php

<?php

echo "<pre>"; print_r($_FILES);
exit();


?>

Online waiting: django submit form and display result in same page

I would suggest taking a look at htmx.org which makes this really simple without having to write any actual JS.

For your example:

(1) You add the htmx JS (which is only about 10k) to your HTML, and use hx-post and hx-target to trigger the ajax calls on your form. With these the form will fire an AJAX request, and the hx-target tells htmx to take the response (which you want to be only the result of your calculation) and put it in the div without refreshing the whole page.
See docs for more details on this.
Note also I gave an id to the div containing the result.
You will need to replace hx-post="{% url 'blog:post_list' %}" with the correct name to your view (which we don't know as you didn't post your urls.py).

<html>
<body>
<form method="POST" hx-post="{% url 'blog:post_list' %}" hx-target="#result">
{% csrf_token %}
<div>
<label>num_1:</label>
<input type="text" name="num_1" value="1" placeholder="Enter value" />
</div>
<div>
<label>num_2:</label>
<input type="text" name="num_2" value="2" placeholder="Enter value" />
</div>
<br />
<div id="result">{{ result }}</div>
<button type="submit">Submit</button>
</form>
<script src="https://unpkg.com/htmx.org@1.6.1"></script>
</body>
</html>

(2) In your view then you determine if the request is an AJAX request from htmx by checking the headers, in which case you want to only return the result. There are easier or elegant ways to do this (eg. check django-htmx, but just to keep it simple:

from django.http.response import HttpResponse
from django.shortcuts import render

# Create your views here.
def post_list(request):
result = 0
if request.method == "POST":
num1 = request.POST.get('num_1')
num2 = request.POST.get('num_2')
result = int(num1) + int(num2)

if request.headers.get('Hx-Request') == 'true':
# return only the result to be replaced
return HttpResponse(str(result))
else:
return render(request, 'blog/post_list.html', {'result': result})

How to send form data and display them dynamically with ajax in the same page

I am not a strong advocate on using javascript framework, however, ajax is a pain to handle without it, so here is an example using JQuery, but it's possible to do more or less the same thing with any other framework.

The first step is to intercept the submit event, then get the form data, perform an ajax query and display results in a div.

<!DOCTYPE doctype html>
<html>
<head>
</head>
<script src="jquery-3.1.0.min.js">
</script>
<script>
jQuery( document ).ready(function() {
jQuery('#myForm').submit(function(e){
e.preventDefault();

jQuery.ajax({
url: e.currentTarget.action,
data:{
comment: jQuery('#comment').val()
}
}).done(function(data){
console.log(data);
jQuery('#display-data').append(data);
});
});
});
</script>
<body>
<form id="myForm" action="getData.php" method="post">
<div class="form-group">
<label for="comment">
</label>
<textarea class="form-control" id="comment" name="message_content" required="" rows="5">
</textarea>
</div>
<button class="btn btn-default" name="send_msg" type="submit">
send
</button>
</form>
<div id="display-data"></div>
</body>
</html>

EDIT: From your comment, I gathered you wanted to reload page after submission, you can do it after at the end of your ajax query :

jQuery('#myForm').submit(function(e){
e.preventDefault();

jQuery.ajax({
url: e.currentTarget.action,
data:{
comment: jQuery('#comment').val()
}
}).done(function(data){
document.location.reload();
});
});

get the form values on the same page after submit the the form in vue.js

Since you want the inputed values in the form show up af

ter the form is successfully submitted

  1. Add a property in your data property as below:

    data(){
    return{
    showFormValues = false;
    }
    }
  2. Add a div with the inputed values in paragraph tags below the form and show the div only if form is sucessfully sunbmitted usimg v-show as below:

    <div v-show="showFormValues">
    <p>date: {{ScheduleInterviewForm.schedule_datetime}}</p>
    <p>type: {{ScheduleInterviewForm.interview_type_id}}</p>
    </div>
  3. Now in the success part then block of your form submittion click method set the value of showFormValues = true like this:

    ScheduleInterview(form, hrcId) {
    var that = this;
    this.$refs[form].validate((valid) => {
    if (valid) {
    // AJAX: Create HrRequest
    axios.post('/ajax/schedule_interview', {
    interviewTypeId: this.ScheduleInterviewForm.interview_type_id,
    scheduleDatetime: this.ScheduleInterviewForm.schedule_datetime,
    hrcId
    })
    .then(function(res) {
    that.interviewScheduled = true;
    //show the input form values on succesful form submission
    that.showFormValues = true;
    setTimeout(() => that.interviewScheduled = false, 3000);
    console.log(res);
    // that.candidates = res.data.candidates;
    })
    .catch(function(err) {
    console.log(err);
    });
    } else {
    return false;
    }
    });
    },


Related Topics



Leave a reply



Submit