I try to use x-editable but i can't find a way to update my database with new data.
In my index.php i have :
superuser
and in main.js i have :
$('#username').editable({
type: 'text',
pk: 1,
url: 'post.php',
title: 'Enter username'
and in post.php :
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
and after :
$result = mysql_query('update users set '.mysql_escape_string($name).'="'.mysql_escape_string($value).'" where user_id = "'.mysql_escape_string($pk).'"');
When i try, nothing happen, no change in DB, no message, just nothing. If i change $value = $_POST['value']; and others with real values and i launch post.php directly, sql works.
JS
(function(){
$('a#editlang').editable({
url: 'post.php',
escape: false,
"mode": 'inline',
"rows": '5',
"inputclass": 'input-xxlarge',
validate: function(value) {
if($.trim(value) == '') {
return 'This field is required';
}
},
});
});
HTML
<a name="editlang" id="editlang" data-type="textarea" data-pk="1" title="Edit">superuser</a>
in php
$pk = $_POST['pk']; // register id
$value = $_POST['value']; // new name
query:
$result = mysql_query('update users set name = "'.mysql_escape_string($value).'" where user_id = "'.mysql_escape_string($pk).'"');
Related
I tried the pagination feature for searching data using Select2 4.x, but I haven't been able to achieve it. Does anyone know how to do it on codeigniter 4 by including the CSRF token.
If the user performs a search it will display 20 lines, and return to do so with a scroll of 20 lines.
Can anyone help for my problem.
my template HTML:
<div class="form-group">
<select id="selectData" class="form-control" style="width: 100%;"></select>
</div>
Script:
$(document).ready(function() {
var csrfName = $('.txt_csrfname').attr('name'); // CSRF Token name
var csrfHash = $('.txt_csrfname').val(); // CSRF hash
$('#selectData').select2({
placeholder: '-- Select --',
minimumInputLength: 3,
ajax: {
url: "<?= base_url('servis/getAjax'); ?>",
type: 'POST',
dataType: 'json',
delay: 250,
data: function(params) {
return {
[csrfName]: csrfHash, // CSRF Token
search: params.term
};
},
prosessResults: function(data) {
return {
results: data
};
},
cache: true
},
});
});
Controller:
$search = $this->request->getPost('search');
$result = new MerekModel();
$results = $result->getDataAjax($search);
$selectAjax['token'] = csrf_hash();
$selectAjax = array();
foreach ($results as $row) {
$selectAjax[] = array(
'id' => $row['id_merek'],
'text' => $row['merek'] . ' ' . $row['model'] . ' ' . $row['tipe'],
);
header('Content-Type: application/json');
echo json_encode($selectAjax);
}
Models:
function getDataAjax($search)
{
$data = $this->db->table('tb_merek_tipe')
->select('id_merek, merek, model, tipe')
->orlike('merek', $search)
->orlike('model', $search)
->orlike('tipe', $search)
->get()->getResultArray();
return $data;
}
I'm using $.ajax to insert data into database. But no data will be inserted and I don't receive any data in success function. Do I have to set more parameters into the success function?
That's what I currently have:
JS:
$.ajax({
url: '/pro.php',
data: {
'name':name,
'email':email,
'reply':reply
},
type: 'post',
success: function() {
}
});
PHP:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'redskydb';
$connection = mysqli_connect('localhost','yasi','ucsc','redskydb');
$name = $_POST['name'];
$email = $_POST['email'];
$reply = $_POST['reply'];
$query="INSERT INTO feedbacks (CusId,Reply,Name)VALUES('$email','$reply','$name')";
Check your ajax. Don't put the object keys in quotes and pass the success function the result parameter.
$.ajax({
url: './pro.php',
data: {
name: 'nameValue',
email: 'emailValue',
reply: 'replyValue',
},
type: 'POST',
success: function(result) {
console.log('this is result from call', result);
}
});
UPDATE
Please check your pro.php first it is not save an on the other hand, your Values(...) are set incorrectly. My code is just an example, how you could going through.
$mysqli = new mysqli("localhost", "root", "", "redskydb");
if($mysqli->connect_error) {
exit('Error connecting to database');
}
$stmt = $mysqli->prepare("INSERT INTO feedbacks (CusId, Reply, Name) VALUES (?, ?, ?)");
$stmt->bind_param($_POST['email'], $_POST['reply'], $_POST['name']);
$stmt->execute();
//here you could select with last_id and fetch the inserted row, but don't return before close()
$stmt->close();
For some reason when I do my AJAX request in my main.js file, I get an error:
Undefined index: id in sqlinfo.php on line 13
And I'm not sure why because I feel that I am filling out the request object correctly. What's also strange is that this works:
$requestType = filter_input(INPUT_POST, 'requestType', FILTER_SANITIZE_STRING);
So why doesn't $_POST['id'] work?
If anyone could tell me what error I'm making that would be great!
Note: I know albumId has a value because I already used console.log() to verify that it has a value.
Code
main.js
$(document).ready(function () {
$(".grid").on("click", ".edit", function (){
var albumId = $(this).siblings(".grid-info").attr("id");
var imageId = $(this).siblings("img").attr("id");
var request = (albumId == '') ? {requestType: 'Album', id: albumId} : {requestType: 'Image', id: imageId};
var getSQLInfo = $.ajax({
url: '../P3_M2/ajax/sqlinfo.php',
method: 'post',
data: request,
dataType: 'json',
error: function(error) {
console.log(error);
}
});
});
sqlinfo.php
<?php
require_once('../configsql.php');
$queryFor = array(
'Album' => 'SELECT * FROM Album WHERE id = ?',
'Image' => 'SELECT * FROM Image WHERE id = ?');
$requestType = filter_input(INPUT_POST, 'requestType', FILTER_SANITIZE_STRING);
if (empty($requestType)) {
echo 'Missing requestType.';
die();
}
$id = $mysqli->real_escape_string($_POST['id']); //getting undefined index id
?>
Thanks to #v Sugumar I realized I had the wrong boolean (==) when I assigned request. Changing it to != fixed it:
var request = (albumId != '') ? {requestType: 'Album', id: albumId} : {requestType: 'Image', id: imageId};
I am making a single registration form with all the data and input tags I need and pass that data to the next page via AJAX. But I do not get my image upload value to the next page. Please help me find a solution regarding ajaxfileupload.js and validation.js and tell me how to store image in a database using codeigniter.
<script src="<?php echo JS_PATH;?>jquery-validation.js"></script>
javascript:
$(document).ready(function() {
$("#registration_form").validate({
rules: {
name: {
required: true
},
surname: "required",
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
messages: {
name: {
required: "Please enter your name"
},
surname: "Please enter your surname",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
}
},
submitHandler: submitForm
});
function submitForm() {
var name = $('#name').val();
var surname = $('#surname').val();
var age = $('#age').val();
var dob = $('#datepicker').val();
var ph_no = $('#ph_no').val();
var gender = $('input[type="radio"]:checked').val();
var hobbies = new Array();
$('input[name="hobbies[]"]:checked').each(function() {
hobbies.push(this.value);
});
var city = $('#city').val();
var email = $('#email').val();
var pwd = $('#password').val();
var photo = $("#userfile").val();
$.ajax({
url: "<?php echo SITE_ROOT;?>Registration/insertdata",
type: "POST",
data: {
username: name,
user_surname: surname,
user_email: email,
password: pwd,
user_age: age,
user_dob: dob,
user_ph_no: ph_no,
user_gender: gender,
user_hobbies: hobbies,
user_city: city,
user_photo: photo
},
success: function(data) {
alert(data);
}
}
});
}
html:
<form method="post" enctype = "multipart/form-data" >
<label> File Input: </label>
<input type="file" name="userfile" id="userfile">
<input type="submit" name="submit" value="Submit" />
</form>
php controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Registration extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('menupages/registration_model');
}
public function index() {
$this->first();
}
function first() {
$data['title'] = "Registration Page";
$this->load->view('menupages/registration', $data);
}
function insertdata() {
$file = $_POST['user_photo'];
print_r($file);
exit();
$config['upload_path'] = '/var/www/html/upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['file_name'] = $file;
$this->load->library('upload'); //initialize
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
print_r($error);
exit();
} else {
$data = array('upload_data' => $this->upload->data());
print_r($data);
exit();
}
}
}
First of all , there are many things that are not okay with your current code inside php codeginiter 's controller, let's first see a difference between $_POST vs $_FILES
$_POST contains all the data from forms (except files)
$_FILES contains all files sent to server via forms (only from <input type="file" />)
What you are doing is , you are using $_POST['user_photo'] to fetch the file details , which is not okay to fetch the file information for uploading it. And also another thing is :
$this->upload->do_upload('userfile');
You are wrong here. the parameter userfile does not even exist in your http request. While sending the data to the server , you have replaced the userfile with user_photo , so what you have to here is also you have to change these two things
$_POST['user_photo'];
$this->upload->do_upload('userfile');
to
$_FILES['user_photo'];
$this->upload->do_upload('user_photo');
change your :
$('#userfile').val();
to
$("#userfile").prop("files")[0];
and add these parameters into javascript parameters along with url , data and etc..
contentType: false,
processData: false,
cache: false,
change your submitForm function to this:
function submitForm() {
var name = $('#name').val();
var surname = $('#surname').val();
var age = $('#age').val();
var dob = $('#datepicker').val();
var ph_no = $('#ph_no').val();
var gender = $('input[type="radio"]:checked').val();
var hobbies = new Array();
$('input[name="hobbies[]"]:checked').each(function() {
hobbies.push(this.value);
});
var city = $('#city').val();
var email = $('#email').val();
var pwd = $('#password').val();
var photo = $("#userfile").prop("files")[0];
var form_data = new FormData();
form_data.append("user_photo", photo);
form_data.append("username",name);
form_data.append("user_surname",surname);
form_data.append("password",pwd);
form_data.append("user_age",age);
form_data.append("user_dob",dob);
form_data.append("user_ph_no",ph_no);
form_data.append("user_gender",gender);
form_data.append("user_hobbies",hobbies);
form_data.append("user_city",city);
$.ajax({
url: "<?php echo SITE_ROOT;?>Registration/insertdata",
type: "POST",
data: form_data,
success: function(data) {
alert(data);
}
}
});
}
Make use of FormData() on javascript.
data = new FormData();
data.append('name', $('#name').val());
data.append('surname', $('#surname').val());
data.append('age', $('#age').val());
data.append('dob', $('#datepicker').val());
data.append('ph_no', $('#ph_no').val());
data.append('gender', $('input[type="radio"]:checked').val());
//for Photo
data.append('photo', $('#userfile')[0].files[0]);
//AJAX
$.ajax({
url: "<?php echo SITE_ROOT;?>Registration/insertdata",
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log(data)
}
});
PHP CODE:
To test if you successfully passed file and post data on php:
print_r($_FILES);
print_r($_POST);
You can submit the form and send it by form.serialize in JQuery. It will send data with picture by Ajax.
I have this working to a point, but would like, after true is returned, to set localstorage to value of the id passed in mySQL query. I'm unsure how to pass this, as my php currently echos only true or false.
<script type="text/javascript">
$(document).ready(function() {
$('#loginButton').click(function(){
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "login.php",
cache: false,
data: { username: username, password: password },
success: function(res) {
switch(res) {
case ('true'):
alert('true');
break;
case ('false'):
alert('false');
break;
}
}
});
return false;
});
});
</script>
<?php
$username = $_POST['username'];
$password = md5($_POST['password']);
if(!empty($username) && !empty($password)) {
$stmt = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindValue('username', $username);
$stmt->bindValue('password', $password);
$stmt->execute();
if($stmt->rowCount() == 0) {
echo 'false';
} else {
echo 'true';
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user_id = $row['user_id'];
}
}
}
$conn = null;
?>
If you want to respond with several values when using AJAX you may use JSON.
In php code it should be like this (paste it after $stmt->execute(); line instead of if-else construction):
if($stmt->rowCount() == 0) {
echo json_encode(array('success' => false));
} else {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$user_id = $row['user_id'];
echo json_encode(array(
'success' => true,
'user_id' => $user_id
));
}
Then in javascript you should specify that you expect JSON as a response. This is a code:
$.ajax({
type: "POST",
url: "login.php",
cache: false,
dataType: 'json', //this is where we specify JSON response
data: { username: username, password: password },
success: function(res) {
if (res.success) {
localStorage.setItem('user_id', res.user_id); //set user id to local storage
alert(res.user_id);
} else {
alert('false');
}
},
error: function() {
//this will trigger in case the server send invalid JSON (or other types of errors)
alert('false');
}
});
I would also recommend to use GET method instead of POST in this case. POST is usually used when you need to change something of a server (database, session, file system, etc.), but when you want just get some data, it's better to use GET. However no one restricts you to do as you want, but I think it better to follow standard.
Good luck!