Receiving data from the server without updating the page - javascript

Good day!
I'll Forgive Forgiveness, I'm zero in programming. But I want to learn. I need to transfer data using the POST method, without updating the page. Through django, how should the javascript and views.py look like!
<form class="form-horizontal" role="form" method="post" id="lol">
<div class="form-group">
<label for="" class="col-sm-2 control-label">ФИО</label>
<div class="col-sm-4">
<input name="firstname" class="form-control" placeholder="ФИО">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Шифр Группы</label>
<div class="col-sm-4">
<input name="Code" class="form-control" placeholder="Шифр Группы">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Пол</label>
<div class="col-sm-4">
<input name="Pol" class="form-control" placeholder="М или Ж">
</div> </div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Семейное положение</label>
<div class="col-sm-4">
<input name="Floor" class="form-control" placeholder="0 или 1">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Номер комнаты</label>
<div class="col-sm-4">
<input name="Room" class="form-control" placeholder="Номер комнаты">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Войти</button>
</div>
</div>
</form>
<div class="examples">
<script language="javascript" type="text/javascript">
</script>
<div class="results">Ждем ответа</div>
#csrf_exempt
def polls(request, form=None):
if request.method == 'POST' and form.is_valid():
pass
else:
return render(request, 'base.html')

In Html page first change type of "Войти" button from "submit" to "button"
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" id="submit_button" class="btn btn-default">Войти</button>
</div>
add id tag to all input element. for example
<input name="firstname" id="firstname" class="form-control" placeholder="ФИО">
<input name="Code" id="Code" class="form-control" placeholder="Шифр Группы">
Then add Script in html page
<script type="text/javascript">
$('#submit_button').click( function (){
$.ajax({
url: '/submit/',
data: {
'firstname': $("#firstname").val(),
'Code': $("#Code").val(),
// and all other input element
},
type: 'post',
cache: false,
success: function (data) {
if (data.status)
{
alert('Post method');
}
else{
alert('error')
}
}
});
});
</script>
Then add this line to project urls.py file of django
urlpatterns = [
url(r'',include('YourAppName.urls')),
]
Then create urls.py file in your app directory and add
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^submit/', views.get_ajax_request, name='ajaxPost'),
]
In view your code will be like
import json
from django.shortcuts import HttpResponse
from django.core.serializers.json import DjangoJSONEncoder
def get_ajax_request(request):
room = request.POST.get('Room') # get html element value by name tag of element
##############
Your Operation
##############
response = {'status':True,'msg':'Success'}
return HttpResponse(json.dumps(response, cls=DjangoJSONEncoder))

Related

Pass data to PHP file using Ajax

