Multiple Delete using JQuery Ajax and Code Igniter - javascript

I am currently working on a program that uses php jquery and bootstrap, I want to delete multiple data using checkbox. I search and found out that it must use AJAX to passing the paramater from view to controller. The Jquery work find and can get the value from checkbox. But when I use Ajax, the button not working. Nothing change. Please help me to find the problem on my code. Thank you
My Controller
public function hapusbeberapa()
{
$this->model_security->getsecurity();
$this->load->model('model_barang');
$arr = $this->input->post('data');
//$arrcode= json_encode($arr);
foreach($arr as $id)
{
$query = $this->model_barang->getID($id);
if($query->num_rows()>0)
{
$this->model_barang->getdelete($id);
//$this->session->set_flashdata('info',"Data Berhasil Dihapus");
}
}
}
My Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_barang extends CI_model {
public function getdelete($key)
{
$this->db->where('IDBarang',$key);
$this->db->delete('tBarang');
}
public function getID($key)
{
$this->db->where('IDBarang',$key);
$query = $this->db->get('tbarang');
return $query;
}
}
My View
<script src="<?php echo base_url();?>http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnhapus").click(function(){
var favorite = [];
$.each($("input[name='checkboxlist']:checked"), function(){
favorite.push($(this).val());
});
$.post("<?php echo site_url(barang/hapusbeberapa) ?>"+actMult, {data:favorite}););
});
});
</script>
</script>

use your script as:
<script type="text/javascript">
$(document).ready(function() {
$("#btnhapus").click(function(){
var favorite = [];
$.each($("input[name=checkboxlist]:checked"), function(){
favorite.push($(this).val());
});
$.post("<?php echo site_url(/barang/hapusbeberapa) ?>", {data:favorite}, function(returnData){
console.log(returnData);
});
});
});
</script>
it will work for sure,
the result will be same as you echo in controller's function, and check console log for check result, you can also check it by using alert(returnData) instead of console.log(returnData).
hope it helps

Try something like that:
var favorite = [];
$.each($("input[name='checkboxlist']:checked"), function(){
favorite.push($(this).val());
});
favorite = favorite.join();
$.post
...
In Controller
$arr = $this->input->post('data');
$arr = explode(',', $arr);

Related

Convert PHP variable to JQuery

Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery
View:
<?php
foreach ($muziek as $ms)
{
if ($ms->id == 2) {
echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
echo '</audio>';
}
}
foreach ($muziek as $ms)
{
echo '<br>';
echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
}
?>
</div>
<script>
$("input").click(function () {
var test = $(this).attr("id");
console.log(test);
//Here needs to be the foreach muziek
});
</script>
Muziek variable:
This is how i fill the music variable
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
return $muziek;
}
Does someone has an idea or show me how this can be done?
I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:
$.get( "base_url/your_controller/getAllMuziek" )
.done(function( muziek ) {
//Here needs to be the foreach muziek
$.each(muziek, function( index, value ) {
// whatever
});
});
with a simple modification to your method getAllMuziek:
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
header('Content-Type: application/json');
echo json_encode($muziek);
}
now when you make you ajax call you will get your result.
Convert $muziek into javascript array using json_encode
<script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>

Javascript - How to pull a WooCommerce variable in PHP?

I'm trying to execute some PHP code that is using the WooCommerce variable to get the order ID.
add_action('add_meta_boxes', 'gen_order_meta_boxes');
function gen_order_meta_boxes()
{
add_meta_box(
'woocommerce-order-gen',
__( 'TESTNG' ),
'order_meta_box_gen',
'shop_order',
'side',
'default'
);
}
function order_meta_box_gen()
{
echo '<button class="button save_order button-primary alert-mass">Generate</button>';
}
add_action('admin_footer', 'lolcats');
function lolcats()
{
$order = new WC_Order($post_id);
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
alert('<?php echo $order->get_order_number; ?>');
});
});
</script>
<?php
}
I can't seem to get it to return anything besides either null or 0.
Using something like this obviously works perfectly: window.location="dhlgen.php?order=1234"; because I'm trying to pass it through the URL to a PHP function which uses it later.
This also seems to fail, but it returns 'false':
function lolcats($post_id)
{
$order = new WC_Order($post_id);
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
var data = <?php echo json_encode($order->shipping_first_name); ?>;
alert(data);
});
});
</script>
<?php
}
Thank you.
Okay, I solved it.
function lolcats()
{
global $post;
$order_id = $post->ID;
?>
<script type="text/javascript" >
jQuery(document).ready(function($)
{
$(".alert-mass").click(function(e)
{
e.preventDefault();
alert('<?php echo $order_id; ?>');
});
});
</script>
<?php
}

Using values from PHP in JavaScript

I would like to use a value from PHP in JavaScript, but it's not working. I fetch data from a database and store it in a PHP variable and for conditional formatting. I need to also use the data in JavaScript for validation.
The value required by me is $date = date('Y-m-d'); If I pass the value by json Encode the alert function is not working...
$(document).ready(function()
{
alert("Hi");
var array = php print(json_encode($date));
});
Whereas if I just alert the function without...
var array = php print(json_encode($date)); ;
...it works fine.
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("Hi");
var array = '<?php print(json_encode($date)); ?>';
});
</script>
</head>
<body>
<form action="majorprocess.php">
<?php
$dbconn = mysql_connect('localhost', 'root','' );
if(!$dbconn)
{
die(mysql_error());
}
else
{
$date = date('Y-m-d');
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("<?php echo json_encode(date('Y-m-d')); ?>");
});
</script>
What is the resulting HTML?
There could be a PHP error outputting instead of valid javascript.
Try putting the PHP section at the top maybe?
When asking a question it is always best to post any outputs you are getting so people can help.
try this one
</head>
<body>
<form action="majorprocess.php">
<?php
$dbconn = mysql_connect('localhost', 'root','' );
if(!$dbconn)
{
die(mysql_error());
}
else
{
$date = date('Y-m-d');
}
?>
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var array = '<?php print(json_encode($date)); ?>';
alert(array);
});
</script>
You are using the PHP $date variable before setting its value. Make sure to move the php block before you try to output the date:
<?php
$dbconn = mysql_connect('localhost', 'root','' );
if(!$dbconn)
{
die(mysql_error());
}
else
{
$date = date('Y-m-d');
}
?>
<script type="text/javascript" src="assests/js/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("<?php echo json_encode($date) ?>");
});
</script>

