why this jquery script is not working Code igniter - php

i am working in a code igniter .. i am making five rows ..actually i am doing is that the options which are display in the 2nd select box based on the first select box ..
if i dont make five rows with the loop then script is working fine but if i put them in a loop ..selection dont work .. in firebug its give me response false and saying that
localhost/......./controller/get_items/undefined...
i dont know whats wrong in that code
<?php
for ($i = 0; $i < 5; $i++) {
?>
<?php echo form_dropdown('cat_id', $records2, '#', "id='category_".$i."'");?>
<?php echo form_dropdown('item_id', $records3, '#', "id='items_".$i."'"); ?>
<script type="text/javascript">
// <![CDATA[
$(document).ready(function()
{
for (var i= 0; i<5; i++)
{
$('#category_'+ i).change(function()
{
$('#items_'+ i > option").remove();
var category_id = $('#category_'+ i).val();
$.ajax({
type : "POST",
url : "stockInController/get_Items/"+category_id,
success : function(items)
{
$.each(items,function(item_id,item_name)
{
var opt = $('<option />');
opt.val(item_id);
opt.text(item_name);
$('#items_'+ i).append(opt);
});
}
});
});
}
}

As far as i understand your problem here is the solution.
Yor function should look like this
function getCategories(obj)
{
var category_id = obj.id ;
$.ajax({
type : "POST",
url : "stockInController/get_Items/"+category_id,
success : function(data)
{
$('#'+id).html(data);// here you should provide 2nd dropdown id so that it can be replaced
}
});
}
Controller method
function get_Items()
{
$id = $this->uri->segment(3);
$data['result'] = $this->somemodel->getProducts($id);
$this->load->view('options',$data);
}
View
options.php
foreach($result as $row){
?> <option value = "<?php echo $row->item_id?>"><?php echo $row->item_name?></option><?php
}
And on each dropdown of categories you should call this function.
<?php echo form_dropdown('cat_id', $records2, '#', "id='category_".$i."' onclick = "getCategories(this)"");?>

Related

Changing content of multiple elements with same name

I have some <td name="puja"> elements I want to update every 5 seconds deppending on their id so they contain the greatest bid(puja) for it's auction(subasta). For that, I'm trying to use AJAX and PHP.
Html looks like this (relevant code):
<?php
foreach ($subastas as $subasta) { ?>
<td name="puja" id="<?php echo $subasta["oid_s"] ?>"> </td>
As I have multiple elements to update, I tried getting all the elements and then running my AJAX function for every one of them.
AJAX:
$(document).ready(function()
{
var ids = document.getElementsByName("puja");
for (var i=0; i<ids.length;i++){
var id = ids[i].id;
$.ajax({
url : 'includes/getPuja.php',
data:{"oid_s":id},
success: function(data){
$(`#${id}`).html(data);
}
});
};
});
Finally, in my php file I just make a database connection, get the desired value , and echo it.
getPuja.php (relevant code):
$puja = 0;
if(isset($_POST["oid_s"])) {
$oid_s = $_POST["oid_s"];
$consultaPuja='SELECT pujado from (SELECT * from pujas WHERE OID_S = :oid_s ORDER BY pujado DESC) where rownum = 1';
try {
$stmtPuja = $conexion->prepare($consultaPuja);
$stmtPuja -> bindParam(':oid_s', $oid_s);
$stmtPuja -> execute();
foreach ($stmtPuja as $fila) {
$puja = $fila["PUJADO"] ;
}
echo $puja;
} catch(PDOException $e) {
$_SESSION["excepcion"] = $e -> GetMessage();
header("Location: excepcion.php");
}
}
When I run it, the HTML is not modified.
I fixed my problem with the following code, now the values get updated every second:
$(document).ready(function(){
setInterval(getPuja, 1000);
function getPuja() {
$( '[name=puja]' ).each(function() {
var id = $( this ).attr('id');
$.ajax({
url : 'includes/getPuja.php',
method:"POST",
data:{oid_s:id},
success: function(data){
$(`#${id}`).html(data);
}
});
});
}
});

how to get values from database in codeigniter based on select box value without refreshing page?

Unable to get value from database in codeigniter. I tried to fetch data based on select box value(menu_code) without refreshing page using ajax but I got result undefined.
This my controller's code : login.php
public function get_menu_rights()
{
if (isset($_POST['name']))
{
$root_id = $this->input->post('menu_root_id');
$data['res'] = $this->login_model->get_menu_check($root_id);
// print_r($data['res']);
echo json_encode($data);
//$this->load->view('pages/role_rights',$data);
}
}
Below is my model code login_model.php
public function get_menu_check($root_id)
{
$this->db->select('menu_code,menu_name');
$this->db->from('create_menu as C1');
$this->db->where('C1.menu_root_id',$root_id);
$this->db->order_by('menu_code');
return $this->db->get()->result_array();
}
This is my view code role_rights.php
<form action="<?php echo base_url('login/get_menu_rights');?>" method="post">
<?php
print"<select class=\"form-control\" name=\"menu_root_id\" onchange=\"javascript:__doPostBack();\" id=\"menu_root_id\">"; ?> <option value="select">select</option>
<?php foreach($result as $res) { ?>
<option value="<?php echo $res->menu_code; ?>">
<?php echo $res->menu_name.'-'.$res->menu_code; ?>
</option>
<?php } ?>
</select>
</form>
</div>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
function __doPostBack()
{
var name = document.getElementById('menu_root_id').value;
var dataString='name='+ name;
$.ajax({
type:"post",
url:"<?php echo base_url('login/get_menu_rights'); ?>",
data:dataString,
cache:false,
dataType: 'json',
success: function(data)
{
var id = data[0];
var vname = data[1];
$('#output').html("<b>menu_code: </b>"+id+"<b> menu_name: </b>"+vname);
}
});
return false;
}
</script>
</div>
<div id="output"></div>
Hope this will help you :
Replace
$root_id = $this->input->post('menu_root_id');
with
$root_id = $this->input->post('name');
Your controller's get_menu_rights method should be like this :
public function get_menu_rights()
{
$root_id = $this->input->post('name');
if(! empty($root_id))
{
$data = $this->login_model->get_menu_check($root_id);
// print_r($data);
echo json_encode($data);
exit;
}
}
Your ajax success function should be like this :
success: function(data)
{
var html = '';
$.each(data,function(k,v){
alert(v);
html += "<b>menu_code: </b>"+v.menu_code+"<b> menu_name: </b>"+v.menu_name
});
$('#output').html(html);
}
There are a few things I noticed
$data is an undefined array & you are settings the result array returned by the model function to it's 'res' key
dataString is not a json neither it's a js array that you are sending
since you used json_encode, you need to use JSON.parse(data) in the ajax success
if you do have the result in $data['res'], then you need to do something like this - data=JSON.parse(data)['res']; now you can get id from data[0]
I think the query return empty please try this Code.....
public function get_menu_check($root_id)
{
$data = $this->db->select('C1.menu_code,C1.menu_name')
->from('create_menu as C1')
->where('C1.menu_root_id',$root_id)
->order_by('C1.menu_code')
->get();
if($data->num_rows() >= 0)
return $data->result_array();
else
return false;
}

AJAX Form Submission Not Querying PHP

Trying to use AJAX to submit form data to a PHP file. Everything in the code seems to work except for a call to the PHP file.
I setup a Java Alert() on the PHP file and it never alerts.
I am sure it is an issue with the AJAX code but I don't know it well enough to figure out what is going wrong.
The AJAX Call:
$(document).on('click','.addItem',function(){
// Add Item To Merchant
var el = this;
var id = this.id;
var splitid = id.split("_");
// Add id's
var addid = splitid[1]; // Merchant ID
var additem = splitid[2]; // Item ID
// AJAX Request
$.ajax({
url: "jquery/addItem.php",
type: "POST",
data: { mid : addid , iit : additem },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(300, function(){
$(this).remove();
});
}
});
});
The HTML Form Call Within a Table:
<span class='addItem' id='addItem_<?php echo $m; ?>_<?php echo $list['id']; ?>' >Add Item</span>
Ok Simple PHP code that it calls to with some alerts for testing:
<?php
require_once("../includes/constants.php");
require_once("../includes/functions.php");
$iid = filter_input(INPUT_POST, 'iit', FILTER_SANITIZE_STRING); // Item ID
$mid = filter_input(INPUT_POST, 'mid', FILTER_SANITIZE_STRING); // Merchant ID
$slot = 0;
$slot = getMerchSlot($mid);
?>
<script>
alert ("Slot Value: <?php echo $slot; ?>");
</script>
<?php
$result = $pdoConn->query("INSERT INTO merchantlist (merchantid, item, slot)
VALUES
('$mid', '$iid', '$slot') ");
if ($result) {
?>
<script>
alert("Looks like it worked");
</script>
<?php
}
echo 1;
?>

Passing 2 datas from AJAX to PHP

So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;

How to code like this kind of output?When I click a specific link it will show some form(not sure if it is form)

How to code this? when I hover my name It pop outs like a form but I think its not a form
I want exactly the same like this because I want to happen in my page when I hover my name it has a value of id and send it via ajax to the php then the php script queries the id and return its other details then the other details will display like in the image I already have a function and a php code the only I need is how to do like this image
code for js function:
function searchWarriors() {
var id = $("#name").val();
$.ajax({
url: "retrieve_result.php",
type:"GET",
datatype:"json",
data: {id: id},
success: function(data) {
var toAppend = '';
if(typeof data === "object"){
for(var i=0;i<data.length;i++){
var warrior = data[i];
toAppend += '<ul class="ul">';
toAppend += '<li>'+data[i]['loc']+'</li>';
toAppend += '<li>'+data[i]['email']+'</li>';
toAppend += '<li>'+data[i]['sex']+'</li>';
toAppend += '</ul>';
}
$(".ul").remove();
$("#details").append(toAppend);
}
}
});
return false;
}
Code for my PHP:
<?php
header("Content-Type: application/json");
include 'functions/class.php';
$db = new DB();
$result = $db->getDetails($_GET['id']);
$details = array();
foreach($result as $values){
$details[] = $names;
}
echo json_encode($details);
?>
Code for my html to call function
<?php
foreach($result as $id){
//I don't know if this is right
echo'<a id="name" href="myphpcode.php"?id='.$id['user_id'].'>'.$id['name'].'</a>';
}
?>
<div id="details">
</div>
Easiest way to do this is to normally create exactly how you want the pop-up to look in a php script, then use jQuery and call the script with $("#Popup-id").load(script-url.php?getvar=1). The div element will need a high z-index in order to show on top of the screen.

Categories