Im trying to send a data containing username, password etc from a HTML form-> ajax -> instance -> oop class file.
But im not sure i have the right approach...
It starts with the form on index.php
<!-- Formular for signing up -->
<form method="post">
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" name="newusername">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" name="newpassword">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" name="newclub">
</div>
<input type="button" id="btn-reg" class="btn btn-success" value="Sign up!">
</form>
And then it goes trough my script file and ajax
$(document).ready(function () {
console.log('Script loaded...');
$("#btn-reg").on("click", reg);
// Function for registrate of new users
function reg(newusername, newpassword, newclub) {
$.post('classCalling.php', {
newusername: 'newusername',
newpassword: 'newpassword',
newclub: 'newclub'
});
};
});
And then my data is going to a page, classCalling.php where i instance my class
?php
include("class/userClass.php");
include("class/pagesClass.php");
// Creating instance of the class userClass.php
$user = new User();
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newname = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user->newUsers($newusername, $hashpassword, $newname);
?>
And finaly my OOP Class, but im not getting this far
public function newUsers($newusername, $newpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTOusers(username,password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $newpassword, $newclub);
if($stmt->execute()) {
echo "<h3 class='usercreated'>Användare skapad</h3>";
} else {
echo "<h3 class='usercreated'> Gick ej att skapa användare</h3>";
}
}
Im getting these errors Notice: Undefined index: newusername in /Applications/MAMP/htdocs/web 2.0/projektet/classCalling.php on line 13
I think the error is because ur not passing any arguments to reg.
Try passing the form values to reg function it ll be fine
problem with your code is that you are not fetching value from form..
You don't need to put the code in form tag.
Use this form and Script, hope it may help.....
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" name="newusername" id="username">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" name="newpassword" id="password">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" name="newclub" id="club">
</div>
and script:
$(document).ready(function () {
console.log('Script loaded...');
$("#btn-reg").on("click", reg);
var newusername=$("#newusername").val();
var newpassword=$("#newpassword").val();
var newclub=$("#club").val();
function reg() {
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
});
};
});
Try out this
$(document).ready(function () {
console.log('Script loaded...');
$("#btn-reg").click(function(){
var newusername = $("#username").val();
var newpassword = $("#newpassword").val();
var newclub = $("#newclub").val();
$.ajax({
method: "POST",
url: "classCalling.php",
data: { newusername: newusername,newpassword: newpassword,newclub: newclub },
success:function(data){
alert(data);
}
});
});
});
And adjust your newUsers() method into
public function newUsers($newusername, $newpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username,password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $newpassword, $newclub);
if($stmt->execute()) {
echo "<h3 class='usercreated'>Användare skapad</h3>";
} else {
echo "<h3 class='usercreated'> Gick ej att skapa användare</h3>";
}
}
Try this function:
function reg() {
var newusername=$(this).val();
var newpassword=$(this).val();
var newclub=$(this).val();
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},function(data){
console.log(data);
});
}
To avoid error in your classCalling.php file always check if the POST value you are trying to get is set or not.
check below code
<?php
include("class/userClass.php");
include("class/pagesClass.php");
// Creating instance of the class userClass.php
$user = new User();
if(isset($_POST['username']) && isset($_POST['password']) && isset($_POST['newclub'])){
$username = $_POST['username'];
$password = $_POST['password'];
$newclub = $_POST['newclub'];
$hashpassword = sha1($newpassword);
$user->newUsers($newusername, $hashpassword, $newname);
}else{
// handle your request when POST parameters are missing.
}
Related
i'm triying to check if some user is already registered in my database so i'll be able to submit a form.
The problem seems to be that de ajax call is not made, i've tried to check other code's and debug but the problem doesn't looks like i had found.
Any help is good.
Thank you!
HTML Code:
<form method="POST" action="#" onsubmit="return (Inscrito() && Rut());" name=form1>
<div class="row">
<div class="col">
<label class="label">Rut</label>
<input type="text" name="rut" class="input--style-4" id="rut" required >
</div>
<div class="col">
</div>
</div>
<div class="p-t-15">
<button class="btn btn--radius-2 btn--blue" id="submit_inscription"
type="submit">Inscribirse</button>
</div>
</form>
JS Code.
function Inscrito(){
var rut = document.getElementById("rut").value;
if(rut != ''){
$.ajax({
type: 'POST',
url : '../controller/validate_inscripcion.php',
data: {rut : rut},
success: function(data){
if(data == 'exists')
//username exists
alert('Este rut ya se encuentra registrado!');
return false;
},
error: function(request , status , error){
alert(request.resposeText);
return true;
}
});
}else{
alert('Rut incompleto');
return false;
}
};
PHP Code (controller_inscripcion.php)
<?php
require ('../model/modelo_inscripcion.php');
$modelo =new modeloInscripcion();
if(isset($_POST['rut'])){
var $x = $modelo->validarInscrito($_POST['rut']);
$db->desconectarBD();
if($x==true){
echo 'exists';
}else{
echo '';
}
exit;
}
PHP Code (model_inscripcion)
<?php
require ('../model/database.php');
class modeloInscripcion{
public $db;
function __construct(){
$this -> db = new DataBase();
}
public function validarInscrito($rut){
$query = 'SELECT * FROM person WHERE rut = "'.$rut.'"';
$link= $this -> db->getConexion();
$result = mysqli_query($link,$query);
if(mysqli_num_rows($result)>0){
return false;
}
return true;
}
}
I have a messaging system installed on my site. For each message that a user receives I want to have a reply form, that knows to reply to the person who sent the original message.
I can get the forms to appear and messages to send, but the replies are going to the user who sent the last message received instead of the user who sent the posted message.
HTML and Javascript:
<!–– INBOX START ––>
<div id="navitem1" onclick="navitem1(event)" class="navitem1"><i class="fa fa-envelope fa-lg" id="navicon"></i><div class="redball"><div class="message_count"></div></div><p class="text">Inbox</p>
</div>
<div id="navitem1dropdown" class="navitem1content">
<h3>Inbox</h3>
<div class="sectionheader2"></div>
<div class="inboxscroll">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.message_count').html('0');
function load_unseen_messages(viewmsg = '')
{
$.ajax({
url:"inbox.php",
method:"POST",
data:{viewmsg:viewmsg},
dataType:"json",
success:function(data)
{
$('.inboxscroll').html(data.messagehtml);
if(data.message_count > 0)
{
$('.message_count').html(data.message_count);
}
}
});
}
load_unseen_messages();
$(document).on('click', '.navitem1', function(){
$('.message_count').html('0');
load_unseen_messages('yes');
});
setInterval(function(){
load_unseen_messages();;
}, 5000);
});
</script>
<script>
$('#inboxForm').submit(function(){$('input[type=submit]', this).attr('disabled','disabled');});
function replyPM(){
var pmTextArea = $("#pmTextArea");
var sendName = $("#pm_send_name");
var sendID = $("#pm_send_id");
var receiveName = $("#pm_receive_name");
var receiveID = $("#pm_receive_id");
var timesent = $("#pm_timesent");
var url = "messages.php";
$.post(url,{ message: pmTextArea.val(), sendername: sendName.val(), senderid: sendID.val(), recname: receiveName.val(), recID: receiveID.val(), time: timesent.val() }, function(data){
$("#interaction").html('Message sent successfully.').show().fadeOut(5000);
document.inboxForm.pmTextArea.value='';
});
}
</script>
PHP:
<?php
session_start();
require_once 'class.channel.php';
$user_inbox = new USER();
$user_id = $_SESSION['userID'];
$user_name = $_SESSION['userName'];
if(isset($_POST["viewmsg"]))
{
if($_POST["viewmsg"] != '')
{
$stmt = $user_inbox->runQuery("UPDATE inbox SET status = 1 WHERE receive_id = ?");
$stmt->bindValue(1,$user_id);
$stmt->execute();
}
$stmt = $user_inbox->runQuery("SELECT * FROM inbox WHERE receive_id= ? ORDER BY id DESC LIMIT 50");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
$messagehtml = '';
if(count($messages) > 0)
{
foreach($messages as $message)
{
$messagehtml .= '
<div class="inboxsection"><h6>From: '.$message["send_name"].'</h6><h6>'.$message["timesent"].'</h6><h6>Message: </h6><img src="images/preview2.jpg" height="100%" width="100%" class="inboxvid">
<h7>'.$message["comment"].'</h7>
<div style="clear:both;"><br><button id="reply" class="button" onclick="inboxmessage(event)">Reply</button> <button id="archive" class="button">Archive</button> <button id="delete" class="button">Delete</button></div>
</div>
<div id="inboxmessage" class="messagearea">
<form action="javascript:replyPM();" name="inboxForm" id="inboxForm" method="post">
<input name="pm_send_id" id="pm_send_id" type="hidden" value="'.$user_id.'" />
<input name="pm_send_name" id="pm_send_name" type="hidden" value="'.$user_name.'" />
<input name="pm_receive_id" id="pm_receive_id" type="hidden" value="'.$message["send_id"].'" />
<input name="pm_receive_name" id="pm_receive_name" type="hidden" value="'.$message["send_name"].'" />
<input name="pm_timesent" id="pm_timesent" type="hidden" value="" />
<div id="interaction"></div>
<br>
<p style="color:#fff;">Message:</p>
<textarea name="pmTextArea" id="pmTextArea"></textarea>
<p style="color:#fff;">Attach A Video:</p>
<input name="pmSubmit" type="submit" value="Submit" />
</form>
</div>
<div class="sectionheader3"></div>
';
}
}
else
{
$messagehtml .= '<div><h2 style="color: #4b8ed3; padding: 10px;">No Messages Found<h2></div>';
}
$count = $user_inbox->runQuery("SELECT * FROM inbox WHERE receive_id= ? AND status= 0");
$count->bindValue(1,$user_id);
$count->execute();
$countresult = $count->fetchAll(PDO::FETCH_NUM);
if(count($countresult) > 0){
$message_count = count($countresult);
}
else{
$message_count = 0;
}
header('Content-type: application/json');
$inbox_array = array('messagehtml'=>$messagehtml,'message_count'=>$message_count);
echo json_encode($inbox_array);
}
?>
Upon creating/inserting your replies, have a reference field like parentId that would reference it to the original message being replied to.
And with that you can get the information of the user if you have like a reference column to your user table. ex createdBy
I can update this answer, and give you more specifics you if give a column list of your inbox table.
Get the Primary ID of the POSTED message
base on your table design I would do it like this:
$postedMessageId = $_GET['id'];// you can pass the id however you want.this is just a sample
INSERT INTO inbox ("parentId","comment",....) VALUES ( <postedMessageId>, <comment>,.... )
With that you can now reference all the replies, using the parentId column, by using JOIN.
Firstly I'm not sure if missing anything in my code other than the problems in my functions, but i digress. I'm new to jquery so I'm having difficulty setting up a registration page. In the form I'm trying to check for valid entries as well as checking the queries in the back-end using php. I set up 2 files one is an html file and the other is a php file. Using ajax the function was supposed to call the php file, but I cant seem to get it working and I'm wondering if I should just put all the code in the same file. Furthermore I'm unsure if the functions are even working at all because its not returning any status. I will post the code for the two files below. Any hints or tips would be greatly appreciated.
The HTML file without css
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Register</title>
<link rel="stylesheet" href="assets/css/reset.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<script src="assets/js/jquery.min.js"> </script>
<script src="assets/js/main.js"> </script>
<div class="pen-title">
<h1>Registration Form</h1></div>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass").value;
var p2 = _("pass2").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else
{
_("submit").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "registration.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("submit").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1);
}
}
</script>
<!-- Form Module-->
<div class="module form-module">
<div class="form">
</div>
<div class="form">
<h2>Create an account</h2>
<form method="post" name="signupform" id="signupform" onsubmit="return false;">
<input type="text" id="username" onfocus="emptyElement('status')" placeholder="Username" maxlength="50"/>
<input type="password" id="pass" onfocus="emptyElement('status')" placeholder="Password" maxlength="10"/>
<input type="password" id="pass2" onfocus="emptyElement('status')" placeholder="Confirm Password" maxlength="10"/>
<input type="email" id="email" onfocus="emptyElement('status')" placeholder="Email Address" maxlength="50"/>
<!-- <input type="tel" name="telephone" placeholder="Phone Number" maxlength="10"/> -->
<button type="submit" onclick="signup()" name="submit">Register</button>
</form>
</div>
</div>
</body>
</html>
The PHP file
<?php
// Connects to your Database
$host="myhost"; // Host name
$username="myuser"; // Mysql username
$password="mypass"; // Mysql password
$db_name="mydbname"; // Database name
$con = mysqli_connect("$host", "$username", "$password", "$db_name") or die(mysql_error());
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($con, $_POST['e']);
$p = $_POST['p'];
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($con, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($con, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
//$cryptpass = crypt($p);
//include_once ("php_includes/randStrGen.php");
//$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p' ,'$ip',now(),now(),now())";
$query = mysqli_query($con, $sql);
$uid = mysqli_insert_id($con);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
//if (!file_exists("user/$u")) {
// mkdir("user/$u", 0755);
//}
}
}
?>
Your javascript code has many errors. Like you used _ instead of $ and your element Ids is wrong. They are not include #. So I have organized your code with your logic. Bu it is not a real question or it is not a true way to learn.
HTML
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Register</title>
<link rel="stylesheet" href="assets/css/reset.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!--script src="assets/js/main.js"> </script-->
<div class="pen-title">
<h1>Registration Form</h1></div>
<script>
function emptyElement(x){
$('#' + x).text("");
}
function signup(){
var un = $("#username").val();
var em = $("#email").val();
var p1 = $("#pass").val();
var p2 = $("#pass2").val();
if(un == "" || em == "" || p1 == "" || p2 == "")
{
$('#status').text("Fill out all of the form data");
}
else if(p1 != p2)
{
$('#status').text("Your password fields do not match");
}
else
{
$.ajax({
type: "POST",
url: "registration.php",
dataType: "json",
data : { u: un, p:p1, e:em },
cache: !1,
beforeSend: function(){
$("#submit").hide();
$('#status').text('please wait ...');
},
complete: function(){
$("#submit").show();
},
success: function(answer){
if(answer.result == "successful")
{
$("#status").html(answer.text);
}
else
{
$("#status").html(answer.result);
}
},
error: function(answer){
$("#status").text(answer);
}
});
}
/*
var ajax = ajaxObj("POST", "registration.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
$("submit").style.display = "block";
} else {
window.scrollTo(0,0);
$("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1);
*/
}
</script>
<!-- Form Module-->
<div class="module form-module">
<div class="form">
</div>
<div class="form">
<h2>Create an account</h2>
<form method="post" name="signupform" id="signupform" onsubmit="return false;">
<input type="text" id="username" onfocus="emptyElement('status')" placeholder="Username" maxlength="50"/>
<input type="password" id="pass" onfocus="emptyElement('status')" placeholder="Password" maxlength="10"/>
<input type="password" id="pass2" onfocus="emptyElement('status')" placeholder="Confirm Password" maxlength="10"/>
<input type="email" id="email" onfocus="emptyElement('status')" placeholder="Email Address" maxlength="50"/>
<!-- <input type="tel" name="telephone" placeholder="Phone Number" maxlength="10"/> -->
<button type="submit" onclick="signup()" name="submit">Register</button>
<div id="status"></div>
</form>
</div>
</div>
</body>
</html>
registration.php
<?php
$answer = new stdClass;
if(isset($_POST))
{
$answer->result = "successful";
$answer->text = "";
foreach($_POST as $key => $value)
{
$answer->text .= $key . ": " . $value . "<br />";
}
}
else
{
$answer->result = "Error";
$answer->text = "Error Message";
}
echo json_encode($answer);
?>
This registration.php is an example for you. You can rewrite with your logic.
You should use $answer object for response.
$answer->result is status of repsonse
$answer->text is response
I hope it will help you.
I have this form where i can insert data, on code igniter. it has validations, all i want to do is to make it ajax. how can I put ajax on it?
my codes,
controller
// CREATE /////////////////////////////////////////////////////////
public function create(){
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
if($this->form_validation->run($this) == FALSE){
$this->add_view();
}else{
if($query = $this->Provinces_Model->insert()){
redirect('Provinces/index');
}else{
$this->add_view();
}
}
}
/////////// Checking duplicates
public function if_exist(){
$available = $this->Provinces_Model->check_if_exist(); //change
if($available){
return TRUE;
}else{
$this->form_validation->set_message('if_exist','{field} already exist!');
return FALSE;
}
}
models
/// call back
public function check_if_exist(){
$sql = "SELECT * FROM $this->table WHERE PROVINCE = ?";
$data = array('PROVINCE' => $this->input->post('PROVINCE'));
$query = $this->db->query($sql, $data);
if($query->num_rows() == 0){
return TRUE;
}else{
return FALSE;
}
}
///// CREATE /////////////////////////////////////////////////////////
public function insert(){
$input = array(
'PROVINCE' => $this->input->post('PROVINCE')
);
$insert = $this->db->insert($this->table,$input);
return $insert;
}
and finally the view
<div class="box-body">
<div class="form-group">
<label for="PROVINCE" class="col-sm-2 control-label col-sm-offset-2">Province Name:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="PROVINCE" name="PROVINCE" value = "<?= set_value("PROVINCE"); ?>">
</div>
</div>
<div class="form-group has-error col-sm-offset-7">
<label class="control-label" for="error"><?php echo form_error("PROVINCE"); ?></label>
</div>
</div>
notice that I have the error reporting so and value = "<?= set_value("PROVINCE"); ?>" for retaining the value i inserted if its values did not pass the validation.. now I want to make it ajax as a practice because the next part that I am going to do is after I submitted a form, it will go to another form.
Edit your code like below:
Controller:
public function create(){
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
if($this->form_validation->run() == FALSE){
echo 'ERR';
}else{
if($query = $this->Provinces_Model->insert()){
redirect('Provinces/index');
}else{
$this->add_view();
}
}
}
And the view's Javascript part:
<script type="text/javascript" >
$('#send').click(function(){ // you should add an id called "send" to your submit button
var province = $('#province').val();
$.ajax({
type:'POST',
url:'yourposturl',
data: province,
success:function(response){
if (response = 'ERR') {
$("#response").html('Some error text');
}
else {
$("#response").html('Some success text');
}
}
});
});
</script>
Also please change <label class="control-label" for="error"> part to <label class="control-label" id="response" for="error"> if you want to use this method.
I have a modal that submit some information and an image through form to database. I am working with php and javascript...well i am not so good with js so i need some help.
Work i have done so far is that i can insert data from form to db without no errors but i don't know how to start and what to do with image upload. I am working now on localhost.
I want to upload image to local folder and to automatically rename it with title that someone entered through form. So the name of image saves into table and the image in folder.
I will past the code here so if anyone can help me with code i will appreciate it.
ajax:
$(document).ready(function(){
$('form.insert-movie').on('submit', function(e) {
e.preventDefault();
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: 'POST',
data: data,
success: function (msg) {
alert("YOUR SUCCESS MESSAGE HERE");
},
error: function (msg) {
alert("Error " + msg.d.toString());
}
});
return false;
});
});
queries:
<?php
include 'config.php';
$pdo = connect();
if(isset($_POST['InputTitle'], $_POST['InputYear'], $_POST['InputDuration'], $_POST['InputDescription'], $_POST['InputGender'])) {
$InputTitle = $_POST['InputTitle'];
$InputYear = $_POST['InputYear'];
$InputDuration = $_POST['InputDuration'];
$InputDescription = $_POST['InputDescription'];
$InputGender = $_POST['InputGender'];
$InputImage = $_POST['InputImage'];
$sql = $pdo->prepare("INSERT INTO filmovi(naslov,godina,trajanje,opis,id_zanr,slika)
VALUES(:field1,:field2,:field3,:field4,:field5,:field6)");
$sql->execute(array(':field1' => $InputTitle,
':field2' => $InputYear,
':field3' => $InputDuration,
':field4' => $InputDescription,
':field5' => $InputGender,
':field6' => $InputImage));
$affected_rows = $sql->rowCount();
}
modal:
<form action="inc/queries.php" method="post" class="insert-movie" enctype="multipart/form-data">
<div class="form-group"> <!-- TITLE -->
<label for="title">Title</label>
<input type="text" class="form-control" name="InputTitle" id="InputTitle" placeholder="Enter title" required>
</div>
<div class="form-group"> <!-- YEAR -->
<label for="year">Year</label>
<input type="date" class="form-control" name="InputYear" id="InputYear" placeholder="Year" required>
</div>
<div class="form-group"> <!-- DURATION -->
<label for="year">Duration</label>
<input type="time" class="form-control" name="InputDuration" id="InputDuration" placeholder="Duration" required>
</div>
<div class="form-group"> <!-- GENDER -->
<label for="year">Gender</label></br>
<select name="InputGender">
<option>select a genre</option>
<?php
$pdo = connect();
// display the list of all members in table view
$sql = "SELECT * FROM zanr";
$query = $pdo->prepare($sql);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
?>
echo'
<option name="InputGender" value="<?php echo $rs['id'] ?>"><?php echo $rs['naziv'] ?> </option>'
<?php } ?>
echo'
</select>
</div>
<div class="form-group"> <!-- DESCRIPTION -->
<label for="year">Description</label>
<textarea class="form-control" name="InputDescription" placeholder="Description" rows="3" required></textarea>
</div>
<div class="form-group"> <!-- IMAGE -->
<label for="image">Image upload</label>
<input type="file" name="InputImage" id="InputImage">
<p class="help-block">Select image of movie.</p>
</div>
Close
First, you must handle the file upload. Examples here: http://php.net/manual/en/features.file-upload.post-method.php Second you need to figure out what you want to store in your Database.
<?php
include 'config.php';
$pdo = connect();
if(isset($_POST['InputTitle'], $_POST['InputYear'], $_POST['InputDuration'], $_POST['InputDescription'], $_POST['InputGender'])) {
$InputTitle = $_POST['InputTitle'];
$InputYear = $_POST['InputYear'];
$InputDuration = $_POST['InputDuration'];
$InputDescription = $_POST['InputDescription'];
$InputGender = $_POST['InputGender'];
$uploaddir = '/var/www/uploads/'; // Change this to be a path on your server
$uploadfile = $uploaddir . basename($_FILES['InputImage']['name']);
if (move_uploaded_file($_FILES['InputImage']['tmp_name'], $uploadfile)) {
$InputImageStorePath = $uploadfile;
$InputImage = $_FILES['InputImage']['name'];
} else {
$InputImage = "";
}
$sql = $pdo->prepare("INSERT INTO filmovi(naslov,godina,trajanje,opis,id_zanr,slika)
VALUES(:field1,:field2,:field3,:field4,:field5,:field6)");
$sql->execute(array(':field1' => $InputTitle,
':field2' => $InputYear,
':field3' => $InputDuration,
':field4' => $InputDescription,
':field5' => $InputGender,
':field6' => $InputImage));
$affected_rows = $sql->rowCount();
}
?>
I would advise using FormData for your AJAX:
$('form.insert-movie').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($('form.insert-movie')),
url = $(this).attr('action'),
method = $(this).attr('method');
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function (msg) {
alert("YOUR SUCCESS MESSAGE HERE");
// Close Modal here with .hide() ?
},
error: function (msg) {
alert("Error " + msg.d.toString());
}
});
});