after refreshing only i am getting the last inserted item - codeigniter

When i am inserting new manufacturer ,
('already exists ' checking is happening but
after refreshing only i am getting the latest view.but last insert manufacture is getting after the refresh.what will i do>
Controller Erp_c
function manufacturertable($user)
{
$m1=$this->input->post('man');
$result['query']=$this->erp_m->insertmanu($m1,$user);
$result['query2']=$this->erp_m->getmanu();
if(($result['query'])>0)
{
?>
<script type=text/javascript>
alert("Name already Exists")
</script>
<?php
// echo"already exists";
// $this->load->view('head1');
// $this->load->view('header3');
// $this->load->view('manuview1',$result);
}else{
?>
<script type=text/javascript>
alert("Name Available")
</script>
<?php
$this->erp_m->insertmanu2($m1,$user);
}
$this->load->view('head1');
$this->load->view('header3');
$this->load->view('manuview1',$result);
model erp_m
function insertmanu($m1,$user)
{
$this->db->where('manufacture',$m1);
$res=$this->db->get('manufacturer3');
$num=$res->num_rows();
return $num;
}

your information not enough to solve.
advise : for check available may be you can relocate your code to model, and send return in array.
function insertmanu($m1,$user)
{
$this->db->where('manufacture',$m1);
$res=$this->db->get('manufacturer3');
$num=$res->num_rows();
if($num > 0 ){
// todo something
return array("status"=>1,'msg'=>'name available');
}else{
//todo something
return array("status"=>0,'msg'=>'name unique');
}
}

Related

Json Data print after insert a record using Jquery Ajax in CodeIgniter

I am using Jquery Ajax in Codeigniter, after register a user via bootstrap modal I got JSON data as below instead of fetching the data from table. Where I am wrong? please help!
{"success":true,"type":"add"}
Here is my Jquery function
```
<script>
$(function(){
display();
//add new
function display(){
$.ajax({
type:'ajax',
url:'<?php echo base_url()?>frame_cont/display',
async: false,
dataType:'json',
success:function(data){
var html='';
var i;
for(i=0;i<data.length;i++){
html +='<tr>'+
'<td>'+data[i].id+'</td>'+
'<td>'+data[i].username+'</td>'+
'<td>'+data[i].email+'</td>'+
'<td>'+data[i].password+'</td>'+
'<tr>';
}
$('#showdata').html(html);
},
error:function(){
alert('Could not get Data from Database');
}
});
};
});
</script>```
and here is controller class
<?php
class Frame_cont extends CI_Controller{
public function index(){
$this->load->view('index');
}
public function register(){
$this->load->model('frame');
$result=$this->frame->insert();
$msg['success']=false;
$msg['type']='add';
if($result){
$msg['success']=true;
}
echo json_encode($msg);
}
public function display(){
$this->load->model('frame');
$result=$this->frame->display();
echo json_encode($result);
}
}
This is all about the code and sorry for the english
in your register function you doing echo json_encode($msg); at the end. you should echo inserted value inside if condition
The issue occur because of I am using type="submit" instead of type="button" in my form button.

wordpress ajax pagination breaks after 10 pages

Can someone help me with ajax pagination please, i'm on it 2 days already and can't figure it out. I have Load More style pagination, this is the code, preety classic(down below).
Everything works as planing except when the placeholder reaches page 10. Then, hell break loose and nothing is loading anymore. The button still works untill maxpages is reached and so the button gets removed, but nothing happens with more than 10 placeholders. The website i'm currently using this scriptand the place you can test yourself is this: http://filmhdonline.com/category/toate-filmele/
I would appreciate someone having an ideea what i'm talking about. Thanks in advance.
jQuery(document).ready(function() {
// The number of the next page to load (/page/x/).
var pageNum = parseInt(pbd_alp.startPage);
// The maximum number of pages the current query can return.
var max = parseInt(pbd_alp.maxPages);
// The link of the next page of posts.
var nextLink = pbd_alp.nextLink; pageNum++;
//Load more videos translation
var more = pbd_alp.more;
//Loading videos translation
var loading = pbd_alp.loading;
/**
* Replace the traditional navigation with our own,
* but only if there is at least one page of new posts to load.
*/
if(pageNum <= max) {
// Remove the traditional navigation.
jQuery('.pagination').remove();
// Insert the "More Posts" link.
if( jQuery('#content').find('ul.listing-videos').length == 1 ){
jQuery('#content ul.listing-videos').append('<li class="more-posts pbd-alp-placeholder-' + pageNum + '"></li>');
jQuery('#content').append('<p id="pbd-alp-load-posts" class="pagination">' + more + '</p>');
}
}
/**
* Load new posts when the link is clicked.
*/
jQuery('#pbd-alp-load-posts a').click(function() {
// Are there more posts to load?
if(pageNum <= max) {
// Show that we're working.
jQuery(this).text(loading);
jQuery('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' #content ul.listing-videos li',
function() {
//jQuery('.pbd-alp-placeholder-'+ pageNum).children('li').unwrap();
console.log(pageNum);
jQuery(this).children().hide();
$newContent = jQuery(this).children().unwrap();
$newContent.fadeIn('fast');
// Update page number and nextLink.
pageNum++;
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
**// Add a new placeholder, for when user clicks again.
jQuery('#content ul.listing-videos').append('<li class="more-posts pbd-alp-placeholder-'+ pageNum +'"></li>');**
// Update the button message.
if(pageNum <= max) {
jQuery('#pbd-alp-load-posts a').text('Vezi mai multe');
} else {
jQuery('#pbd-alp-load-posts a').remove();
}
}
);
} else {
jQuery('#pbd-alp-load-posts a').append('.');
}
return false;
});
});
For ajax pagination in wordpress, You can use the plugin like https://wordpress.org/plugins/wp-pagenavi/.
OR
<div id="content">
<?php
$new_query = new WP_Query();
$new_query->query('post_type=post&showposts=1'.'&paged='.$paged);
?>
<?php while ($new_query->have_posts()) : $new_query->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?>
<div id="pagination">
<?php next_posts_link('« Older Entries', $new_query->max_num_pages) ?>
<?php previous_posts_link('Newer Entries »') ?>
</div>
</div><!-- #content -->
<script>
jQuery(function($) {
$('#content').on('click', '#pagination a', function(e){
e.preventDefault();
var link = $(this).attr('href');
$('#content').fadeOut(500, function(){
$(this).load(link + ' #content', function() {
$(this).fadeIn(500);
});
});
});
});
</script>
I Have the same problem.
If it still happening, replace:
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
to
nextLink = nextLink.replace(/\/page\/[0-9]*/, '/page/'+ pageNum);
Problem in wrong regex [0-9]? match only single number from 1 to 9. From 10 it takes only 1. Instead [0-9]* match from 0 to infinity. So, it breaks after 9 (form 0 to 9), because next 10 and it's take fore use only 1.

CodeIgniter Ajax form - submitting form

I'm new to stackoverflow and to CodeIgniter and I'm currently experimenting on some simple code examples I have found on the Internet in order to get a start. The one I'm working on right now is a form which uses CI and Ajax (jQuery) along with saving the inputs of the form in a database and then display the most recent of them on the same page as the form.
If I confused you it's the 4.7 application example from here. The initial source code lies here but I have modified it in order to work with the latest release of CI and I quote all my MVC files just below.
Controller:
<?php
class Message extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('security');
$this->load->model('Message_model');
}
function view()
{
//get data from database
$data['messages'] = $this->Message_model->get();
if ( $this->input->is_ajax_request() ) // load inline view for call from ajax
$this->load->view('messages_list', $data);
else // load the default view
$this->load->view('default', $data);
}
//when we pres the submit button from the form
function add()
{
if ($_POST && $_POST['message'] != NULL)
{
$message['message'] = $this->security->xss_clean($_POST['message']);
$this->Message_model->add($message);
}
else
{
redirect('message/view');
}
}
}
?>
Model:
<?php
class Message_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database();
}
function add($data)
{
$this->db->insert('messages', $data);
}
function get($limit=5, $offset=0)
{
$this->db->order_by('id', 'DESC');
$this->db->limit($limit, $offset);
return $this->db->get('messages')->result();
}
}
?>
Views
default.php:
<!-- called using message/view -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="<?php echo base_url('js/jquery-1.8.1.min.js'); ?>" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("", {message: msg}, function() {
$('#content').load("");
$('#message').val('');
});
});
});
</script>
</head>
<body>
<?php echo form_open("message/add"); ?>
<input type="text" name="message" id="message">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>
<div id="content"></div>
</body>
</html>
messages_list.php:
<!-- called from ajax call -->
<ol>
<?php foreach ($messages as $cur): ?>
<li><?php echo $cur->message; ?></li>
<?php endforeach; ?>
</ol>
The problem mainly lies in the 1st of the views (default.php). That is, if I omit the e.preventDefault(); line from the javascript code then the form loads a different page (message/add as the form action parameter implies) which is a blank page, also cancelling the ajax behavior of my application that way.
On the other hand, if I actually add this line then the add method of my message controller isn' t called, thus not adding what I've typed into the database.
Finally, I tried the following js code instead of the other above:
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
$('#content').load("");
$('#message').val('');
});
});
});
but that way it seems as the $.post() crashes because nothing is executed in the function which is supposed to run on a successful post() call.
Any help appreciated and sorry for the big post. :)
You are correct that you must call e.PreventDefault();, but you must also deal with the response from the callback function, which you are not. The callback takes a few arguments but the first one is what you're interested in, it is the response from your server. I've denoted it as r below:
$(document).ready(function(){
$('#submit').click(function(e){
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function(r) {
//do something with r... log it for example.
console.log(r);
});
});
});
I've also removed $.("#content").load(...);. This would actually perform another AJAX request when the first one is complete.
Now, inspecting your controller...please refrain from using $_POST. CodeIgniter provides you with $this->input->post() as part of the Input Library. If you turn on Global XSS filtering in config/config.php you won't have to xss clean it either. You can clean on a post-by-post basis by using $this->input->post('name', true);
I recommend this instead:
function add(){
$m = $this->input->post('message', true);
if($m){
$this->Message_model->add($m);
}
}
The problem doesn't lie with the CI, its the JS that is wrong,
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var msg = $('#message').val();
$.post("<?php echo base_url(); ?>message/add", {message: msg}, function() {
$('#content').load("<?php echo base_url(); ?>/message/view");
$('#message').val('');
});
});
});
The e.preventDefault() is used to stop the default behaviour of the submit button (which will take you to message/add), which we don't want. You are correct in adding the URl paramter to the $.post() function later, but in the callback function, the .load loads the URL that is passed to it into the #content, so without passing any url, of course there won't be anything to load.

