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.
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'm currently developing a website for a gaming community but I've stumbled on some issues I can't fix. This is suppose to edit a user inserted in the database.
edituser.php
<form id="edituser" enctype="multipart/form-data">
<div class="col-sm-3">
<div class="form-group">
<img src="../../assets/images/users/<?=$row['users_image']; ?>.<?=$row['users_imagetype']; ?>" class="img-responsive img-circle">
</div>
<div class="form-group">
<input type="file" id="image">
</div>
</div>
<div class="col-sm-9">
<div id="usersidControl" class="form-group">
<label>User ID:</label>
<input id="usersid" class="form-control" value="<?=$row['usersid']; ?>" placeholder="<?=$row['usersid']; ?>" disabled>
</div>
<div id="nameControl" class="form-group">
<label>Name:</label>
<input id="name" class="form-control" value="<?=$row['name']; ?>" placeholder="<?=$row['name']; ?>">
</div>
<div id="usernameControl" class="form-group">
<label>Username:</label>
<input id="username" class="form-control" value="<?=$row['username']; ?>" placeholder="<?=$row['username']; ?>" disabled>
</div>
</div>
</form>
edituser.js
$(document).ready(function() {
$('form#edituser').submit(function(e) {
var edituser = {
'usersid' :$('input#usersid').val(),
'name' :$('input#name').val(),
'image' :$('input#image').attr('files'),
}
$.ajax({
type : 'POST',
url : 'processedituser.php',
data : edituser,
contentType : 'multipart/form-data',
enconde : true
})
.done(function(data) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
if (!data.success) {
if (data.errors.name) {
// empty name
$('#nameControl').addClass('has-error');
$('#nameControl').append('<div class="help-block">' + data.errors.name + '</div>');
}
if (data.errors.username) {
// empty username
$('#usernameControl').addClass('has-error');
$('#usernameControl').append('<div class="help-block">' + data.errors.username + '</div>');
}
} else if (data.success) {
if ($('#result').hasClass('alert-danger') || $('#result').hasClass('alert-warning') || $('#result').hasClass('alert-success') || $('#result').hasClass('alert-info') ||$('#result').hasClass('hidden')) {
$('#result').removeClass('alert-danger alert-info alert-success alert-warning hidden');
$('#result').addClass('alert-success fade in');
$('#result').html(data.message);
}
}
})
.fail(function(data) {
if ($('#result').hasClass('alert-danger') || $('#result').hasClass('alert-warning') || $('#result').hasClass('alert-success') || $('#result').hasClass('alert-info') ||$('#result').hasClass('hidden')) {
$('#result').removeClass('alert-danger alert-info alert-success alert-warning hidden');
$('#result').addClass('alert-danger fade in');
$('#result').html('An error has ocurred trying to edit this user, please try again in a few moments. If the problem persists, please contact the webmaster.');
}
});
e.preventDefault();
});
});
processedituser.php
include ("config.php");
global $conn;
$errors = array();
$data = array();
$editorid = $_COOKIE['backoffice_usersid'];
$editor = $_COOKIE['backoffice_username'];
$usersid = $_POST['usersid'];
$name = $_POST['name'];
$file = $_POST['image'];
if (empty($name)) {
$errors['name'] = "Please fill in the name.";
}
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="../../assets/images/users/";
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
$final_file = str_replace(' ','-',$new_file_name);
if (empty($image)) {
$errors['file'] = "Please choose an image to upload";
} else if (!move_uploaded_file($file_loc,$folder.$final_file)) {
$errors['file'] = "Couldn't upload the file, please try again later";
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
try {
// Update Users table
$sql_update = "UPDATE users SET .... ";
// Insert log
$sql_insert = "INSERT INTO logs (action, content, type, date, usersid) VALUES ('Edited', 'user $username by $editor', 'pencil-square-o', NOW(), '$editorid')";
$conn->exec($sql_insert);
$data['success'] = true;
$data['message'] = "You have successfully edited this user. You'll be redirected in 5 seconds.";
} catch(PDOException $e) {
$data['success'] = false;
$data['message'] = "Couldn't register you on our database!";
}
}
echo json_encode($data);
Ok, so this is my code, I've been working on this for like 2 months, I have a similar code, but it works with no problem whatsoever.
The real problem is that when I have no errors to trigger the !data.success, it simply gives me TypeError: data.errors is undefined, which I've checked over and over again, not knowing what can possibly be wrong.
The other problem is the file upload seems no to be working properly, it doesn't upload anything to the Db even though the code works outside the back office just like the rest of the code.
Can anyone please help me?
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.
}
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());
}
});
});
I'm working on converting a jQuery ajax request into plain JavaScript just so I know how to do it both ways. What I'm trying to do is pass a JSON object from my PHP script into my JavaScript file and display the values of the JSON object on the page.
I'm just beginning to dive into AJAX and I've gotten the jQuery version to work on my own easily enough, but I'm having difficult with the plain JavaScript version. For the plain JavaScript part, I'm following along with a JavaScript book that I have. That's why the code structure may seem different.
Also, I'm aware there are no real security implementations and that is fine. This is just for my own learning purposes.
Here is the HTML:
<body>
<h3>Grab the location of a person in the database below</h3>
<form action="ajax/name.php" method="POST" name="ajaxForm" id="ajaxForm">
<label for="name">Name: </label>
<input type="text" id="name" name="name">
<input type="submit" id="name-submit" name="name-submit" value="Grab">
</form>
<div id="results">
<label for="location">Location: </label>
<input type="text" name="name-data" id="name-data" disabled>
</div>
<div id="insert">
<h3>Insert a new person with a new location below</h3>
<form action="ajax/name.php" method="POST" name="insForm" id="insForm">
<label for="name">Name: </label>
<input type="text" name="ins-name" id="ins-name">
<label for="location">Location: </label>
<input type="text" name="ins-location" id="ins-location">
<input type="submit" id="ins-submit" name="ins-submit" value="Insert">
</form>
<div id="insresults_name"></div>
<div id="insresults_loc"></div>
</div>
<script src="js/ajax.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/global.js"></script>
</body>
Here is my jQuery code that works fine:
$('document').ready(function() {
var locForm = $('#ajaxForm');
var insForm = $('#insForm');
locForm.submit(function() {
$.ajax({
type: 'POST',
url: locForm.attr('action'),
data: locForm.serialize(),
success: function (response) {
$('#name-data').val(response);
}
});
return false;
});
insForm.submit(function() {
$.ajax({
type: 'POST',
url: insForm.attr('action'),
data: insForm.serialize(),
dataType: 'json',
success: function (response) {
$('#insresults_name').text('Name: ' + response[0]);
$('#insresults_loc').text('Location: ' + response[1]);
}
});
return false;
});
});
Here is my PHP Script:
<?php
if (isset($_POST['name'])) {
require '../db/connect.php';
$conn = new Con();
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare('SELECT * FROM names WHERE name=:name');
$stmt->bindParam(':name', $name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo (isset($result['location'])) ? $result['location'] : 'That name isn\'t listed';
}
if (isset($_POST['ins-name']) && isset($_POST['ins-location'])) {
require '../db/connect.php';
$conn = new Con();
$name = filter_input(INPUT_POST, 'ins-name', FILTER_SANITIZE_STRING);
$loc = filter_input(INPUT_POST, 'ins-location', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare('INSERT INTO names (name, location) VALUES (:name, :loc)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':loc', $loc);
try {
$stmt->execute();
$result = $stmt->rowCount();
if ($result) {
$stmt = $conn->prepare('SELECT * FROM names WHERE name=:name');
$stmt->bindParam(':name', $name);
$stmt->execute();
$res = $stmt->fetch(PDO::FETCH_ASSOC);
$val = array();
$val[0] = $res['name'];
$val[1] = $res['location'];
echo json_encode($val);
} else {
echo 'Fail';
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . '';
}
}
?>
And here is the plain JavaScript that I've come up with, but doesn't work:
function getData() {
'use strict';
var name = document.getElementById('ins-name').value();
var location = document.getElementById('ins-location').value();
var url = document.getElementById('ins-name').getAttribute('action');
if ((name.length > 0) && (location.length > 0)) {
var ajax = getXMLHttpRequestObject();
ajax.ononreadystatechange = function () {
if (ajax.readyState == 4) {
// Check the status code:
if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)) {
// if ajax.responseText isn't empty
if (ajax.responseText) {
var arr = Array();
arr = JSON.parse(responseText);
document.getElementById('insresults_name').innerHTML('Name: ' + arr[0]);
document.getElementById('insresults_loc').innerHTML('Location: ' + arr[1]);
} else {
alert('Something went wrong!');
}
} else {
alert('Bad Status Code!');
}
}
};
ajax.open('POST', '../ajax/name.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data = 'name=' + encodeURIComponent(name) + 'location=' + encodeURIComponent(location);
ajax.send(data);
return false;
} else {
alert('Please complete the form!');
}
}
function init() {
'use strict';
if (document && document.getElementById) {
var form = document.getElementById('insForm');
form.onsubmit = getData;
}
}
window.onload(init);