How i can list one rows with foreach? - javascript

I have one question for you.
Have this code right now:
<?php
use yii\helpers\Url;
use yii\helpers\Html;
use yii\web\JsExpression;
?>
<form action="<?= Url::to(['/worker/equipment/updatecol']) ?>" id="editcol" method="POST">
<div class="form-group">
<?php foreach($columns as $column) { ?>
<label >Edit title</label>
<input type="text" class="form-control" value="<?= $column->equipment_column_title ?>" name="equipment_column_title" placeholder="Put name.." />
<?php } ?>
</div>
<div class="form-group">
<?php foreach($columns as $column) { ?>
<label>Edit type</label>
<select class="form-control" name="equipment_column_type">
<option value="1" <?php if ($column->equipment_column_type==1) echo "selected='selected'"?>>Int</option>
<option value="2" <?php if ($column->equipment_column_type==2) echo "selected='selected'"?>>Varchar</option>
<option value="3" <?php if ($column->equipment_column_type==3) echo "selected='selected'"?>>Date</option>
<option value="3" <?php if ($column->equipment_column_type==4) echo "selected='selected'"?>>File</option>
</select>
<?php } ?>
</div>
<input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
<?php foreach($columns as $column) { ?>
<input type="hidden" name="column" value="<?= $column->equipment_column_id ?>" />
<?php } ?>
<button type="submit" class="btn btn-primary">Update column</button>
</form>
</div>
This is my form for edit choosen column right?
Its yii2 framework and now my problem. This is form for editing my columns, but i dont want list all of fields, but one field i wanna edit. How i do it?
This function is my form controller:
public function actionUpdatecolumnform()
{
$columns = EquipmentColumn :: find() -> all();
return $this->renderAjax('_editcol',['columns'=>$columns]);
}
And this i have for updating columns:
public function actionUpdatecol(){
$model = EquipmentColumn::findOne($_POST['id']);
$model -> equipment_column_title = $_POST['equipment_column_title'];
$model -> equipment_column_type = $_POST['equipment_column_type'];
$model -> update();}
Now we going for jquery, where i have modal.
$('.editcolumn').click(function()
{
var essay_id = $(this).data('id');
$.ajax({
cache: false,
type: 'POST',
url: '".Url::to(['/worker/equipment/updatecolumnform'])."',
data: 'id='+essay_id,
success: function(data)
{
console.log(data);
$('#update_col').modal('show');
$('#edit_col').html(data);
}
});
});
$('#editcol').submit(function(){
var th=$(this);
console.log(th);
$.ajax({
url: '".Url::to(['/worker/equipment/updatecol'])."',
type: 'POST',
data: th.serialize(),
error: function(data,status,text) {alert(text);},
success: function(data) {
var n=noty({
text: '".Yii::t('app', 'Type was saved')."',
type:'success',
layout: 'topCenter',
animation: {
open: 'animated bounceInLeft', // Animate.css class names
close: 'animated bounceOutLeft', // Animate.css class names
easing: 'swing', // unavailable - no need
speed: 500 // unavailable - no need
}
})
}
})
})
This two part of jquery scripts i using for submit edited fields.
My question is: This code list all of columns with titles and types, but i want list only one column with title and type which i want edit.
Thanks for the help :)
I think there is a problem with foreach, but im not sure. :)

You update for given id but render all. With foreach you see all of records. If you want to see just the edited one data record, send one data to view.
$columns = EquipmentColumn::model()->findAllByPk($id);
With that code you get all the infos by given id which belongs to changed record.

Related

Ajax is not working when I fetch data from MySQL

I'm building an ecommerce.and for this I'm fetching data products from database, I want to let people add products in cart without refreshing the page, I have tried AJAX but I don't know why but it works only when data is not in a loop, I'm in PHP, and MySQL.
Code:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="upcart(<?php echo $list['id']; ?>)">
</form>
<?php
}
?>
<script>
$(document).ready(function() {
function upcart(id){
e.preventDefault();
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId"+ id).serialize(),
// dataType: "text",
success: function (response) {
alert("success");
}
// return false;
});
};
});
</script>
Use events instead of manually calling the javascript function.
We then don't need to generate id's for the forms since it we will have access to the correct form in the callback.
The PHP part:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" class="some-form-class">
<input type="hidden" name="name" value="value" />
<input type="submit" />
</form>
<?php
}
?>
The JS part:
<script>
$(document).ready(function() {
// Bind the forms submit event
$('.some-form-class').on('submit', function (event) {
event.preventDefault();
// Here we can use $(this) to reference the correct form
$.ajax({
method: "POST",
url: "data.php",
data: $(this).serialize(),
success: function (response) {
alert("success");
}
});
});
});
</script>
NOTE: Magnus Eriksson answer is far cleaner
since function upcart(id) is not in the global scope, onclick="upcart(<?php echo $list['id']; ?>)"> will fail due to the missing function
You need to declare that function in the global scope
Also, you need to prevent the form submission properly
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="return upcart(<?php echo $list['id']; ?>)">
</form>
<?php
note the return upcart .... - very important
NOT INSIDE $(document).ready(function() { since you don't need to wait for document ready to declare a function!
function upcart(id) {
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId" + id).serialize(),
success: function (response) {
alert("success");
}
});
return false; // to prevent normal form submission
}

