jQuery UI is not inherited in ajax loaded content - ajax

I am using CI 2.1.3, having problem with jQuery UI inheritance. Trying to create a ajax gui sortable page nesting.
view/admin/components/page_head.php
<!DOCTYPE html>
<html>
<head>
<title><?php echo $meta_title; ?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="<?=site_url(config_item('path_bootstrap').'css/bootstrap.min.css');?>" rel="stylesheet" media="screen">
<!-- jQuery -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
if (!window.jQuery) {
document.write('<script src="<?php echo site_url(config_item("path_assets")."js/jquery-1.10.1.js"); ?>"><\/script>');
}
</script>
<script src="<?php echo site_url(config_item('path_bootstrap').'js/bootstrap.min.js'); ?>"></script>
<?php //if((isset($sortable)) AND ($sortable === TRUE)): ?>
<!-- script src="<?php echo site_url(config_item('path_jqueryui').'minified/jquery-ui.min.js'); ?>"></script -->
<script src="<?php echo site_url(config_item('path_assets').'js/jquery-ui.js'); ?>"></script>
<script src="<?php echo site_url(config_item('path_assets').'js/jquery.mjs.nestedSortable.js'); ?>"></script>
<script type="text/javascript">
if (window.jQuery.ui) {
alert('jquery ui found');
}
else {
alert('jquery ui not found');
}
/*if (window.jQuery) {
alert('jquery found');
}
if (window.jQuery.ui) {
alert('jquery ui found');
}
if (window.jQuery.ui.sortable) {
alert('jquery ui sortable found');
}
if (window.jQuery.mjs.nestedSortable) {
alert('jquery nestedSortable found');
}*/
</script>
<?php //endif; ?>
<script src="<?php echo site_url(config_item('path_assets').'js/tinymce/tinymce.min.js'); ?>"></script>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
</head>
view/admin/order.php
<section>
<h2>Order pages</h2>
<p class="alert alert-info">Drag to order pages and then click 'Save'</p>
<div id="orderResult"></div>
<input type="button" id="save" value="Save" class="btn btn-primary" />
</section>
<?php dump($sortable); ?>
<script>
$(function() {
$.post('<?php echo site_url("tutsplus_admin/page/order_ajax"); ?>', {}, function(data)
{
$('#orderResult').html(data);
});
$('#save').click(function()
{
oSortable = $('.sortable').nestedSortable('toArray');
$('#orderResult').slideUp(function()
{
$.post('<?php echo site_url("tutsplus_admin/page/order_ajax"); ?>', { sortable: oSortable }, function(data)
{
$('#orderResult').html(data);
$('#orderResult').slideDown();
});
});
});
});
</script>
order_ajax.php
<?php
//dump($pages);
function get_ol ($array, $child = FALSE)
{
$str = '';
if (count($array)) {
$str .= $child == FALSE ? '<ol class="sortable">' : '<ol>';
foreach ($array as $item) {
$str .= '<li id="list_' . $item['id'] .'">';
$str .= '<div>' . $item['title'] .'</div>';
// Do we have any children?
if (isset($item['children']) && count($item['children'])) {
$str .= get_ol($item['children'], TRUE);
}
$str .= '</li>' . PHP_EOL;
}
$str .= '</ol>' . PHP_EOL;
}
return $str;
}
?>
<?php echo get_ol($pages); ?>
<script type="text/javascript">
$(document).ready(function()
{
$('.sortable').nestedSortable({
handle: 'div',
items: 'li',
toleranceElement: '> div',
maxLevels: 2
});
});
</script>
In order.php jquery, jquery_ui and msj.nestedSortable is succesfully loaded. order_ajax.php is loaded as ajax content. It is not working unless I load jquery ui and msj.nestedSortable script again in order_ajax.php.
Any thoughts?

Script content in a page loaded via AJAX is not beeing executed. Put your script in a *.js-File and load this via jQuery.getScript or change dataType of your AJAX call to script:
$.ajax({
...
dataType: "script",
...
});
From http://api.jquery.com/jQuery.ajax/:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

Related

How to detect which button has been pressed with ajax

