Who to append php on chnage with Jquery Ajax - javascript

I am trying to append php script to the dom in a div that has the class .new-session but it doesn't work how it should.
Here is my code
$('select[name=quantity]').change(function() {
quantity = $(this).val();
if (quantity == 20) {
newSession = '<?php echo $_SESSION[\'product\'][\'quantity\'] = 20; ?>';
}
elseif(quantity == 30) {
newSession = '<?php echo $_SESSION[\'product\'][\'quantity\'] = 30; ?>';
}
elseif(quantity == 40) {
newSession = '<?php echo $_SESSION[\'product\'][\'quantity\'] = 40; ?>';
}
elseif(quantity == 50) {
newSession = '<?php echo $_SESSION[\'product\'][\'quantity\'] = 50; ?>';
}
elseif(quantity == 60) {
newSession = '<?php echo $_SESSION[\'product\'][\'quantity\'] = 60; ?>';
}
$.ajax({
url: "/multisite/",
dataType: "html",
success: function(newSession) {
$('.set-session').append(newSession);
}
})
});
<div class="set-session">
</div>

You can't append PHP to the DOM, PHP code is run on the server when the page is being created. You use AJAX to run server code in response to a user action, and the script that receives the AJAX call updates the session.
Here's how you can do what you want:
$('select[name=quantity]').change(function() {
var quantity = $(this).val();
$.ajax({
url: "/multisite/setquantity.php",
data: { quantity: quantity }
});
});
The PHP in setquantyt.php should be like:
<?php
session_start();
$_SESSION['product']['quantity'] = intval($_GET['quantity']);

Related

Auto Load More on scroll down is loading only first 2 pages

I have auto load more on page scroll down.
My jQuery/ajax is working but it is auto loading only first 2 pages on scroll down. There are more pages/records but it stuck after 2nd page loads.
I cannot understand the issue.
Somebody please help me out. My php and java code is given below
just played around with the same moving lines up and down but no use.
<?php
$pxe = $_GET['pname'];
$sxe = $_GET['sname'];
?>
$(document).ready(function(){
var is_ajaxed = false;
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#faq-result").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() >= ($(document).height() - $(window).height()-900) && is_ajaxed == false){
if($(".pagenum").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum").val()) + 1;
var pname = "<?php echo $pgianame; ?>";
var sname = "<?php echo $stianame; ?>";
getresult('sellers_forum_page_posts_getresult.php?page='+pagenum+'&pname='+pname+'&sname='+sname);
is_ajaxed = true
}
}
});
});
getresult.php
<?php
include('inc/db.php');
$perPage = 10;
$sql = "SELECT * from posts";
$allrows = $dba3->query($sql);
$allrowscount = mysqli_num_rows($allrows);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start < 0) $start = 0;
$query = $sql." limit ".$start.",".$perPage;
$faq = $dba3->query($query);
if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = mysqli_num_rows($faq);
}
$output = '';
if(!empty($faq)) {
$output .= '<input hidden class="pagenum" value="'.$page.'" />';
$output .= '<input hidden class="total-page" value="'.$pages.'" />';
while ($row = $faq->fetch_assoc()) {
$output .= $row["ename"];
} }
print $output;
?>
no errors just loader image keeps moving
The key is to get the row count from the initial sql, before applying the limit, something like:
$perPage = 10;
$sql = "SELECT * from posts";
$allrows = $dba3->query($query);
$allrowscount = mysqli_num_rows($allrows);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start < 0) $start = 0;
$query = $sql . " limit " . $start . "," . $perPage;
$faq = $dba3->query($query);
You should add async : false, in your ajax request.
url: url,
async : false,
type: "GET",
data: {rowcount:$("#rowcount").val()},
Your browser needs to wait for the response before the next request is sent.

CodeIgniter ajax reloading page issue

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);
}

Error in AJAX code causing broswer to crash