parsing dojo tundra dijits in ajax response

I am having massive problems re-parsing my dojo elements in an ajax response in Zend framework. I have a simple validationTextBox and a submit button. When the index page is first rendered, all the dojo/dijit tundra styles/attributes etc are parsed correctly. However, when I have an ajax call that rebuilds the dojo form and posts it back to the Index View. The form if posted back ok but the tundra styles are no longer working. I have tried so many different things but have spent many hours getting nowhere. I thank anyone in advance who attempts to assist. I have added the simplest example to this post to explain.
layout.phtml
<?php
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo $this->doctype();
?>
<html>
<head>
<meta content="text/html; charset=UTF-8" />
<script>
function showForm()
{
dojo.xhrGet( {
url: "../public/index.php?ajax=true",
// The load function is called on successful response from server
// It inserts the response to the HTML div “put_here” placeholder
handleAs:"text",
sync:true,
load: function(response, ioArgs)
{ dojo.byId("welcome").innerHTML = response;
return response;
},
// The error function displays error message if server does not
// respond right
error: function(response, ioArgs)
{
console.error("HTTP status code: ", ioArgs.xhr.status);
return response;
}
});
// dojo.parser.parse(dojo.byId("welcome"));
}
</script>
<?php
echo $this->headTitle();
echo $this->headStyle();
echo $this->headScript();
echo $this->dojo()->setDjConfigOption('parseOnLoad', true);
echo $this->dojo()->addStyleSheetModule('dijit.themes.tundra');
echo $this->dojo();
?>
</head>
<body class='tundra'>
<div id='ajaxcontent'>
<?php echo $this->layout()->content; ?>
</div>
</body>
indexController.php
<?php
//require_once '../public/js/custom.js';
class IndexController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('index', 'html')
->initContext();
}
public function indexAction()
{
$form = new Zend_Dojo_Form('dojoForm', array('dojotype'=> 'dijit.layout.ContentPane'));
$element = new Zend_Dojo_Form_Element_ValidationTextBox('TestBoxName',
array(
'id' => 'TextBoxId',
'required' => true
)
);
$button = new Zend_Dojo_Form_Element_Button('TestButton',
array(
'value'=> 'Button',
'onclick' => 'showForm()'
));
$form->addElements(array($element,$button));
$this->view->form = $form;
}
}
View index.phtml
<div id="welcome" >
<?php
echo $this->form;
?>
Try to run your page through the http://validator.w3.org/ - it is probably the DOCTYPE, and issues with non-closed tags?
The line with addStyleSheetModule simply adds a css file, the class set on your <body> asserts, that all nodes below body 'inherits' the theme (CSS selectors). Selectors however is highly depending on wellconstructed DOM (hence the validation)
But the main issue here seems to be that the dijit classes are not set - probably because data-dojo-type's are not initialized. There are two approaches
1.1 In layout.phtml
function showForm() { dijit.byId('welcome').set('href', '../public/index.php?ajax=true'); }
1.2 In index.phtml
Create a contentpane (which defaults to parseOnLoad) in your <div id='welcome'..
<div id="welcome" data-dojo-type="dijit.layout.ContentPane">
2.0 call parser manually
load: function(response, ioArgs)
{ var domnode = dojo.byId("welcome");
domnode.innerHTML = response;
dojo.parser.parse(domnode);
return response;
}