I want that every time the "plato" button is pressed (there are several because I create them inside a loop) this function is executed
"$ ('# plato'). click (function ()" but I have observed that this code is only executed when the first button is pressed. With the others it is not executed.
menu.php:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="estilos.css">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="ajax.js"></script>
</head>
<body>
<?php
$restaurante=$_GET['restaurante'];
chdir(getcwd()."/".$restaurante);
$id_fichero= #fopen("menus.txt","r") or die("<B>El fichero no se pudo abrir");
?>
<?php
while (!feof($id_fichero))
{
if(($linea=trim(fgets($id_fichero,256),"\n\r"))!=false)
{
echo("<button type='button' class='accordion'>".$linea."</button>");
echo("<div class='panel'>");
$id_fichero2= #fopen($linea.".txt","r") or die("<B>El fichero no se pudo abrir");
while (!feof($id_fichero2))
{
if(($linea2=trim(fgets($id_fichero2,256),"\n\r"))!=false)
{
echo("<button type='button' id='plato' name='plato'>".$linea2."</button><br>");
echo("<input type='hidden' id='nombrePlato' name='nombrePlato' value='".$linea2."'>");
}
}
echo ("</div>");
}
}
?>
<div id="carrito">
</div>
<script src="collapsible.js"></script>
</body>
</html>
ajax.js
$(document).on('ready',function(){
$('#plato').click(function(){
alert("I'm here");
var url = "anadirCarrito.php";
$.ajax({
type: "POST",
url: url,
data: $('#platos').serialize(),
success: function(data)
{
$('#carrito').html(data);
}
});
});
});

TypeError: $.ajax is not a function with jquery 3.2.1

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<!--Navigation bar-->
<div id="nav-placeholder">
</div>
<div id="carousel">
</div>
<div id="successfulModal">
</div>
<script>
$(function(){
$("#nav-placeholder").load("newnavbar.html");
$("#carousel").load("carousel.php");
});
</script>
<!--end of Navigation bar-->
<?php
if($_REQUEST['signupValue']==1)
{
echo "<script>";
echo "alert('Thank you for signup');";
echo "</script>";
}
require "database.php";
/* echo " after requre database.php"; */
$result = home_page_image();
if(!$result)
{
/* echo 'Could not run query'.mysql_error(); */
exit;
}
/* $row = $result->fetchAll(PDO::FETCH_ASSOC); */
/* $row = $result->fetch(PDO::FETCH_ASSOC); */
/* echo 'inside php'; */
$count = $result->rowCount();
echo '<div class="container">';
while($count>0)
{
echo '<div class="row">';
$i=0;
while($i<3)
{
$row = $result->fetch(PDO::FETCH_ASSOC);
echo '<div class="col-sm-4">';
echo '<div class="card">';
echo '<div class="card-body"><a href="productDetails.php?id=';
echo $row['code'];
echo '"><img src="../';
echo $row['imageurl'];
echo '" class="img-responsive" style="width:250px;height:250px" alt="Image">';
echo '</a></div><div class="card-footer">';
echo mb_strimwidth($row['name'],0,28,"...");
echo '<button type="button" class="btn btn-outline-dark pull-right" onclick="like('.$row['code'].')"><i class="fa fa-thumbs-o-up"></i></button><button type="button" class="btn btn-outline-dark pull-right" onclick="cart('.$row['code'].')"><i class="fa fa-cart-arrow-down"></i></button></div></div></div>';
$i++;
$count--;
}
echo '</div>';
}
?>
</div><br><br>
<div id="footer">
</div>
<script>
function like($code)
{
alert("like button clicked");
$.ajax({
url: 'insertLike.php',
type: 'POST',
data: {
code: $code
}
/*success: function(msg) {
alert('Email Sent');
} */
});
};
$(function(){
$("#footer").load("footer.html");
});
</script>
</body>
</html>
When I use <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
instead of <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> the output damaged.
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> works.
But the original view of the output is
newnavbar.html uses some other script where there is a different version of jquery. I don't sure whether this generates the error or not.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
I view some answer answer with the same error, but nothing solves my problem. For that I have to post a new question with same error. Is it jquery version problem? Or, syntax error problem?
first you should put any scripts in the end of body
for that you should put jquery script in the end of body
As e.g
<body>
<h1> hello world </h1>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
</body>
replace https://code.jquery.com/jquery-3.3.1.slim.min.js with the full jQuery version https://code.jquery.com/jquery-3.3.1.min.js that works.