How to get CSS on-off button value in PHP page?

Well,
I have this code which generate CSS on-off button in a php while loop:
<div class="onoffswitch">
<input type="hidden" name="hiddenID" value="<?php echo $id; ?>">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch<?php echo $i ?>" <?php echo $status; ?>>
<label class="onoffswitch-label" for="myonoffswitch<?php echo $i; ?>">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
When the on-off button changes then I am calling a PHP page using jQuery/Ajax.
jQuery/Ajax Code:
$(document).ready(function () {
$(".onoffswitch").change(function() {
var hiddenID = $(this).find("[name='hiddenID']").val()
var status = $('.onoffswitch-checkbox').val();
$.ajax({
type: 'post',
url: 'changeInlineData.php',
data: {
'id' : hiddenID,
'status' : status,
},
dataType : 'html',
success: function ( result ) {
$('.validation_msg').html(result);
}
});
});
});
Here you can see I just pass 2 key which is id and status in a php page. Now in php page I see the id value only not status value. Everytime status key is showing 0. It's should be 0 or 1.
PHP page:
<?php
echo $id = (int) $_POST['id'];
echo $status = (int) $_POST['status'];
Can you tell me what I am doing wrong?
Update:
I see in console log network tab that is showing status:on always if I toggle the button to on or off!!
Form Data
id:2203
status:on
You have to take value of checked checkbox. Change your status var in jquery as below :
var status = $('.onoffswitch-checkbox:checked').val();

Can I use php and javascript create form edit data?

I want to create form for edit data from MySQL with javascript. when I click link Edit it will show edit form for edit data.
This is from and php code for show data.
<form id="form-edit" method="post">
<?php
$sql = "SELECT * FROM comment WHERE question_id = $question_id ORDER BY id DESC";
$r1 = mysqli_query($link, $sql);
while($cm = mysqli_fetch_array($r1)) {
$comment_id = $cm['id'];
echo '<section class="section-comment">';
echo '<span class="commentator">' .$cm['user_id'] . '</span>';
echo $cm['detail'];
// This is link Edit
echo 'Edit';
echo $comment_id; //This can show correct comment_id
?>
<div id="form-edit-dialog">
<input type="text" name="user_id" value="<?php echo $user_id ?>" readonly > <br>
//I add this line for check comment_id but it show max comment_id to min when I open and close form
<input type="text" name="id" value="<?php echo $comment_id ?>" readonly > <br>
<textarea name="detail"></textarea><br>
<button type="submit" id="submit-edit">Submit</button>
<input type="hidden" name="comment_id" id="comment-id">
}
</form>
</div>
I write code java script like this.
$(function() {
$('a.edit-comment').click(function(event) { //Click link Edit
$('#form-edit')[0].reset();
event.preventDefault();
var t = "Edit Comment";
$('#form-edit-dialog').dialog({
width: '600px',
title: t,
modal: true,
position: { my: "center", at: "center", of: window}
});
//set value for hidden
$('#comment-id').val($(this).attr('edit-id'));
});
$('#submit-edit').click(function() {
$('form#form-edit').ajaxForm({
url: 'save-edit.php',
type: 'post',
dataType: 'script',
beforeSend: function() {
$.blockUI({message:'<h3>Sending data...</h3>'});
},
complete: function() {
$.unblockUI();
}
});
});
});
PHP can list all comment and show comment_id correctly but when I click at Edit , it show max number of comment_id and when I close form and click Edit again. The comment_id will reduce comment_id number untill no comment_id.
Can I use php and javascript create form edit data or I have to send data to new page?
if the user has the right to comment it means he is logged, so basically you can get the id from session, cookie; doesn't make sens to extract here the user id OR you can make the check if he has the right to comment ( user_id is same with session one).
just make the switch between and like this:
<
<div id="showtext<?php echo $comment_id ?>" >
<span id="comment<?php echo $comment_id ?>"><?php echo $cm['detail'] ?></span>
Edit
<div>
<!-- this is invisible at start -->
<div id="showedit<?php echo $comment_id ?>" style="display:none">
<textarea id="edittext<?php echo $comment_id ?>"><?php echo $cm['detail'] ?></textarea>
Save comment
</div>
and javascript to toggle views:
$('.edit-comment').click(function() {
var id=$(this).attr("id");
$("#showedit"+id).show();
$("#showtext"+id).hide();
});
and to submit
$('.submit-comment').click(function() {
var id=$(this).attr("id");
var comment=$("#edittext"+id).val();
//send the data via ajax with parameters id and comment to alter the row, in php add the user id from session, cookie and on success:
//replace the old text
$("#comment"+id).html(comment);
//and make the switchback
$("#showedit"+id).hide();
$("#showtext"+id).show();
})