Hello I have written an ajax script that grabs different pages and displays them for X amount of time and then switches to the next page. I use the setTimeout function to display the pages for the X amount of time. In order to grab each page I created a list of different pages in a database that my code looks at then calls the appropriate php function to grab the data.
What seems to be happening is that it causes firefox to crash after a couple of days because firefox seems to run out of memory. My guess is that my code is not efficient but, I am not sure how I can make it more efficient so it does not crash the browser. Any help would be greatly appreciated. Here is my code:
<?php $this->load->view('includes/header'); ?>
<div id="result">
</div>
<?php $this->load->view('includes/footer');?>
<?php $displayName = $this->input->get('name');?>
<script type="text/javascript">
var views = [];
var cell = '';
var i = 0;
var display = <?php echo json_encode($displayName); ?>;
var timeOut = 0;
$(function get_data() {
$.ajax({
url: "get_display_data/"+display,
type: "post",
cache: false,
success: function(data){
views = JSON.parse(data);
if (i >= views.display.length) {
i = 0;
} else if (views.display[i].view == 'Fabrication') {
var loadUrl = "<?php echo base_url();?>/index.php/Cells/FabricationStatus/"+views.display[i].view + "/"+ "display1?name="+display;
$("#result").empty().load(loadUrl+"#mainContent");
timeOut = 60;
i++;
} else if(views.display[i].view == 'CYLPLNGLCMSH') {
var loadUrl = "<?php echo base_url();?>/index.php/Cells/CYLPLNGLCMSHStatus/"+views.display[i].view + "/"+display;
$("#result").empty().load(loadUrl+"#mainContent");
timeOut = 60;
i++;
} else if(views.display[i].view == 'COTCTR') {
var loadUrl = "<?php echo base_url();?>/index.php/Cells/COTCTRStatus/"+views.display[i].view + "/"+display;
$("#result").empty().load(loadUrl+"#mainContent");
timeOut = 60;
i++;
} else {
var loadUrl = "<?php echo base_url();?>/index.php/Cells/Display/"+views.display[i].view + "/"+display;
$("#result").empty().load(loadUrl+".mainContent");
timeOut = 30;
i++;
}
setTimeout(get_data, (1000 * timeOut));
}
});
});

How to show the errors through ajax and Jquery in codeigniter