Getting console error : mysql_real_escape_string() when used ignited datatable codeigniter

This is the console error i got
mysql_real_escape_string(): The mysql extension is deprecated and will be removed in the
future: use mysqli or PDO instead. this error i got in Datatable library file.Anybody knows what is the issue?
My controller
public function manageuser()
{
$tmpl = array ( 'table_open' => '<table id="big_table" border="1" cellpadding="2" cellspacing="1" class="mytable">' );
$this->table->set_template($tmpl);
$this->table->set_heading('First Name','Last Name','Email');
$this->load->view('moderator/manageuser');
}
public function datatable()
{
$this->datatables
->select("mro_id,mro_name,mctg_name,mctg_id")
->from('jil_mroproducts')
->join('jil_mrocategory', 'jil_mroproducts.mro_category=jil_mrocategory.mctg_id', 'INNER')
->edit_column('mro_name', '$2', 'mro_id, mro_name');
//->unset_column('mro_id');
echo $this->datatables->generate();
}
My View
<html>
<head>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<title>Subscriber management</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/datatable.css" type="text/css" media="screen"/>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/ui-lightness/jquery-ui.css" type="text/css" media="screen"/>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="wrapper">
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#big_table').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": '<?php echo base_url(); ?>moderator/User/datatable',
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"iDisplayStart ":20,
"oLanguage": {
"sProcessing": "<img src='<?php echo base_url(); ?>assets/images/ajax-loader_dark.gif'>"
},
"fnInitComplete": function() {
//oTable.fnAdjustColumnSizing();
},
'fnServerData': function(sSource, aoData, fnCallback)
{
$.ajax
({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
});
}
} );
} );
</script>
<h1>Subscriber management</h1>
<?php echo $this->table->generate(); ?>
</div>
</body>
</html>
i used this code for datatable.
http://www.ahmed-samy.com/php-codeigniter-full-featrued-jquery-datatables-part-2/
The code uses mysql_real_escape_string() in library so it is deprecated.
You have to remove mysql_real_escape_string() from the code and use your custom code.
Otherwise you must use mysqli driver for codeigniter.
Then you can use mysqli_real_escape_string().
CodeIgniter switching driver from mysql --> mysqli
Update: Added Angel's solution below.
$sSearch =$this->ci->db->escape_like_str($this->ci->input->post('sSearch'));

uncaught exception: Call to StartUpload failed in uploadify integration with codeigniter