I'm trying to pass data to PHP file using Ajax and then save to MySQL database. From some reasons it's not working. I tested PHP code with passing data from HTML form and it's working. When use Ajax, after click on submit button nothings happen. I think that the problem is in Ajax data parameter.
Here is the code:
HTML
<body>
<div class="container">
<form class="search" action="" method="">
<div class="form-group">
<div class="input-group input-group-lg">
<span class="input-group-addon"><i class="fa fa-search" aria-hidden="true"></i></span>
<input type="text" class="form-control form-control-lg" id="trazi" name="trazi" placeholder="Pretražite artikle - upišite naziv, barkod ili šifru artikla">
</div>
</div>
</form>
<form class="articles" id="novi_artikl" action="" method="">
<div class="form-group row">
<label for="sifra" class="col-sm-4 col-form-label col-form-label-lg">Šifra artikla</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-lg" id="sifra" name="sifra" placeholder="Upišite šifru">
</div>
</div>
<div class="form-group row">
<label for="barkod" class="col-sm-4 col-form-label col-form-label-lg">Barkod artikla</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-lg" id="barkod" name="barkod" placeholder="Upišite barkod">
</div>
</div>
<div class="form-group row">
<label for="naziv" class="col-sm-4 col-form-label col-form-label-lg">Naziv artikla</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-lg" id="naziv" name="naziv" placeholder="Upišite naziv artikla" required>
</div>
</div>
<div class="form-group row">
<label for="mjera" class="col-sm-4 col-form-label col-form-label-lg">Jedinična mjera</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-lg" id="mjera" name="mjera" placeholder="Upišite mjeru" required>
</div>
</div>
<div class="form-group row">
<label for="cijena" class="col-sm-4 col-form-label col-form-label-lg">Cijena artikla</label>
<div class="col-sm-8">
<div class="input-group input-group-lg">
<input type="text" class="form-control form-control-lg text-right" id="cijena" name="cijena" placeholder="Upišite cijenu" required>
<span class="input-group-addon">KM</span>
</div>
</div>
</div>
<div class="form-group row">
<label for="kolicina" class="col-sm-4 col-form-label col-form-label-lg">Količina artikla</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-lg text-right" id="kolicina" name="kolicina" placeholder="Upišite količinu" required>
</div>
</div>
<div class="form-group row">
<label for="ukupno" class="col-sm-4 col-form-label col-form-label-lg">Ukupna vrijednost artikla</label>
<div class="col-sm-8">
<div class="input-group input-group-lg">
<input type="text" class="form-control form-control-lg text-right" id="ukupno" name="ukupno" placeholder="Ukupna vrijednost" required>
<span class="input-group-addon">KM</span>
</div>
</div>
</div>
<br>
<div class="float-right">
<button type="submit" class="btn btn-primary btn-lg" id="spremi" name="spremi">Spremi</button>
<button type="submit" class="btn btn-primary btn-lg" id="ponisti" name="ponisti">Poništi</button>
</div>
</form><!-- Content here -->
</div>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script src="https://use.fontawesome.com/38d56b17e3.js"></script>
<script src="script.js" type="text/javascript"></script>
JavaScript
$('#spremi').click(function(){
var sifra = $('#sifra').val();
var barkod = $('#barkod').val();
var naziv = $('#naziv').val();
var mjera = $('#mjera').val();
var cijena = $('#cijena').val();
var kolicina = $('#kolicina').val();
var ukupno = $('#ukupno').val();
$.ajax({
type: 'POST',
url: 'insert.php',
contentType: "application/json; charset=utf-8",
dataType:'json',
data: ({sifra: sifra}, {barkod: barkod}, {naziv: naziv}, {mjera: mjera}, {cijena: cijena}, {kolicina: kolicina}, {ukupno: ukupno}),
success: function(response){
alert(response);
}
});
});
PHP code
<?php
include("connection.php");
if ($_POST["sifra"]) {
$sifra = $_POST["sifra"];
$barkod = $_POST["barkod"];
$naziv = $_POST["naziv"];
$mjera = $_POST["mjera"];
$cijena = $_POST["cijena"];
$kolicina = $_POST["kolicina"];
$ukupno = $_POST["ukupno"];
$query = "INSERT INTO lista (sifra, barkod, naziv, mjera, cijena, kolicina, ukupno) VALUES ('$sifra', '$barkod', '$naziv', '$mjera', '$cijena', '$kolicina', '$ukupno')";
$results = mysqli_query($dbc, $query);
if($results){
echo "Artikl je uspješno spremljen.";
}
else {
echo "Artikl nije spremljen. Došlo je do pogreške.";
}
}
mysqli_close($dbc);
?>
You should provide the values to the data property of $.ajax as a single object not as a collection of them:
data: {
sifra: sifra,
barkod: barkod,
naziv: naziv,
mjera: mjera,
cijena: cijena,
kolicina: kolicina,
ukupno: ukupno
},
Also, it's very important that you note your PHP code is wide open to SQL injection attacks. You should change the logic to use prepared statements ASAP.
The cause of your problem is the fact you are using type: 'POST'. To quote the docs :
An associative array of variables passed to the current script via the
HTTP POST method when using application/x-www-form-urlencoded or
multipart/form-data as the HTTP Content-Type in the request.
POST is a more "old fashioned" method, typically you would POST a <form> where the content automatically is serialized, i.e urlencoded, but you try to POST data in a JSON format. What you should do is either consider whether you really need POST. If you change it to GET (or simply remove type: 'POST') and access the passed data by $_GET then it will work (as long as you correct data as well).
If not, change the content type to indicate incoming urlencoded data :
$.ajax({
type: 'POST',
url: 'insert.php',
contentType: "application/x-www-form-urlencoded",
data: {sifra: sifra, barkod: barkod, naziv: naziv, mjera: mjera, cijena: cijena, kolicina: kolicina, ukupno: ukupno},
success: function(response){
alert(response);
}
});
I am pretty sure your code will work now, i.e the $_POST works and any message is properly received as plain text you can alert.

Pass form results to another form into a form value