AJAX not submitting fom

I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});

Ajax loaded comment not working

My php file loops out each blog post in my database and also creates the comments section. The blogs post great. When I comment on the most recent blog post, the comment does not appear but it seems to add a line as the space expands, just does not include the comment. When I comment on the first post, it works great and exactly as expected. I can't figure out how to correct it. I thought it was a matter of add a .closest to the comment-block selector but that didn't seem to do the trick.
I appreciate any help or feedback!
PHP/HTML
<?php // retrive post
include('php/config.php');
include ('php/function.php');
dbConnect();
$blog_query = mysql_query(
'SELECT *
FROM Blog
ORDER BY DATE DESC');
$date = date_create($row['DATE']);
while($row = mysql_fetch_array($blog_query)): ?>
<div class="post">
<h2><?php echo $row['TITLE']?></h2>
<h3><?php echo date_format($date, 'l, F j, Y')?></h3>
<p><?php echo $row['CONTENT']?></p>
</div>
<h2>Comments.....</h2>
<div class="comment-block">
<?php // retrieve comments with post id
$comment_query = mysql_query(
"SELECT *
FROM Comments
WHERE BID = {$row['ID']}
ORDER BY CID DESC
LIMIT 15") or die(mysql_error());
while($comment = mysql_fetch_array($comment_query)):?>
<div class="comment-item">
<div class="comment-post">
<h3><?php echo $comment['UNAME'] ?> <span>said....</span></h3>
<p><?php echo $comment['COMMENT']?></p>
</div>
</div>
<?php endwhile?>
</div>
<h2>Submit new comment</h2>
<!--comment form -->
<form id="form" method="post">
<div>
<input type="hidden" name="BID" value="<?php echo $row['ID']?>">
<label> <span>Display Name: *</span>
<input id="uname" type="text" tabindex="1" name="commentName" required />
</label>
</div>
<div>
<label> <span>Comment: *</span>
<textarea id="textarea" placeholder="Enter your comment here..." tabindex="2" name="commentMessage" required></textarea>
</label>
</div>
<div>
<input type="submit" id="submit" value="Submit Comment">
</div>
</form>
<?php endwhile?>
</div>
Jquery/Ajax:
var form = $('form');
var submit = $('#submit');
form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'php/ajaxcomment.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(800);
$('.comment-block').append(item);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
ajajcomment.php
<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
include('config.php');
include('function.php');
dbConnect();
if (!empty($_POST['commentName']) AND !empty($_POST['commentMessage']) AND !empty($_POST ['BID'])) {
$name = mysql_real_escape_string($_POST['commentName']);
$comment = mysql_real_escape_string($_POST['commentMessage']);
$BID = mysql_real_escape_string($_POST['BID']);
mysql_query("
INSERT INTO Comments
(UNAME, BID, COMMENT)
VALUES('{$name}', '{$BID}', '{$comment}')");
}
?>
<div class="comment-item">
<div class="comment-post">
<h3><?php echo $name ?> <span>said....</span></h3>
<p><?php echo $comment ?></p>
</div>
</div>
<?php
dbConnect(0);
endif?>
What does "php/ajaxcomment.php" return when you post a comment? Pure HTML?
I'd make the "php/ajaxcomment.php" return JSON, for example:
<?php
/*
here you do what ever you do now,
Insert the new comment to database, etc
*/
// Then you return the inserted data:
$data = array(
'UNAME' => $username,
'COMMENT' => $comment,
);
header('Content-Type: application/json');
print json_encode( $data );
?>
..and change the ajax:
...
...
success: function(data){
var commentItem = $('<div/>').addClass('comment-item');
var commentPost = $('<div/>').addClass('comment-post');
var user = $('<h3/>').html( data.UNAME +'<span>said...</span>' );
var comment = $('<p/>').html( data.COMMENT );
commentItem.html( commentPost.html( user + comment ) ).hide().fadeIn(800);
$('.comment-block').append(commentItem);
// reset form and button
form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
...
...

Categories

Resources