server crashes when i use onreadystatechange

I am trying to create a chat for my website.
To load the new data, i run a function every 1.5''.
If i use asynchronous mode, my website is fast, my server does not crash, but browser freezes until the response.
When i use synchronous mode, my server crashes after a while, and i have to restart Apache (! ?).
I thought that i was requesting too much data and my (virtual) server crashes, but why in asynchronous mode works fine ?
function loadchat() {
xmllive.open('GET','live.php', false);
xmllive.send(null);
myelemen('dcdd').innerHTML = xmllive.responseText;
}
function loadchatv() {
xmllive.onreadystatechange=function() {
if (xmllive.readyState==4 && xmllive.status==200){
myelemen('dcdd').innerHTML = xmllive.responseText;
}
}
xmllive.open('GET','live.php', true);
xmllive.send();
Thank you for your answer, MMM. Since your response, i read about your suggestions.
(http://dsheiko.com/weblog/websockets-vs-sse-vs-long-polling).
I figured that, in Long Pooling the server makes a loop until finds new data and only then browser receives and makes a new request.
So, tell me please, what do you think about this solution (simplified):
/////////// html file //////////////
<script type="text/javascript" charset="utf-8">
var xmlff;
if (window.XMLHttpRequest) {
xmlff=new XMLHttpRequest();
} else {
xmlff=new ActiveXObject("Microsoft.XMLHTTP");
}
function waitForMsg(){
xmlff.onreadystatechange=function() {
if (xmlff.readyState==4 && xmlff.status==200){
document.getElementById('messages').innerHTML = xmlff.responseText ;
setTimeout('waitForMsg()', 1000 );
}
}
xmlff.open('GET','msgsrv.php' ,true);
xmlff.send();
}
</script>
</head>
<body>
<div id="messages">
</div>
<script type=text/javascript>
waitForMsg()
</script>
</body>
</html>
/////// php file ///////////
<?
do {
sleep(3);
$result = mysql_query("SELECT message FROM chat ");
while ($row = mysql_fetch_array($result)){
$msg .= $row[0];
}
} while (mysql_num_rows($result) == 0);
header("HTTP/1.0 200");
print $msg;
?>
Thanks in advance.

Resources