i have integrated uploadify with codeigniter.i can't able select images while clicking the select photos.
MY View file
<!DOCTYPE HTML>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<title>Uploadify V3 & CodeIgniter</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Capsone-System2" >
<!-- Styles -->
<link href="/assets/bootstrap/css/bootstrap.min.css" type="text/css" media="screen" rel="stylesheet"/>
<link href="<?php echo base_url;?>assets/js/jquery/uploadify_31/uploadify.css" type="text/css" media="screen" rel="stylesheet"/>
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<!-- Main Content -->
<div class="container">
<h1 class="page-header">Uploadify V3 & CodeIgniter</h1>
<p>This is a simple tutorial demo showing Uploadify V3 working with CodeIgniter 2.1.2</p>
<?php echo form_open_multipart(); ?>
<ul class="unstyled">
<li>
<?php echo form_upload('userfile','','id="userfile"'); ?>
<?php echo (isset($error)) ? $error : ''; ?>
</li>
<li>
<?php echo form_button(array('content'=> 'Upload', 'id'=>'upload-file', 'class'=>'btn btn-large btn-primary')); ?>
</li>
</ul>
<?php echo form_close(); ?>
</div>
<!-- End Of Main Content -->
<!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>-->
<!--<script>window.jQuery || document.write('<script src="<?php echo base_url;?>assets/js/jquery/jquery-1.8.0.min.js"></script>')</script>-->
<script src="<?php echo base_url;?>assets/js/jquery/uploadify_31/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
<!--<script src="<?php echo base_url;?>assets/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>-->
<script type="text/javascript">
$(document).ready(function () {
var base_url = '<?php echo base_url; ?>';
alert(base_url);
$('#upload-file').click(function (e) {
e.preventDefault();
$('#userfile').uploadify('upload', '*');
alert(base_url);
});
$('#userfile').uploadify({
'debug':true,
'auto':false,
'swf': base_url + 'assets/js/jquery/uploadify_31/uploadify.swf',
'uploader': base_url + 'uploadify_v3/do_upload',
'cancelImg': base_url + 'assets/javascript/jquery/uploadify_31/uploadify-cancel.png',
'fileTypeExts':'*.jpg;*.bmp;*.png;*.tif',
'fileTypeDesc':'Image Files (.jpg,.bmp,.png,.tif)',
'fileSizeLimit':'2MB',
'fileObjName':'userfile',
'buttonText':'Select Photo(s)',
'multi':true,
'removeCompleted':false,
'onUploadError' : function(file, errorCode, errorMsg, errorString) {
alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
}
});
});
</script>
</body>
</html>
My Controller File
I have error uncaught exception: Call to StartUpload failed
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* #property CI_Upload $upload
*/
class Uploadify_v3 extends CI_Controller
{
public $view_data = array();
private $upload_config;
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->helper(array('url', 'form'));
$this->load->view('uploadify_v3', $this->view_data);
}
public function do_upload()
{
$this->load->library('upload');
$image_upload_folder = FCPATH . '/uploads';
if (!file_exists($image_upload_folder)) {
mkdir($image_upload_folder, DIR_WRITE_MODE, true);
}
$this->upload_config = array(
'upload_path' => $image_upload_folder,
'allowed_types' => 'png|jpg|jpeg|bmp|tiff',
'max_size' => 2048,
'remove_space' => TRUE,
'encrypt_name' => TRUE,
);
$this->upload->initialize($this->upload_config);
if (!$this->upload->do_upload()) {
$upload_error = $this->upload->display_errors();
echo json_encode($upload_error);
} else {
$file_info = $this->upload->data();
echo json_encode($file_info);
}
}
}
/* End of file uploadify_v3.php */
/* Location: ./application/controllers/uploadify_v3.php */
I have spent more time..still now i can't fix this error..please help me.
I too had the same problem, it was a security issue because I was hosting the flash .swf file on a separate domain eg: static.mysite.com
Make sure your swf file and post handler script are hosted on the same domain that you are accessing the site from.
Or if you need to add cross domain posting then see here:
http://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html

Ajax div refreshing

I have a problem with AJAX , I cant find a good solution to refresh only my div "chatwindow" every second. I have tried many posts from stackoverflow and from google.
Can someone help me... to make this.
So far my code
<!DOCTYPE HTML>
<?php
include 'config.php';
?>
<html>
<head>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</script>
</head>
<body>
<div class="container">
<div id="chatwindow">
<?php
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
</div>
<div class="inputMessage">
<form method="post">
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="submit" value="verstuur" name="submit"/>
<input type="text" value="" name="username" />
</form>
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
</div>
</div>
</body>
</html>
[1]: http://chaotix.nl/chat/ "chat"
first you have to download latest jquery file from http://code.jquery.com/jquery-1.7.1.js
put this
<script type="text/javascript" src="jquery-1.7.1.js"></script>
under the head section
now put below code after <script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function(){
$.ajax({
url: 'chat.php',
type: "POST",
data: "",
cache: true,
success: function(response){
$("#chatwindow").html(response);
}
}, 1000);
});
</script>
you should extract php code form chatwindow div into another file and call it with AJAX and setInterval function every second.. if you wish to do it in this way.
This would be
chat.php
<?php
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
Then you would have your main file from which you would call ajax and refresh div:
<!DOCTYPE HTML>
<?php
include 'config.php';
?>
<html>
<head>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</script>
</head>
<body>
<div class="container">
<div id="chatwindow">
</div>
<div class="inputMessage">
<form method="post">
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="submit" value="verstuur" name="submit"/>
<input type="text" value="" name="username" />
</form>
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
</div>
<script type="text/javascript">
$(document).ready(function(){
setInterval ( "get()", 1000 );
});
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatwindow").html(data);
}
});
}
</script>
</div>
</body>
</html>
Try this one
<html>
<head>
<script langauge="javascript">
var counter = 0;
window.setInterval("refreshDiv()", 5000);
function refreshDiv(){
counter = counter + 1;
document.getElementById("test").innerHTML = "Testing " + counter;
}
</script>
</head>
<body>
<div id="test">
Testing
</div>
<div id="staticBlock">
This is a static block
</div>
</body>

Resources