I want to do it so when a user clicks a checkbox it sets the tinyint value that's set in the database from 0 to 1 and vice-versa. My ajax.js:
function emailNextWithAddress(chk, address) {
var nextEmail, inside_where;
if (chk.checked === true) {
$.ajax({
url: "marca_enviado.php",
data: address,
type: "get",
success: function () {
nextEmail = document.createElement('input');
nextEmail.id = address;
nextEmail.value = address;
nextEmail.type = 'text';
nextEmail.name = 'email[]';
nextEmail.className = 'insemail';
nextEmail.style.display = 'inline-block';
inside_where = document.getElementById('addEmail');
inside_where.appendChild(nextEmail);
},
error: function () {
console.log("Erro!");
}
});
} else {
$.ajax({
url: "desmarca_enviado.php",
data: address,
type: "get",
success: function () {
inside_where = document.getElementById(address);
inside_where.parentNode.removeChild(inside_where);
},
error: function () {
console.log("Erro!");
}
});
}
return false;
}
And the part that I'm trying to update is(dbh.php is the connection to the database):
<?php
include_once 'dbh.php';
$id = $_GET['address'];
$updateEnviado = "UPDATE escolas SET Enviado = '$id'";
$result = mysqli_query($conn , $updateEnviado);
?>
In my index.php the part of the code that's being outputted is:
$execItems = $conn->query("SELECT Nome,EmailGeral,Enviado FROM escolas");
while($infoItems = $execItems->fetch_array()){
echo "
<tr style=\"border: 1px solid black;\">
<td>".$infoItems['Nome']."</td>
<td>".$infoItems['EmailGeral']."</td>
<td><input type=\"checkbox\" ".($infoItems['Enviado']?' checked':' ')." onclick=\"emailNextWithAddress(this, '".$infoItems['EmailGeral']."');\"/></td>
</tr>
";
}
?>
Note that I'm only interested in updating the checkbox.
Related
I want to show my data using the Next, Previous, First and Last buttons.
When I click on Next and Previous button 30 or more times, my browser will hang and ajax will not respond.
Please see the below code:
Main page script
<button id="lastbutton" onclick=" getlastinformation();">Last</button>
<button id="previousbutton">Previous</button>
<button id="nextbutton" onclick="getnextinformation();">Next</button>
<button id="firstbutton" onclick="getfirstinformation();">First</button>
<input type="hidden" id="change_id" name="change_id">
<input type="text" class="form-control" id="typedescription" readonly>
<input type="text" class="form-control" id="cityname" readonly>
function getfirstinformation()
{
document.getElementById('change_id').value = first_element;
put_data(first_element);
}
function getnextinformation()
{
var next_element = parseInt(document.getElementById('change_id').value);
if(next_element!=last_element)
next_element++;
document.getElementById('change_id').value = next_element;
put_data(next_element);
}
function getpreinformation()
{
var pre_element = parseInt(document.getElementById('change_id').value);
if(pre_element!=first_element)
pre_element--;
document.getElementById('change_id').value = pre_element;
put_data(pre_element);
}
function getlastinformation()
{
var last = localStorage.getItem("val");
if(last==null)
last = last_element;
else
{
last = localStorage.getItem("val");
localStorage.clear();
}
document.getElementById('change_id').value = last;
put_data(last);
}
function put_data(val)
{
// Add this line for next previous from Search Button
var id = array_of_records[val]['id'];
getalldata(id);
}
function getalldata(val)
{
$.ajax({
type: "POST",
url: "get_account.php",
data:'id1='+val,
success: function(data)
{
var supplier_array = new Array();
supplier_array = data.split("|");
$(".get-code").val(supplier_array[0]);
$("#typedescription").val(supplier_array[23]);
$("#cityname").val(supplier_array[24]);
}
});
}
Ajax requested URL file code
get_account.php
$customer_details = "";
if(!empty($_POST["id1"]))
{
$query ="SELECT * FROM `ledger WHERE id = '" . $_POST["id1"] . "' ORDER BY id DESC";
$results = mysqli_query($connection, $query);
while($state=mysqli_fetch_assoc($results))
{
$customer_details = $state["id"]."|".$state["type"];
$query2 ="SELECT description FROM type WHERE type = '" . $state["type"]. "' ";
$results2 = mysqli_query($connection, $query2);
while($state2=mysqli_fetch_assoc($results2))
{
$customer_details = $customer_details."|".$state2["description"];
}
$query3 ="SELECT cityname FROM citymast WHERE citycode = '".$state["citycode"]."' ";
$results3 = mysqli_query($connection, $query3);
while($state3=mysqli_fetch_assoc($results3))
{
$customer_details = $customer_details."|".$state3["cityname"];
}
}
}
echo $customer_details;
Abort code in my ajax request function
var currentRequest = null;
function getalldata(val) {
currentRequest = $.ajax({
type: "POST",
data:'id1='+val,
url: "master/get_account.php",
beforeSend : function(){ if(currentRequest != null)
{ currentRequest.abort(); } },
success: function(data) {
var supplier_array = new Array();
supplier_array = data.split("|");
$("#typedescription").val(supplier_array[23]);
$("#cityname").val(supplier_array[24]); } }); }
How can I fix the above code such that it fixes the hanging of the browser when sending button clicks 30 or more times?
I have a page with ajax pagination on it, I am currently able to check if the session exists and process accordingly. However, I cannot seem to remove the menu or reload the page properly if the session has expired. Only the menu remains and the login page shows in the small area where the table was.
Controller code
public function index()
{
$conditions = array();
$data = array();
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search(array('limit'=>$this->get_per_page()));
$data['user'] = $this->AccountModel->get_person($this->get_person_id());
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('layout/admins/common/header');
$this->load->view('layout/admins/common/navigation');
$this->load->view('layout/admins/common/title');
$this->load->view('layout/admins/common/errors');
$this->load->view('layout/admins/common/search');
$this->load->view('admins/documents/index',$data);
$this->load->view('layout/admins/common/footer');
}
public function search(){
if($this->input->is_ajax_request()){
if(!$this->logged_in()){
$this->index();
}else{
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('admins/documents/ajax_pagination', $data, false);
}
}
}
My JS Code that is placed in the view
<script>
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (html) {
$('#list').html(html);
$('.loading').fadeOut("slow");
}
});
}
function changeStatus(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/ChangeStatus/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
console.log(result);
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
function deleteDocument(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/Delete/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
</script>
i am assuming $('#list').html(html); code loads the html in the dom. instead of directly sending the html from php you can send a json containing the html as well the login status. like this.
$data = [
'login_status' => 1 // or 0,
'html' => $html // full html your are sending now
];
echo json_encode($data);
then in ajax success.
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (response) {
var data = $.parseJSON(response);
if(data.login_status == 0)
{
window.location.href = 'redirect to login page';
}
if(data.login_status == 1)
{
$('#list').html(data.html);
}
$('.loading').fadeOut("slow");
}
});
}
controller method :
public function search(){
if($this->input->is_ajax_request()){
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$html = $this->load->view('admins/documents/ajax_pagination', $data, true);
$res['html'] = $html;
$res['login_status'] = ($this->logged_in()) ? '1' : '0';
echo json_encode($res);
}
I have an ajax file upload with jquery. It always shows The action you have requested is not allowed. Helper arrays html, url, file, form are added. I tried many ways, but gets the same result.
Here is my code
Controller Functions
function demo() {
$this->load->view('file_upload_ajax', NULL);
}
function upload_file() {
//upload file
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
$config['max_size'] = '1024'; //1 MB
echo $_FILES['file']['name'];
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
echo 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/' . $_FILES['file']['name'])) {
echo 'File already exists : uploads/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
}
}
}
} else {
echo 'Please choose a file';
}
}
View file: file_upload_ajax.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Beep Check</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="<?php echo base_url().'js'?>/beep.js"></script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" />
<button id="upload">Upload</button>
</body>
</html>
beep.js
$(document).ready(function() {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: base_url +"beep/upload_file",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
config.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['base_url'] = '';
//$config['index_page'] = 'index.php';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
$config['url_suffix'] = '';
$config['language'] = 'english';
$config['charset'] = 'UTF-8';
$config['enable_hooks'] = FALSE;
$config['subclass_prefix'] = 'MY_';
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd'; // experimental not currently in use
$config['log_threshold'] = 4;
$config['log_path'] = '';
$config['log_date_format'] = 'Y-m-d H:i:s';
$config['cache_path'] = '';
$config['encryption_key'] = 'kccna_mat_1';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
$config['global_xss_filtering'] = FALSE;
$config['csrf_protection'] = true;
$config['csrf_token_name'] = 'k4rm4_auth';
$config['csrf_cookie_name'] = 'k4rm4_auth';
$config['csrf_expire'] = 7200;
$config['compress_output'] = FALSE;
$config['time_reference'] = 'local';
$config['rewrite_short_tags'] = FALSE;
$config['proxy_ips'] = '';
Please help me Thanks in advance.
Check your config.php if $config['csrf_protection'] = TRUE;
If it is set to true you need to send csrf token with the ajax request.
Add this to your view page.
<input type="hidden" id="hidCSRF" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
In your js file do the below changes.
$(document).ready(function() {
$('#upload').on('click', function () {
var _csrfName = $('input#hidCSRF').attr('name');
var _csrfValue = $('input#hidCSRF').val();
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append(_csrfName, _csrfValue);
$.ajax({
url: base_url +"beep/upload_file",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
I can comment with only first item in while loop, When I tried to comment with another item it's always display alert box You know you need to write a comment right?. I think it can't get comment text on another item in my loop, What's wrong with my code?
I've got this comment code from this link.
My code:
Ajax in index.php
<script type="text/javascript">
$(function () {
// Alert(event.timeStamp);
$('.new-com-bt').live('click', function (evt) {
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* When you click on the cancel button */
$('.bt-cancel-com').click(function () {
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function () {
$('.new-com-bt').fadeIn('fast');
});
});
// On post comment click
$('.bt-add-com').live('click', function (evt) {
var comment_on_id = $("input[name=comment_on_id]");
var theCom = $("textarea[name=comment-text]");
var theName = $('#name-com');
var theMail = $('#mail-com');
if (!theCom.val()) {
alert('You know you need to write a comment right?');
} else {
$.ajax({
type: "POST",
url: "ajax/add-comment.php",
data: 'act=add-com&id_post=' + comment_on_id.val() + '&name=' + theName.val() + '&email=' + theMail.val() + '&comment=' + theCom.val(),
success: function (html) {
theCom.val('');
theMail.val('');
theName.val('');
$('.new-com-cnt').hide('fast', function () {
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>
scroll.js in index.php
var ajax_arry=[];
var ajax_index =0;
var sctp = 100;
$(function(){
$('#loading').show();
$.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page=1",
cache: false,
success: function(response){
$('#loading').hide();
$('#demoajax').html(response);
}
});
$(window).scroll(function(){
var height = $('#demoajax').height();
var scroll_top = $(this).scrollTop();
if(ajax_arry.length>0){
$('#loading').hide();
for(var i=0;i<ajax_arry.length;i++){
ajax_arry[i].abort();
}
}
var page = $('#demoajax').find('.nextpage').val();
var isload = $('#demoajax').find('.isload').val();
if ((($(window).scrollTop()+document.body.clientHeight)==$(window).height()) && isload=='true'){
$('#loading').show();
var ajaxreq = $.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page="+page,
cache: false,
success: function(response){
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$('#loading').hide();
$('#demoajax').append(response);
}
});
ajax_arry[ajax_index++]= ajaxreq;
}
return false;
if($(window).scrollTop() == $(window).height()) {
alert("bottom!");
}
});
});
scroll.php
<?php
include('db.php');
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$con,$limit);
}
function showData($data,$con,$limit){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$sql = "select * from infinitescroll order by id asc limit $start,$limit";
$str='';
$data = $con->query($sql);
if($data!=null && $data->num_rows>0){
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
$post_to_itemid = $row['id'];
$str.="<div class='data-container'><p>".$row['id']."</p><p>".$row['firstname']."</p><p>".$row['lastname']."</p>";
$str .= "<div class='new-com-bt'>
<span>Type something ..</span>
</div>
<div class='new-com-cnt'>
<br>
<input type='hidden' value='".$post_to_itemid."' name='comment_on_id'>
<textarea class='the-new-com' name='comment-text'></textarea>
<div class='bt-add-com'>Comment</div>
<div class='bt-cancel-com'>Cancel</div>
</div></div>";
}
$str.="<input type='hidden' class='nextpage' value='".($page+1)."'><input type='hidden' class='isload' value='true'>";
}else{
$str .= "<input type='hidden' class='isload' value='false'><p>Finished</p>";
}
echo $str;
}
?>
This is the JavaScript code which checks for the validation of the mobile number data (with other data) and forwards it to validate_user.php which stores the mobile number.
But I want to store the data of only those users whose mobile number exists in another table or else I want to display an error message saying 'User not present in the database'.
I need help. What do I do?
Thanks in advance.
JavaScript
$(document).ready(function() {
$("#user_submit_form").submit(function() {
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
if (mobile.length != 10 || !(mobile[0] == 7 || mobile[0] == 8 || mobile[0] == 9)) {
alert('Please enter a valid mobile number');
} else {
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
}); // End ajax method
alert('Thank You');
window.location.reload();
}
});
});
This is the server side PHP code:
<?php
session_start();
require("config/config.php");
if(isset($_POST['user_submit']))
$mobile =mysql_real_escape_string ($_POST['mobile']);
$dob = mysql_real_escape_string($_POST['dob']);
$hostname = '';
$database = '';
$username = '';
$password = '';
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
die("Unable to Connect server!".mysql_error());
}
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT mobile FROM mobile_db WHERE mobile="'.$mobile.'"');
if(mysql_num_rows($sql) == 1)
{
$query = 'INSERT INTO taj_contact_info (chassis,pin,title,fname,lname,email,mobile,dob,anniversary,company,designation,home_business,add1,add2,city,state,pincode,timestamp) VALUES("'.$mobile.'","'.$dob.'",'.strval(time()).')';
$sql1= mysql_query($query);
}
else
{
return true;
}
?>
$(document).ready(function() {
$("#user_submit_form").submit(function() {
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
if (mobile.length != 10 || !(mobile[0] == 7 || mobile[0] == 8 || mobile[0] == 9)) {
alert('Please enter a valid mobile number');
} else {
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success: function(json){
if(json.error){
alert(json.error)// or do whatever you want
}
else{
alert(json.success) // there your made a success call the do your staff
}
}
}); // End ajax method
alert('Thank You');
window.location.reload();
}
});
});
**The Server Side php**
<?php
session_start();
require("config/config.php");
if(isset($_POST['user_submit']))
$mobile =mysql_real_escape_string ($_POST['mobile']);
$dob = mysql_real_escape_string($_POST['dob']);
$hostname = '';
$database = '';
$username = '';
$password = '';
$json = array();
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
$json['error'] = "Unable to Connect server!".mysql_error();
}
if(empty($json)){
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT mobile FROM mobile_db WHERE mobile="'.$mobile.'"');
if(mysql_num_rows($sql) == 1)
{
$query = 'INSERT INTO taj_contact_info (chassis,pin,title,fname,lname,email,mobile,dob,anniversary,company,designation,home_business,add1,add2,city,state,pincode,timestamp) VALUES("'.$mobile.'","'.$dob.'",'.strval(time()).')';
$sql1= mysql_query($query);
$json['success'] = "Successfully inserted";
}
else
{
$json['error'] = 'A Fake Number';
}
}
echo json_encode($json);
You can verify this using success response
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success:(function(result){
if(empty(result)){
return false;
}else{
return true;
}
}));
});