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.
Related
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))
I would like to create contact us web page without refreshing the page when click send button. My code bellow, but there are some problems:
1- The page is refreshed after submitting the form.
2- The value of the Contact form inputs appear in the URL after submitting the form. check this image
3- The confirmation message appears for 0.25 seconds then disappear or does not appear.
4- The email is not received to my email address when I use Firefox browser.
Please help me to solve those problems.
HTML
<div class="col-sm-8 col-sm-offset-2" id="mail-status">
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-8 col-xs-12 col-sm-offset-2">
<div class="well">
<form class="form-horizontal">
<fieldset>
<legend class="legend-title">I'd <span class="heart"><i class="fa fa-heart"></i></span> to contact you!</legend>
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputName" name="name" placeholder="Name" required="required">
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-9">
<input type="email" class="form-control" id="inputEmail" name="email" placeholder="Email" required="required">
</div>
</div>
<div class="form-group">
<label for="inputSubject" class="col-sm-2 control-label">Subject</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputSubject" name="subject" placeholder="Subject" required="required">
</div>
</div>
<div class="form-group">
<label for="textAreaMessage" class="col-sm-2 control-label">Message</label>
<div class="col-sm-9">
<textarea class="form-control" rows="5" id="textAreaMessage" name="message" placeholder="Message" required="required" minlength=5 ></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-3 col-sm-offset-8">
<button type="submit" class="btn btn-primary right-button" id="send" onClick="sendContact()">Send</button>
</div>
</div>
</fieldset>
</form>
Javascript
function sendContact() {
jQuery.ajax({
url: "send_email.php",
data:'inputName='+$("#inputName").val()+'&inputEmail='+$("#inputEmail").val()+'&inputSubject='+$("#inputSubject").val()+'&textAreaMessage='+$(textAreaMessage).val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
php
<?php
$toEmail = "*****#***.com";
$mailHeaders = "From: " . $_POST["inputName"] . "<". $_POST["inputEmail"] .">\r\n";
if(mail($toEmail, $_POST["inputSubject"], $_POST["textAreaMessage"], $mailHeaders)) {
print "<div class='alert alert-success'> <button type='button' class='close' data-dismiss='alert'>×</button> Thank you for your email! I will be in touch.</div>";
} else {
print "<div class='alert alert-danger'> <button type='button' class='close' data-dismiss='alert'>×</button> We are sorry, but there is a problem. Please Make sure all fields are filled!</div>";
}
?>`
Get rid of the inline onclick() event in your HTML, and let your JavaScript handle the click:
$('#send').click(function(e){
e.preventDefault();
sendContact();
});
preventDefault() stops the click event from acting normally, so your form data is submitted without reloading the page.
I'm trying to get formdata to my php file. but i'm getting not any value on post. please advice me what i'm doing is right? i'm doing something wrong in post
// add item to additem
<script type="text/javascript">
$(document).ready(function(){
$("#additembutton").click(function(evt){
evt.preventDefault();
var formData = new FormData($("form #itemform")[0]);
alert(formData);
$.ajax({
url: 'additem.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
return false;
});
</script>
// form submit image
This is my additem.php file
<?php
include '../class/dbconfig.php';
$filename=$_POST['myfile']['name'];
echo $_POST['myfile'];
This is my html form
<form class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label for="select" class="col-md-3 control-label">Menu Type</label>
<div class="col-md-6">
<select class="form-control" id="menutype">
<option>Select Menu</option>
<option value="fastfood">FastFood</option>
<option value="other">Other</option>
</select>
</div>
</div>
<!--
<div class="form-group" id="otherdiv">
<label for="menuorder" class="col-md-3 control-label">Other Menu Type</label>
<div class="col-md-6">
<input type="number" class="form-control" id="othermenu" placeholder="Enter Order">
</div>
</div>
-->
<div class="form-group">
<label for="menuorder" class="col-md-3 control-label">Menu Order</label>
<div class="col-md-6">
<input type="number" class="form-control" id="menuorder" pattern="[0-9]+" placeholder="Enter Order">
</div>
</div>
<div class="form-group">
<label for="select" class="col-md-3 control-label">Menu Status</label>
<div class="col-md-6">
<select class="form-control" id="menustatus">
<option value="1">Active</option>
<option value="0">Deactive</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-3">
<button type="reset" class="btn btn-default">Cancel</button>
<button type="button" class="btn btn-primary" id="addmenubutton" >Submit</button>
</div>
</div>
</form>
You just need to send the form via post:
<form method="POST">
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
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.