The given snippet has a javascript function and a table in which I want to show content of each row using a modal.
But the problem is when I am using alert in middle for debugging for any number of row when I click in view button it always shows the first value of m_id but it must show the corresponding values. $v object is returning expected data only no problem in that.
I need help since I am just a beginner in ajax.
<script type="text/javascript">
function view_message(){
//alert("aa gyaksjhfjxvhk");
var m_id = document.getElementById('m_id').value;
var c_name = document.getElementById('c_name').value;
var message = document.getElementById('message').value;
alert(m_id);
//alert(loc);
$.ajax({
type: "POST",
url: "view_message.php",
data:
{ 'm_id' :m_id,
'c_name' : c_name,
'message' : message
},
success: function(data){
// alert("success");
$(".message_container").html(data);
}
});
}
</script>
foreach($v_message as $v)
{
echo '<tr>';
echo '<td>'.$v->time.'</td>';
echo '<td>'.$v->c_name.'</td>';
echo '<input id="m_id" name="m_id" value="'.$v->id.'" hidden />';
echo '<input id="c_name" name="c_name" value="'.$v->c_name.'" hidden />';
echo '<input id="message" name="message" value="'.$v->message.'" hidden />';
echo '<td data-toggle="modal" data-target="#myModal">';
echo ' <input type="button" id="view" onclick="view_message()" value="view"></input>';
echo '</td>';
echo '<td data-toggle="modal" data-target="#myModal1">
<span>Delete</span>';
echo '</td>';
echo '</tr>'; ?>
<div id="message_container">
</div>
change your selector $(.message_container) to $(#message_container)
modified code is below.
<script type="text/javascript">
function view_message(){
//alert("aa gyaksjhfjxvhk");
var m_id = document.getElementById('m_id').value;
var c_name = document.getElementById('c_name').value;
var message = document.getElementById('message').value;
alert(m_id);
//alert(loc);
$.ajax({
type: "POST",
url: "view_message.php",
data:
{ 'm_id' :m_id,
'c_name' : c_name,
'message' : message
},
success: function(data){
// alert("success");
$("#message_container").html(data);
}
});
}
</script>
because your selector is document, its find first element with target id, so always first row element return in result.in php code replace onclick="view_message()" with class="view-btn" and use my answer javascript,
<script type="text/javascript">
$(document).ready(function() {
var view_message = function(){
var row = $(this).closest('tr');
var m_id = $(row).find('#m_id').val();
var c_name = $(row).find('#c_name').val();
var message = $(row).find('#message').val();
alert(m_id);
}
$(".view-btn").on('click', view_message);
});
</script>
foreach($v_message as $v)
{
echo '<tr>';
echo '<td>'.$v->time.'</td>';
echo '<td>'.$v->c_name.'</td>';
echo '<input id="m_id" name="m_id" value="'.$v->id.'" hidden />';
echo '<input id="c_name" name="c_name" value="'.$v->c_name.'" hidden />';
echo '<input id="message" name="message" value="'.$v->message.'" hidden />';
echo '<td data-toggle="modal" data-target="#myModal">';
echo ' <input type="button" id="view" class="view-btn" value="view"></input>';
echo '</td>';
echo '<td data-toggle="modal" data-target="#myModal1">
<span>Delete</span>';
echo '</td>';
echo '</tr>'; ?>
<div id="message_container">
</div>
IDs must be unique in the document. See: stackoverflow.com/a/9454716/2181514.
Your for loop generates multiple items with the same id, so when you do $(#id you get the first one.
You can fix this by using classes and passing a reference to the current row:
Change
onclick="view_message()"
<input id="m_id" name="m_id"
to
onclick="view_message(this)"
<input class='m_id' id="m_id" name="m_id"
then:
function view_message(el){
var row = $(el).closest("tr");
var m_id = $(".m_id", row).val();
Update: typo - should have been $(el).closest, not $(this)
Example fiddle: https://jsfiddle.net/37tkgsnm/
html:
<tr>
<td><input class='m_id' value='123' /></td>
<td><button type="button" onclick="view_message(this);">click</button></td>
</tr>
js:
function view_message(el) {
var row = $(el).closest("tr");
alert($(".m_id", row).val())
}
Related
I was getting alert value after change function but after success function, I not getting any values
my ajax page
$(document).ready(function(){
$("#customer").change(function() {
var customer_type = $(this).find(":selected").val();
var dataString = 'customer_type='+ customer_type;
$.ajax({
url: 'http://localhost/capms_v3/ajax/getcust_type.php',
dataType: "json",
data: dataString,
cache: false,
success: function(customerData) {
alert(data);
alert("test");
if(customerData) {
var customer = [customerData];
customerData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.company_id+'</td>';
data+= '<td align="right">'+item.company_name+'</td>';
data+='</tr>';
$('.appendData').append(data);
});
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
});
});
my array values are not coming after the success function but in getcusttype page values was coming in an array
getcusttype.php
<?php
//header("Content-type:application/json");
include 'db.php';
$db=DbConnect();
if($_REQUEST['customer_type']) {
$sql = "SELECT company_id,company_name FROM ca_customer WHERE customer_type ='".$_REQUEST['customer_type']."'";
$result = mysql_query($sql) or die(mysql_error());
$data = array();
while( $rows = mysql_fetch_array($result) ) {
$data[] = $rows;
}
echo json_encode($data);
} else {
echo 0;
}?>
//var customer =[{"0":"1","company_id":"1","1":"Win Win
web","company_name":"Win Win web"},{"0":"7","company_id":"7","1":"New
Company","company_name":"New Company"},
{"0":"10","company_id":"10","1":"Murugan Super
Store","company_name":"Murugan Super Store"}];
after the success: function(customerdata) if I alert(data) values was getting alert I don't know what error I have made.
view
<select id="customer" name="customer_type" class="form-control">
<option value="">Select Customer Type</option>
<?php
foreach($all_ca_customer_type as $ca_customer_type)
{
$selected = ($ca_customer_type['customer_type_id'] == $this->input->post('customer_type')) ? ' selected="selected"' : "";
echo '<option value="'.$ca_customer_type['customer_type_id'].'" '.$selected.'>'.$ca_customer_type['customer_type_name'].'</option>';
}
?>
</select>
<tbody class="appendData">
</tbody>
not getting values after success function.if anybody face this problem help me.thanks in advance
Uncomment header("Content-type:application/json"); in getcusttype.php
It looks like your alert() function is referencing data Where does data come from? Try alert(customerData) in place of alert(data).
success: function(customerData) {
alert(data);
alert("test");
if(customerData) {
var customer = [customerData];
customerData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.company_id+'</td>';
data+= '<td align="right">'+item.company_name+'</td>';
data+='</tr>';
$('.appendData').append(data);
});
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
If you're looking to alert the row that your appending you should move the alert(data) call, as is, down into your forEach() block after you declare your data variable.
Ex:
customerData.forEach(function(item) {
var data = '<tr>';
data+= '<td colspan="4"> </td>';
data+= '<td align="right">'+item.company_id+'</td>';
data+= '<td align="right">'+item.company_name+'</td>';
data+='</tr>';
alert(data);
$('.appendData').append(data);
});
function uppp(id){
var eleme = "uploaded_image"+id;
alert(id);
var name = document.getElementById(id).files[0].name;
var form_data = new FormData();
var ext = name.split('.').pop().toLowerCase();
if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
}
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById(id).files[0]);
var f = document.getElementById(id).files[0];
var fsize = f.size||f.fileSize;
if(fsize > 2000000)
{
alert("Image File Size is very big");
}
else
{
form_data.append("file", document.getElementById(id).files[0]);
$.ajax({
url:"http://localhost/wat/admin/category/uppp/"+id,
method:"POST",
data:form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
},
success:function(data)
{
var x = document.getElementById(eleme);
x.style.color = 'green';
x.innerHTML= "done";
}
});
}
}
this function function is supposed to get the file name from the input control then post the details to a php file which will upload the name in the database. the function is working "selectively"... that is sometimes it works and sometimes it produces the error above... here is the php file from where the file name is taken... please help
while($row = mysqli_fetch_assoc($result)) {
$document_id= $row["document_id"];
$document_description = $row["document_description"];
$output .= "</tr>";
$output .= "<tr> ";
$output .= " <td class='text-center'><p class='nums'>".$count."</p></td>
<td>
<input type='text' name='' class='textdd' value= '".$document_description."' disabled>
</td>
<td word-wrap:break-word'>
<input type='file' name='file' id='$document_id' size='20' required />
</td>
<td>
<button name='$document_id' onclick='uppp(this.name)'>Upload</button>
</td>
<td id='uploaded_image$document_id' color='red'></td>
";
$output .= "</tr>";
$count++;
}
$output .= "<tr> <td> <input type = 'submit' value='Save Documents' class='btn btn-info'> </td> </tr> ";
$output.= " </tbody> </table>";
echo $output;
}
else{
$output .="<td class= 'noresults'> NO documents Found </td> </tr> ";
$output.= " </tbody> </table></form>";
echo $output;
i realized that i had elements from different tables with the same id on the same page . this was because of creating the ids dynamically from 1 to 100. so when the function is passed an id which belongs to two elements that`s when the error occurred.
i realized that when creating ids dynamically for elements the creation process should be as unique as possible
I have a problem when I'm trying to get the contents of a JavaScript Array and pass its value to a PHP Array Variable.
What I'm doing is that, when a user clicks a button, the value of the item clicked will be added to the javascript array and every time the javascript array updates, the PHP variable will also update and so the contents of the div displaying the contents of the PHP array. I'm not using forms for this matter but buttons
However, when I try to use the json_decode function to get the values of a JavaScript array, it's giving me a Message: undefined index: data error
I'm a beginner in JavaScript, jQuery and AJAX so please bear with me
This is my code:
<script>
// ARRAY VARIABLE WHERE ITEM VALUES WILL BE STORED
var food_item = new Array();
// FUNCTION TO BE TRIGGERED WHEN USER CLICKED THE BUTTON, GET THE ITEM'S VALUE AND ADD IT TO ARRAY
function addToTray(data){
food_item.push(document.getElementById(data).value);
dataString = food_item; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "main",
data: {data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
}
</script>
<body>
...
// LINE OF CODE RESPONSIBLE FOR FETCHING JAVASCRIPT ARRAY VALUES
$this->session->userdata['food_tray'] = json_decode($_POST['data']);
// DIV TO BE UPDATED
<div class="col-md-3 food-tray" id="food-items" style="margin-top: 7%">
<!--FOOD TRAY-->
<div class="panel-heading">
<h3 class="ft-header">Food Tray</h3>
</div>
<div class="panel-body">
<?php
$count_fi = count($this->session->userdata('food_tray'));
echo "<p>Your Items (" . $count_fi . ")</p>";
if($count_fi == 0){
echo "<p class='no-avail-list'>NO ITEMS ADDED IN FOOD TRAY</p>";
}else{
echo "<table class='table borderless'>";
for($i = 0; $i < $count_fi; $i++){
echo "<tr>";
echo "<td>" . $this->session->userdata['food_tray'][$i] . "</td>";
echo "<td>P 200.00</td>";
echo "<td><form method='post'><input type='number' name='qty' min='1' max='100' value='1'/></form></td>";
echo "</tr>";
}
echo "</table>";
echo "<a href='' class='btn btn-success' data-toggle='modal' data-target='#myModal'>
Add Friend</a>";
echo "<a href='".base_url()."index.php/CheckOut' class='btn btn-warning'>Proceed to Checkout</a>";
}
?>
</div>
</div>
...
<?php
foreach($query->result() as $row){
echo "<div class='col-lg-7'>";
echo "<div class='thumbnail'>";
$file_name = strtolower(preg_replace('/[^A-Za-z0-9\-.]/', '', $row->name));
/*if(file_exists(FCPATH . '/assets/images/main/food/' . $file_name . '.jpg')){
echo "<img src='".base_url()."/assets/images/main/food/".$file_name.".jpg' alt='' width='320px' height='100px'>";
}else{
echo "<img src='http://placehold.it/320x150' alt=''>";
}*/
echo "<img src='http://placehold.it/320x150' alt=''>";
echo "<div class='caption'>";
echo "<h5 class='pull-right'>₱ " . $row->price . "</h5>";
echo "<h5><a href='#'>" . $row->name . "</a></h5>";
echo "<h5>Calorie Count : " . ($row->calorie_count == NULL ? "Not Available" : $row->calorie_count) . "</h5>";
// BUTTON FOR `addToTray()` FUNCTION
echo "<button class='btn btn-primary' id='".$row->id."' value='".$row->name."' style='width:100%' onclick='addToTray(".$row->id.")'>Add to Tray</button>";
// var_dump($row->name);
echo "</div>";
echo "</div>";
echo "</div>";
}
?>
</body>
Anyone who knows how to solve this problem? Any help would be appreciated.
create your session as
$array = array ('food_tray' => json_decode($javascriptarray));
$this->session->set_userdata($array);
check if your javascript libraries are loaded in sources tab.
Im using this is an ID
$id = $row['id'];
echo "<input type='text' id='$id' value='$row["s_code"]'>";
How can I get that ID in javascript function? I want it in here...
var scode = $('#').val();
While loop..
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
$id = $row['id'];
echo "<input type='text' id='$id' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='comval' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqtyval'>";
echo "</td><td>";
echo "<input type='button' onclick='addthis()' value='Add!'>";
echo "</td></tr>";
}
Javascript
function addthis() {
var myID = '$id';
var scode = $("#"+myID).val();
alert(scode);
$.ajax({
type: 'POST',
url: 'insertsimplextoc_comp.php',
data: { simplexcode: scode },
});
}
Been stuck on this for over a week!
PHP:
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
$id = $row['id'];
echo "<input type='text' id='$id' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='comval' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqtyval'>";
echo "</td><td>";
echo "<input type='button' class='submit-scode' data-field-id='$id' value='Add!'>";
echo "</td></tr>";
}
Javascript (using jQuery click event):
$('.submit-scode').click(function(){
var field_id = $(this).attr('data-field-id');
var scode = $("#"+field_id).val();
$.ajax({
type: 'POST',
url: 'insertsimplextoc_comp.php',
data: { simplexcode: scode },
});
});
Untested, but it should work.
Add the id of the current loop as a parameter to the addthis function:
echo "<input type='button' onclick='addthis(\"$id\")' value='Add!'>";
Then grab the id when the function is called like so:
function addthis(myID)
{
var scode = $("#"+myID).val();
//etc
}
have to keep track of that dynamic id's
It you have that id then you can do something like this
var id="assign php varable";
var scode =$('#'+id).val();
I'm guessing you want it to be used in the addthis() function ?
In this case, you'll hve to give a similar class to all your readonly inputs.
Then, while clicking on the add button, you'll have to check for its parent <tr>
I made some example here : http://jsfiddle.net/captain_torche/frzadnbb/
Or, you could alteratively put the ID as a parameter of the addthis() function, like so :
echo "<input type='button' onclick='addthis(".$id.")' value='Add!'>";
Ok , I am finding something wrong with my Jquery and PHP & HTML code , everything used to work , but now event.Preventdefault isn't working , and my Jquery can't loop through the input fields to get the data of the forms ? where did I possibly go wrong ? below is my code
<?php
header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header ("Expires: Sat 26 Jul 1997 05:00:00 GMT"); // Date in the past
require_once ("../_includes/functions.php");
?>
<link rel="stylesheet" title="Style CSS" href="../_reports/report_assets/cwcalendar.css" type="text/css" media="all" />
<script src="../_js/jquery-1.6.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../_js/timer.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="../_reports/report_assets/calendar.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#select').click(function(event){
$(':checkbox').prop("checked", true);
event.preventDefault();
});
$('#deselect').click(function(event){
$(':checkbox').prop("checked", false);
event.preventDefault();
});
$('#add').click(function() {
var field = '<input class="project_fields" type="text" size ="30" name = field_settings[] /> ';
var checkbox = '<input class ="checkbox" type ="checkbox" name ="check_field[]" /> ';
var delete_link = '<a class ="delete_link" style="text-decoration:none;" href="#"> Delete field </a> <br /><br />';
var input = field + checkbox + delete_link;
$('#input_fields').append(input);
});
$('#project_fields_submit').click(function(event) {
event.PreventDefault();
var array_fields = new Array();
$('.checkbox').each(function() {
if($(this) .is(':checked')) {
array_fields.push('1');
alert('checked!!!');
}
else {
array_fields.push('0');
alert('not checked !!!')
}
});
$('#checkboxes').val(array_fields);
});
$('#edit_fields_submit').click(function(event) {
event.PreventDefault(); // this here doesn't work
var edit_fields = new Array();
$('.edit_check').each(function() {
if($(this) .is(':checked')) {
alert('checked !!!'); // doesn't alert anything after filling out the fields , though it used to
edit_fields.push('1');
}
else {
edit_fields.push('0');
alert('not checked !!!');
}
});
$('#edit_checkboxes').val(edit_fields);
});
var nextRowID = 0;
$('#add_edit').click(function() {
var id = ++nextRowID;
var new_field = '<input class ="class'+id+'" type="text" size ="40" name = edit_field_value[] value =""> ';
var new_checkbox = '<input class ="class'+id+'" type ="checkbox" name ="check_field[]" > ';
var delete_edit = '<a id ="'+id+'" class ="new_delete_edit" style="text-decoration:none;" href="#" > Delete field </a><br><br>';
var new_input = new_field + new_checkbox;
$('#new_input_fields').append(new_input);
$('#new_input_fields').append(delete_edit);
});
$('a.delete_edit').click(function(event) {
event.preventDefault();
var ID = $(this).attr('id');
var delete_field_id = 'edit_field'+ID;
var field_data = $('#'+ delete_field_id).val();
var project_id = $('#edit_project_id').val();
var string = {field : field_data, pid : project_id };
$.ajax({
type: "POST",
url: "_ajax/delete_field.php",
data: string,
success: function(data){
$('#'+ID).remove();
$('#'+delete_field_id).remove();
$('#new_check'+ID).remove();
}
});
});
$('.new_delete_edit').live('click', function(event) {
event.preventDefault();
var id = $(this).attr('id');
$('.class'+id).hide();
$('#'+id).hide();
});
});
</script>
<?php
if (isset($_GET['pid']) && isset($_GET['user_id'])) {
$id = $_GET['user_id'];
$pid = $_GET['pid'];
$show_id = $_GET['show_id'];
"
$query_settings ="SELECT project_settings FROM projects WHERE project_id ='$pid'";
$result_settings = mysql_query($query_settings);
$row_settings = mysql_fetch_array($result_settings,MYSQL_ASSOC);
if($row_settings['project_settings'] == NULL) {
echo "<h2> Project Settings </h2>";
echo "<br><br>";
echo " <b> Add fields </b>";
echo " ";
echo "<img id ='add' src='_assets/add.png' /><br><br><br>";
echo '<form action ="" method="post">';
echo'<input type="hidden" name="pid" value="'.$pid.'">';
echo "<input id ='checkboxes' type ='hidden' name ='checkboxes' value ='' >";
echo "<div id='input_fields'> </div>";
echo '<input id ="project_fields_submit" type ="submit" name ="project_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
echo "<br><br><br><br><p></p>";
}
else {
echo "<h2> This Project Settings </h2>";
echo "<br><br><br><br>";
echo "<b> Add fields</b> <img id ='add_edit' src='_assets/add.png' /><br><br><br>";
$fields_data = unserialize($row_settings['project_settings']);
$i = 0;
echo '<form action ="" method="post">';
echo'<input id ="edit_project_id" type="hidden" name="edit_project_id" value="'.$pid.'">';
echo "<div id='new_input_fields'> </div>";
echo "<input id ='edit_checkboxes' type ='hidden' name ='edit_checkbox' value ='' >";
foreach ($fields_data as $key => $value) {
if($value =="1") {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size ='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' checked /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
} else {
echo "<input id ='edit_field".$i."' class ='edit_data' type ='text' size='40' name = edit_field_value[] value ='".$key."' /> ";
echo "<input id ='new_check".$i."' class ='edit_check' type='checkbox' name ='edit_checkboxes' /> ";
echo "<a id ='".$i."' class ='delete_edit' style='text-decoration:none;' href='#'> Delete field </a><br><br>";
}
$i++;
}
echo '<input id ="edit_fields_submit" type ="submit" name ="edit_fields_submit" class="button" value ="Save Settings" /><br><br>';
echo '</form>';
}
echo '</div>';
echo '<div id="project-setting-results"></div><div class="clear"></div>';
echo '</div><!-- end fragment-6 -->';
}
?>
javaScript is case-sensitive. PreventDefault is undefined, use instead preventDefault where "this here doesn't work".
Use a debugging console when writing on javaScript!