I have two forms on a page the "top form" searches for movies and I'm trying to get the data found from the top form and pass it as a value to the bottom form so it can get entered into a database.
I am unable to do this but, I can get the results to be displayed on the page. Here is my code:
TOP FORM DATA
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<?php
$squery="";
if(isset($_GET["squery"]))
{
$squery=$_GET["squery"];
}
?>
<div class="col-xs-8 col-xs-offset-2">
<form action="#" method="GET" class="form-horizontal">
<div class="form-group">
<label for="newMovieName" class="col-sm-3 control-label">Search what movie?</label>
<div class="col-sm-9"> <input type="text" name="squery" class="form-control"><br />
<input type="submit" value="Submit" class="btn btn-success"></div></div>
</form>
<script type="text/javascript" charset="utf-8">
var api_key = '6969696969696969696969696969696';
$(document).ready(function(){
$.ajax({
url: 'http://api.themoviedb.org/3/search/movie?api_key=' + api_key + '&query=<?php echo $squery; ?>',
dataType: 'jsonp',
jsonpCallback: 'testing'
}).error(function() {
console.log('error')
}).done(function(response) {
var i=0;
// for (var i = 0; i < response.results.length; i++) {
$('#search_results').append('<li>' + response.results[i].title + '</li>');
// }
$('#search_results_title').append(response.results[i].title);
$('#search_results_release').append(response.results[i].release_date);
$('#search_results_overview').append(response.results[i].overview);
$('#search_results_poster').append('https://image.tmdb.org/t/p/w185' + response.results[i].poster_path);
$('#search_results_votes').append(response.results[i].vote_count);
});
});
</script>
TOP FORM RESULTS
Here is where the results are displayed from the form above BUT, I would like these results to be displayed as a value in the form below.
<h3>Results</h3>
<p id="error"></p>
<ul id="search_results_title"></ul>
<ul id="search_results_release"></ul>
<ul id="search_results_overview"></ul>
<ul id="search_results_poster"></ul>
<ul id="search_results_votes"></ul>
BOTTOM FORM DATA
Here is the bottom form that SHOULD get submitted to the database with the "Results" that are above as the value.
<form class="form-horizontal" role="form" action="processmovie.php" method="get" enctype="text/plain">
<div class="form-group">
<label for="newMovieName" class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="newMovieName" name="movie_name" placeholder="Movie Title" required value="">
</div>
</div>
<div class="form-group">
<label for="movieYear" class="col-sm-3 control-label">Year</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="movieYear" name="movie_year" placeholder="Year" required>
</div>
</div>
<div class="form-group">
<label for="movieBio" class="col-sm-3 control-label">Storyline</label>
<div class="col-sm-9">
<textarea type="email" class="form-control" id="movieBio" name="movie_bio" rows="4" placeholder="Enter Storyline" required></textarea>
</div>
</div>
<div class="form-group">
<label for="newImage" class="col-sm-3 control-label">Movie Cover URL</label>
<div class="col-sm-9">
<input type="text" id="newImage" class="form-control" name="movie_img" placeholder="Enter URL" required>
</div>
</div>
<div class="form-group">
<label for="movieRating" class="col-sm-3 control-label">Rating</label>
<div class="col-sm-9">
<select id="movieRating" name="movie_rating" class="form-control" required>
<option value="G">G</option>
<option value="PG">PG</option>
<option value="PG-13">PG-13</option>
<option value="R">R</option>
<option value="NR">NR (Not Rated)</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-success">Add Movie</button>
</div>
</div>
</form>
I tried to use a variaty of code to try and get the value here is an example: <?php echo $_GET['search_results_title'];?>
I've also found examples like this: How to pass the value of a form to another form? but, my forms are on the same page and not different ones.
As I said in my comment, you would just want to change your ajax call to something like this:
$.ajax({
url: 'http://api.themoviedb.org/3/search/movie?api_key=' + api_key + '&query=<?php echo $squery; ?>',
dataType: 'jsonp',
jsonpCallback: 'testing'
}).error(function() {
console.log('error')
}).done(function(response) {
var i=0;
$('#newMovieName').val(response.results[i].title);
$('#movieYear').val(response.results[i].release_date);
$('#movieBio').val(response.results[i].overview);
$('#newImage').val('https://image.tmdb.org/t/p/w185' + response.results[i].poster_path);
});
(I'm not sure about the relationship you have between response.results[i].vote_count and movieRating)
Here is a fiddle sort of showing the result, though I can't exactly replicate your code there because of the ajax calls

Error in submitting form using ajax

For some reason, the form is not getting submitted. I have used ajax form to save the form details in my database.
Here is the site link:
http://www.famproperties.com/mudon/Abu-Dhabi/villas.html
Here is the script code.
<script>
$(document).ready(function() {
$("#submit-form-button").click(function() { submitForm(); });
});
function submitForm() {
if ( $("#NAME").val() == '' ||
$("#EMAIL").val() == '' ||
$("#MOBILE").val() == '' ||
$("#NOTE").val() == '' )
{ alert ("All field are required");}
else {
$.ajax({
type: "POST",
url: "http://famproperties.com/real_estate/property/contact/lead/",
data: {
NAME: $("#NAME").val(),
EMAIL: $("#EMAIL").val(),
MOBILE: $("#MOBILE").val(),
NOTE: $("#NOTE").val(),
SOURCE: 'MSB.COM'
},
success: function() {
alert("Thanks, Our specialist will contact you soon.");
},
dataType: 'html'
});
$("#NAME").val('');
$("#EMAIL").val('');
$("#MOBILE").val('');
$("#NOTE").val('');
}};
</script>
Here is the form code.
<!--NEW FORM -->
<div class="form-horizontal" role="form" accept-charset="UTF-8" action="http://famproperties.com/real_estate/property/contact/lead/" autocomplete="on" id="pro-form" method="post">
<div class="form-group">
<label for="NAME" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="NAME" required="" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="EMAIL" class="col-sm-2 control-label ">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="EMAIL" required="" placeholder="me#example.com">
</div>
</div>
<div class="form-group">
<label for="MOBILE" class="col-sm-2 control-label">Mobile</label>
<div class="col-sm-10">
<input type="phone" class="form-control inputs" id="MOBILE" required="" placeholder="Mobile">
</div>
</div>
<div class="form-group">
<label for="NOTE" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="NOTE" required="" placeholder="Note">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<a href="#" onclick="return false" class="btn btn-default btn-lg button" id="submit-form-button" style="background-color: #ffc600;
color: #2a292a;
width: 100%;"> Submit <span class="fa fa-chevron-right fa-1x"></span><span class="fa fa-chevron-right fa-1x"></span> </a>
</div>
</div>
</div>
<!--NEW FORM-->
Seeing the page on http://www.famproperties.com/mudon/Abu-Dhabi/villas.html you are not even loading jquery check the console and youll see this error:
Uncaught ReferenceError: $ is not defined
Thats why ajax is not working
Edit: Sorry, checking your code again i saw you are loading jQuery but you are trying to use jQuery before loading it. So, try moving the jquery script tag to the header or move your js below the jQuery script tag.

How to empty ajax loaded form?

How can we empty a ajax loaded form using pure JavaScript or jQuery.
I have tried document.forms[0].reset(); and $('#new-staff-form')[0].reset(); both didn't work it returns undefined.
Update
<div class="box col-md-12 new-staff">
<form id="new-staff-form" method="post">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" name="f_name" placeholder="First name"/>
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" name="l_name" placeholder="Last name"/>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label for="user_name">User name</label>
<input id="user_name" type="text" name="user_name" placeholder="User name"/>
</div>
<div class="col-md-6">
<button id="user-avail" class="btn btn-primary">Check available</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary pull-left">Save</button>
</div>
</div>
</form>
</div>
Javascript:
$('#new-item').click(function(){ // works fine until I load new html form using ajax with same ids and class
$('#new-staff-form')[0].reset();
$('.new-staff').slideToggle(); // show new form
});
$('.edit-item').click(function(){ // ajax call this loads everything correctly
var id = $(this).data('staf_id'); //item to delete
$.ajax({
url:url_view_staff+id,
type:'get'
}).done(function(data){
edit_item_id = id;
$('.new-staff').html(data).slideDown();
}).fail(function(data){
$('#errors').html(data.responseText);
$('.valid-error').slideDown();
});
});
JavaScript:
document.getElementById("myForm").reset();
Jquery :
$('#form_id')[0].reset();
Make sure your form id is valid.
FIDDLE
$('#configreset').click(function(){
$('#configform')[0].reset();
});

Posting data to php script with sammy.js

Im trying to create a contact form by send data to a php script to send mail from a form in a sammy.js app. I've set it up as follows and it doesn't work. Can anyone explain why and get me in the right direction to fix it? Thanks!
html form:
<form class="form-horizontal" action="#/submitcontact">
<fieldset>
<div class="control-group">
<label class="control-label" for="input01">Your Name:</label>
<div class="controls">
<input type="text" class="input-xlarge" id="from-name">
<p class="help-block">Nice to know who the message is from.</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="input01">Your Email:</label>
<div class="controls">
<input type="text" class="input-xlarge" id="from-email">
<p class="help-block">Supply an email so I can reply.</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="input01">Your Message:</label>
<div class="controls">
<textarea class="input-xlarge" id="from-msg"></textarea>
<p class="help-block">Including a message is always nice.</p>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn" style="position:relative;float:center;">Send!</button>
</div>
</div>
</div>
</fieldset>
</form>
On submit it posts to the route #/submitcontact:
this.post('#/submitcontact', function(context) {
$.post("mail.php", this.params,
function(data) {
alert("Data Loaded: " + data);
});
});
Try passing each value to function post. Modify the code like this:
context = $('form').serialize();
$.post('#/submitcontact', function(context) {
$.post("mail.php", this.params,
function(data) {
alert("Data Loaded: " + data);
});
});
Maybe this could work.

Categories

Resources