Writing JSON array to html page with javascript after getting it from PHP query

I have a MySQL query that I pass to a PHP array. The PHP array is turned into a JSON array using json_encode. I am trying to then get this to print onto my html page. Here is what I have so far.
<?php
class db {
public $conn;
function dbLogin() {
$this->conn = new mysqli("1.2.3.4","user","pwd","db");
}
public function selectQuery() {
$this->dbLogin();
$query = "
SELECT *
FROM tekken_7_frame_data
";
echo "<pre>";
$resultArray = Array();
if ($result = $this->conn->query($query)) {
while ($row = $result->fetch_array()) {
$resultArray[] = $row;
}
}
echo "</pre>";
$resultJson = json_encode($resultArray);
}
}
$fData = new db();
$fData->selectQuery();
?>
<html>
<head>
</head>
<body>
<script>
var jsonArray = <?php echo $resultJson ?>;
document.write(jsonArray);
for (i = 0; i < jsonArray.length; i++) {
document.write(jsonArray[i][1]);
}
</script>
</body>
</html>
I've read up on other similar questions on StackOverflow with no luck; my html page is completely blank. I've tried placing json_econde(...) inside of the javascript variable jsonArray instead of in my PHP class. That didn't work either. I have also var_dump'd the PHP array with no issue (the whole thing displayed on the page), as well as placed the array in a PHP variable using json_encode, then echoed that array with no issue.
I have no idea how to access this JSON array. I ultimately want it in a table, but because this is my first time bridging the gap between PHP and Javascript, I figured that I would take it one step at a time so that I know exactly what is going on.
Try to change your function (don't use echo! but return something) to:
public function selectQuery() {
$this->dbLogin();
$query = "
SELECT *
FROM tekken_7_frame_data
";
$resultArray = Array();
if ($result = $this->conn->query($query)) {
while ($row = $result->fetch_array()) {
$resultArray[] = $row;
}
}
return json_encode($resultArray);
}
and downthere:
$fData = new db();
$resultJson = $fData->selectQuery();
The best way to get data from PHP into JavaScript is to use an asynchronous request (that is, "AJAX").
A javascript library greatly simplifies this process. Here's a rough example using AngularJS (http://angularjs.org).
json.php
// this file JUST needs to print JSON as string.
<?php
class db {
public $conn;
function dbLogin() {
$this->conn = new mysqli("1.2.3.4","user","pwd","db");
}
public function selectQuery() {
$this->dbLogin();
$query = "
SELECT *
FROM tekken_7_frame_data
";
$resultArray = Array();
if ($result = $this->conn->query($query)) {
while ($row = $result->fetch_array()) {
$resultArray[] = $row;
}
}
return json_encode($resultArray);
}
}
$fData = new db();
print $fData->selectQuery();
?>
myscript.js
// this will fetch your JSON string from the PHP file and
// set $scope.myData to a JS object.
// it sets $scope.myDataString to a JSON stringified format.
angular.module('myApp' [])
.controller('myController', function($http, $scope) {
var $scope.myData = {};
var $scope.myDataString = '';
function getMyData () {
$http.get('/json.php')
.success( function (data) {
$scope.myData = data;
$scope.myDataString = JSON.stringify(data);
})
.error(function (err) {
$scope.myData = {error: err};
$scope.myDataString = "ERROR: "+JSON.stringify(data);
})
}
getMyData();
}
mypage.html
<!-- include angular and your app's file.
make sure to link in your app and controller -->
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src='myscript.js'>
</head>
<body ng-app='myApp'>
<main ng-controller='myController as myCtrl'>
<div id='myOutput'>{{myDataString}}</div>
</main>
</body>
</html>

Joomla 2.5 component get json from external script

I would get a json (make from a db query) from a external script javascript.
my model:
<?php
defined('_JEXEC') or die();
jimport( 'joomla.application.component.modelList' );
class MediastoreModelList extends JModelList
{
function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id, type, designation', 'marque', 'prix');
$query->from('produits');
return $query;
}
}
my controller:
<?PHP
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class MediastoreController extends JController
{
public function getJson() {
$model = getModel();
$data = $model.getListQuery();
$document = JFactory::getDocument();
$document->setMimeEncoding('application/json');
JResponse::setHeader('Content-Disposition','attachment;filename="result.json"');
echo json_encode($data);
}
}
my javascript:
$.getJSON( "http://mediastore.dev/index.php?option=com_mediastore&task=getJson", function(data) {
console.log(data);
});
but the getJSON fails.
What's wrong ?
Thanks
Your controller code will throw PHP errors. It has to look like:
public function getJson() {
$model = $this->getModel();
$data = $model->getItems();
$document = JFactory::getDocument();
$document->setMimeEncoding('application/json');
echo json_encode($data);
JFactory::getApplication()->close();
}
Try to put the controller action to lowercase. I would also replace the $ with jQuery in your ajax call.
To see what is actually in the response of the ajax call I suggest to use firebug or the chrome developer console which will display the whole response and then you will find out very quick where the problem is.

Categories