This is my ajax call
function exportCSV(){
var sampleid = $("#sampleid").val();
var scheme = $("#scheme").val();
var v = $("#v").val();
var date = $("#date").val();
var assignedvalue = $("#assignedvalue").val();
var units = $("#units").val();
var assayvalue = $("#assayvalue").val();
var analyte = $("#analyte").val();
var filename=$("#filename").val();
var sample_error=$("#sample_error").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "import/validate_file",
dataType: 'json',
data: {
sampleid: sampleid,
scheme: scheme,
v: v,
date: date,
assignedvalue: assignedvalue,
units: units,
assayvalue: assayvalue,
analyte: analyte,
filename:filename,
sample_error: sample_error
},
success: function (data) {
console.log(data); //as a debugging message.
}
});
}
and this is my controller
<?php
if (!empty($unit_check) and !empty($analyt) and !empty($sch) and count($sample_id) == count(array_unique($sample_id)) and $assigned_check == '1' and $assay_check == '1') {
for ($row = 2; $row <= $lastRow; $row++) {
$data['sample_id'] = $worksheet->getCell($sampleid . $row)->getValue();
$data['scheme'] = $worksheet->getCell($scheme . $row)->getValue();
$data['v'] = $worksheet->getCell($v . $row)->getValue();
$data['units'] = $worksheet->getCell($unit . $row)->getValue();
$data['date'] = $worksheet->getCell($date . $row)->getFormattedValue();
$data['assay_value'] = $worksheet->getCell($assayvalue . $row)->getValue();
$data['assigned_value'] = $worksheet->getCell($assignedvalue . $row)->getValue();
$data['analyte'] = $worksheet->getCell($analyte . $row)->getValue();
$data['trace_id'] = $insert_id;
$this->import_model->insert_data($data);
$response['success'] = true;
}
} else {
$data['sample_id'] = '';
$data['analyte'] = '';
$data['unit_check'] = '';
$data['sch'] = '';
$data['assigned_value'] = '';
$data['assay_value'] = '';
if (count($sample_id) != count(array_unique($sample_id))) {
$data['sample_id'] = '1';
}
if (empty($analyt)) {
$data['analyte'] = '1';
}
if (empty($unit_check)) {
$data['unit_check'] = '1';
}
if (empty($sch)) {
$data['sch'] = '1';
}
if ($assigned_check == '') {
$data['assigned_value'] = '1';
}
if ($assay_check == '') {
$data['assay_value'] = '1';
}
$data['file_name'] = '';
}
?>
I have to show the errors and success message on ajax call.
Right now I'm succeeded in valuating the data and putting it in the database.
But I want to show the success message at the end of the page by clicking the submit button.
And if there is validations error it must shows the errors in that fields at the end of the page
Any help would be appreciated.
Here inside your success method of ajax
success: function (data) {
$("#resultDiv").html(data)
}
Return some real data from your controller in both case success and failed. and based on your data inside success method show your message.
Like:
success: function (data) {
$("#resultDiv").html(data.success) //this requires string to convert your result in string if neccessary
//But you should return a JSON data as msg from your controller
}
You should put a result HTML element for example:
<div id='resultDiv'></div> <!-- to match with #resultDiv -->
Put response data in both condition if success=true and else success=false
In your controller
if(.....){
//what ever check you wanna do
..........
..........
$response['msg']='success';
header('Content-Type', 'application/json');
echo json_encode($response);
}
else{
$response['msg']='failed';
header('Content-Type', 'application/json');
echo json_encode($response);
}
In your ajax
success: function (data) {
$("#resultDiv").html(data.msg)
}
Try something like:
$response = array(
'errCode' = 0,
'errMsg' = 'msg'
);
return this kind of array by json_encode() from php to ajax() call and use it in ajax() success like:
var data = JSON.parse(response);
alert(data.errMsg);
You can also put a check on errCode like:
if(errCode == 0) { something }
if(errCode == 1) { something }

How to send a post through javascript in CodeIgniter?

I want to send a post form in Codeigniter when click a link:
My html code:
Delete
I want to do with post method because is more secure to do with csrf protection.
Thanks
Source: http://jsfiddle.net/iam_groot/aaeftkhv/
You need to create a global variable in html header for csrf protection:
<script>
var csrf_token_name = "<?php echo $this->security->get_csrf_token_name(); ?>";
var csrf_hash = "<?php echo $this->security->get_csrf_hash(); ?>";
</script>
Edit html link:
Delete row
And add this javascript code:
<script>
create_form_post = function(action, fields, target) {
if(target == undefined) {
target = '_self';
}
fields[csrf_token_name] = csrf_hash;
id_form = makeid();
$( '<form method="POST" action="'+action+'" target="'+target+'" id="'+id_form+'" style="display:none !important;"></form>' ).appendTo( "body" );
$.each(fields, function( k, v ) {
$( '<input name="'+k+'" value="'+v+'" type="hidden" />' ).appendTo( "form#"+id_form );
});
return id_form;
}
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 9; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
$(document).ready(function() {
$("a.delete").click(function() {
if(confirm("¿Are you sure?")) {
action = $(this).attr('href');
delete_id = $(this).attr('id');
id_delete_form = create_form_post(action, {id: delete_id});
$("form#" + id_delete_form).submit();
}
});
});
</script>
Use AJAX
url = '<?php echo site_url('clientes/delete/'); ?>';
$('.delete').click(function(){
clientId = $(this).attr('id');
$.ajax({
type: "POST",
url: url,
data: { clientId: clientId }
});
})
In controller
if(isset($_POST['clientId'] {
$clientId = $_POST['clientId'];
} else {
$clientId = 'No data';
}

Categories