The loop works fine, it display what it supposed to do, but there is a mysql update button of which updates only the first row value displayed:
$(document).ready(function() {
$("#update").click(function() {
var fname = $("#fname").val();
var lname = $("#lname").val();
var recordId = $("#recordId").val();
$.ajax({
url: 'update.php',
method: 'POST',
async: true,
data: {
fname: fname,
lname: lname,
recordId: recordId
},
success: function(response) {
alert(response);
}
});
});
});
<?php
$conn = new mysqli('localhost', 'root', '123456', 'lc');
$sql = "SELECT * FROM lc where customer='souhail'";
$result = $conn->query($sql);
// while ( $row=mysqli_fetch_assoc($result)) {
while($row = $result->fetch_array()) {
echo 'LC ID :<input type="text" id="fname" value="'.$row['element_6'].'"><br>';
echo 'Status :<input type="text" id="lname" value="'.$row['element_101'].'"><br>';
$recordId = $row['lc_id'];
echo '<input id="recordId" name="recordId" value="' . $recordId . '" >';
?>
<button type="button" style="background-color:<?php
if($row['element_101'] == '1'){
echo '#0000FFF';
}elseif ($row['element_101'] == '2'){
echo '#ffff00';
}elseif ($row['element_101'] == '3'){
echo '#00FF00';
}elseif ($row['element_101'] == '4'){
echo '#ffffff';
}
//echo $row['element_101'];
?>;color:#000000" id="update">Go Forward ></button>
<br><br>
<?php
} ?>
You must have unique IDs but instead wrap each set in a container and access relative tags:
$(".update").on("click", function() {
var $container = $(this).closest(".container");
var fname = $container.find(".fname").val();
var lname = $container.find(".lname").val();
var recordId = $container.find(".recordId").val();
$.ajax({
url: 'update.php',
method: 'POST',
data: {
fname: fname,
lname: lname,
recordId: recordId
},
success: function(response) {
alert(response);
},
error: function(xhr, textStatus, error) {
alert(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
Php
while($row = $result->fetch_array()) {
echo '<div class="container">
echo 'LC ID :<input type="text" class="fname" value="'.$row['element_6'].'"><br>';
echo 'Status :<input type="text" class="lname" value="'.$row['element_101'].'"><br>'; $recordId = $row['lc_id'];
echo '<input class="recordId" name="recordId" value="' . $recordId . '">';
echo '<button type="button" clsss="update">Go Forward ></button>';
echo '/div>';
} ?>
Related
I have a simple form that generates a JSON format of the 'brand name' input box. I've used knockout.js to generate the JSON from the form. Now, how can give this generated data to php action file to insert this JSON data in my mySql table named 'b_names' in the field 'brand_name' using php?
This is my form:
<button data-bind='click: addBrandName'>Add a drug</button>
<form action="php/action.php">
<table data-bind="foreach: brandNames">
<tbody >
<td>
<label>Brand name</label>
<input type="text" data-bind='value: brandName'>
</td>
</tbody>
</table>
<button type="submit">Submit</button>
</form>
<p>
<button data-bind='click: save, enable: brandNames().length > 0'>Save to JSON</button>
</p>
<div>
<textarea data-bind='value: lastSavedJson' rows='10' cols='33'>
</textarea>
</div>
This is the script:
<script>
$( document ).ready(function() {
var initialData = [
];
var brandNamesModel = function(brandNames) {
var self = this;
self.brandNames = ko.observableArray(ko.utils.arrayMap(brandNames, function(drug) {
return {
brandName: drug.brandName };
}));
self.addBrandName = function() {
self.brandNames.push({
brandName: ""
});
};
self.save = function() {
self.lastSavedJson(JSON.stringify(ko.toJS(self.brandNames), null, 2));
};
self.lastSavedJson = ko.observable("")
};
ko.applyBindings(new brandNamesModel(initialData));
});
</script>
I was trying this php action and surely it's not working.
$dbCon = mysqli_connect(localhost, $user, $password, $database)
or die ("error connecting database");
echo "Connected";
$data = file_get_contents($lastSavedJson);
$arrat = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO b_name(brand_name) VALUES('".$row["brandName"]."')";
mysqli_query($bdCon, $sql);
};
I'm trying to understand it so, any help would be appreciated.
Without the php here is the working fiddle of the form-
fiddle
Kindly try ajax call like in this way
$.ajax({
url: "your api url",
type: "post",
data: ko.toJSON(self),
contentType: "application/json",
success: function(data){
console.log(data);
alert("success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
In your php you should check data is coming or not in php file like below & on your browser console. Check data is coming that you sent in console.
print_r($_POST['data']);
I've got the best help from the blog of Wern Ancheta. It is a great article and he explains all the codes there.
Here is his version of how he does the job that I've been looking for:
The html and knockout code:
<div class="container" data-bind="load: loadData()">
<div class="new_student">
<input type="text" class="name" placeholder="name" data-bind="value: person_name, hasfocus: person_name_focus"/>
<input type="text" class="age" placeholder="age" data-bind="value: person_age"/>
<button data-bind="click: createPerson">Create</button>
</div>
<table data-bind="visible: people().length > 0" class="students">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Remove</th>
<th>Update</th>
</tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td>
<span data-bind="text: name, click: nameUpdating, visible: !nameUpdate()"></span>
<input type="text" class="name" data-bind="value: name, visible: nameUpdate, hasfocus: nameUpdate">
</td>
<td>
<span data-bind="text: age, click: ageUpdating, visible: !ageUpdate()"></span>
<input type="text" class="age" data-bind="value: age, visible: ageUpdate, hasfocus: ageUpdate">
</td>
<td>remove</td>
<td>update</td>
</tr>
</tbody>
</table>
<button data-bind="click: echoPerson">echo</button>
</div>
<script>
var personModel = function(id, name, age){
var self = this;
this.id = ko.observable(id);
this.name = ko.observable(name);
this.age = ko.observable(age);
this.nameUpdate = ko.observable(false);
this.ageUpdate = ko.observable(false);
this.nameUpdating = function(){
self.nameUpdate(true);
};
this.ageUpdating = function(){
self.ageUpdate(true);
};
};
var model = function(){
var self = this;
this.person_name = ko.observable("");
this.person_age = ko.observable("");
this.people = ko.observableArray([]);
this.person_name_focus = ko.observable(true);
this.createPerson = function(){
if(self.validatePerson()){
var person = {'name' : this.person_name(), 'age' : this.person_age()};
$.ajax(
{
url: 'refresher_save.php',
type: 'POST',
data: {'student' : person, 'action' : 'insert'},
success: function(id){
console.log(this);
self.people.push(new personModel(id, self.person_name(), self.person_age()));
self.person_name("");
self.person_age("");
}
}
);
}else{
alert("Name and age are required and age should be a number!");
}
};
this.validatePerson = function(){
if(self.person_name() !== "" && self.person_age() != "" && Number(self.person_age()) + 0 == self.person_age()){
return true;
}
return false;
};
this.removePerson = function(person){
$.post(
'refresher_save.php',
{'action' : 'delete', 'student_id' : person.id()},
function(response){
self.people.remove(person);
}
);
};
this.updatePerson = function(person){
var id = person.id();
var name = person.name();
var age = person.age();
var student = {'id' : id, 'name' : name, 'age' : age};
$.post(
'refresher_save.php',
{'action' : 'update', 'student' : student}
);
};
this.loadData = function(){
//fetch existing data from database
$.ajax({
url : 'refresher_save.php',
dataType: 'json',
success: function(data){
for(var x in data){
var id = data[x]['id']
var name = data[x]['name'];
var age = data[x]['age'];
self.people.push(new personModel(id, name, age));
}
}
});
/*
note: nothing would actually show up in the success function if the
data that was returned from the server isn't a json string
*/
};
this.echoPerson = function(){
console.log(ko.toJS(self.people()));
};
};
ko.applyBindings(new model());
</script>
The server side php to connect, insert, update and delete data is:
<?php
$db = new MySqli('localhost', 'ashonko', '', 'tutorials');
$action = (!empty($_POST['action'])) ? $_POST['action'] : '';
$student = (!empty($_POST['student'])) ? $_POST['student'] : '';
if(!empty($student)){
$name = $student['name'];
$age = $student['age'];
}
switch($action){
case 'insert':
$db->query("INSERT INTO students SET name = '$name', age = '$age'");
echo $db->insert_id; //last insert id
break;
case 'update':
$id = $student['id'];
$db->query("UPDATE students SET name = '$name', age = '$age' WHERE id = '$id'");
break;
case 'delete':
$id = $_POST['student_id'];
$db->query("UPDATE students SET status = 0 WHERE id = '$id'");
break;
default:
$students = $db->query("SELECT * FROM students WHERE status = 1");
$students_r = array();
while($row = $students->fetch_array()){
$id = $row['id'];
$name = $row['name'];
$age = $row['age'];
$name_update = false;
$age_update = false;
$name_focus = false;
$age_focus = false;
$students_r[] = array(
'id' => $id, 'name' => $name, 'age' => $age,
'nameUpdate' => $name_update, 'ageUpdate' => $age_update,
'nameHasFocus' => $name_focus, 'ageHasFocus' => $age_focus
);
}
echo json_encode($students_r);
break;
}
?>
I have table received from database:
<p id="result"></p>
<?php
//$id = $_SESSION['staff_id'];
$teamResult = getQuarter($leader_id);
$count1 = 0;
if (mysqli_num_rows($teamResult) > 0)
{
?>
<table id="confirm">
<tr>
<th>1st Quarter</th>
</tr>
<?php
while($row = mysqli_fetch_array($teamResult))
{
$staff_id = $row['staff_id'];
$username = $row['username'];
$date1 = $row['date1']; $fdate1 = $row['fdate1']; $q1 = $row['q1']; $cfm1 = $row['cfm1'];
?>
<tr>
<td>
<?php if($date1 != NULL){
echo "Ev.date: ".$date1."<br/> Fb.date: ".$fdate1.""
."<input type='text' id='stid' name='confirm' class='confirm' value='". $q1. "| " . $staff_id ."'>";
}else {echo "";}
?>
</td>
</tr>
<?php
$count1++;
}
} else {
echo "<h2>No Data to Display</h2>";
}
?>
</table>
This field is checkbox but I changed it to text to see its value:
<input type='text' id='stid' name='confirm' class='confirm' value='". $q1. "| " . $staff_id ."'>
Here is what I got in table:
Then I have AJAX function:
<script>
$(function () {
$(document).on('click', '.confirm', function(){
var stid = $("#stid").val();
$.ajax({
url: "comAssessment/change.php",
method: "POST",
data: {stid: stid},
dataType:"text",
success: function (data) {
$('#confirm').hide();
$('#result').html(data);
}
});
});
});
</script>
And change.php:
$info = $_POST["stid"];
list($value1,$value2) = explode('|', $info);
echo $value1;
echo "<br/>";
echo $value2;
But the problem is I dont get correct value. For first and second row i get 1| 1000302. Even for second row where is should be 1| 1000305. What it the problem and how can I solve it?
IDs have to be unique. $("#stid") will always select the first element with that ID.
You can simply use $(this) to get the value of the element you clicked on.
$(document).on('click', '.confirm', function(){
var stid = $(this).val();
$.ajax({
url: "comAssessment/change.php",
method: "POST",
data: {stid: stid},
dataType:"text",
success: function (data) {
$('#confirm').hide();
$('#result').html(data);
}
});
});
I am a newbie on ajax. I spend hours with "try and error", but unfortunately without success.
I have a form:
<form id="upload" method="post" name="form">
<input class="datepicker" type="text" name="date" value="<?php echo $date_bes; ?>"/>
<input class="chk" name="chk" type="checkbox" value="<?php echo $id_submit; ?>"
<?php if($check == 1){ echo "checked"; }else{ echo "";} ?>/>
<textarea class="remark" name="remark" cols="30" rows="1"><?php echo $remark; ?> </textarea>
<input class="submit" type="image" src="save.jpg"></td>
</form>
Then I my ajax_script.js:
$(document).ready(function() {
$( "#upload" ).on("submit", function() {
var id = $('.chk').val();
var date = $('.datepicker').val();
var chk = $('.chk').prop('checked');
var remark = $('.remark').val();
$.ajax({
type: "POST",
url: "update.php",
data : "{'id':'" + id + "', 'date':'" + date + "', 'chk':'" + chk + "', 'remark':'" + remark + "'}",
success: function (data) {
if(data.success == true)
{
console.log('everything fine');
}
},
error: function(){
console.log('something bad happened');
}
});
});
});
and my update.php
<?php
$id = $_POST['id'];
$date = $_POST['date'];
$chk = $_POST['chk'];
if($chk == true){
$check = 1;
}else{
$check = 0;
}
$remark = $_POST['remark'];
$jahr = substr($date,6,4);
$mon = substr($date,3,2);
$tag = substr($date,0,2);
$date = $jahr.'-'.$mon.'-'.$tag;
echo $id ."<br>".$date."<br>".$chk."<br>".$remark;
require_once('config.php');
$link = mysqli_connect (
MYSQL_HOST,
MYSQL_BENUTZER,
MYSQL_KENNWORT,
MYSQL_DATENBANK
);
if(!$link){
die('Keine Verbindung möglich: ' .mysql_error());
}
$sql = "UPDATE mytable
SET date = '$date', chka ='$chk', remark = '$remark' WHERE id_submits = $id";
$result = mysqli_query( $link, $sql );
echo $sql."<br>";
?>
After push on the bottom, firebug deliver me following:
Can anybody help me - please!
Regards,
Yab86
I think that you do not really need the quotes around the variable in the data section of ajax.
data: {id: id, date: date, chk: chk, remark: remark},
To let AJAX pass data through JQuery you should simply put in the "data" part of the AJAX request your data in this format {'name':name_on_php,'name2':name_on_php2}
I've written "name_on_php" to remind you that the part after the " : " is the one that you GET or POST on your php page.
Hope it helped :)
I have a Edit Profile, for the user's profile. Well, The Javascript seems to be only getting the value of the Age's Form. The PHP File is getting the Age, but no others and it's not updating the database.
Javascript:
function UpdateProfile() {
var newage = $("#NewAge").val();
var newimage = $("#NewImage").val();
var newbio = $("#NewBio").val();
var dataString = 'newage=' + newage || 'newimage=' + newimage || 'newbio=' + newbio;
if (newbio.length , newage.length , newimage.length == 0) {
$('#Required').fadeIn(300);
$('#Mask').fadeIn(300);
} else {
$.ajax({
type: "POST",
url: "update_profile.php",
data: dataString,
cache: false,
success: function (UpdateProfile) {
$('#EditInfo').hide();
$("#UpdatedProfile").html(UpdateProfile);
$("#UpdatedProfile").fadeIn('slow');
$("#Age").html('Age: ' + newage);
$('#Image').html('<img src="' + newimage +'" width="150" height="100" />');
}
});
}
}
Here's The update_profile.php File:
<?php session_start() ?>
<?php include 'connect.php' ?>
<?php
$newimage = $_POST['newimage'];
$newbio = $_POST['newabout'];
$newage = $_POST['newage'];
$update = "UPDATE members SET bio=(".$newbio.") age=(".$newage.") image=(".$newimage.") WHERE id='".$id."'";
$res = mysql_query($update);
echo 'Success: Profile Updated!<br />';
echo $update . '<br />';
?>
HTML:
<input type="text" id="NewAge" value="<?php echo $age ?>" maxlength="2" />
<input type="text" id="NewImage" value="<?php echo $image ?>" maxlength="500" />
<textarea id="NewBio" style="width: 500; max-width: 500; height: 100; max-height: 150;"><?php echo $bio ?></textarea>
<input type="submit" value="Update Profile" onClick="UpdateProfile()" />
The Code The Update outputs is this:
Success: Profile Updated!
UPDATE members SET bio=() age=(18) image=() WHERE id='1'
Try this instead:
$.ajax({
...
data: { newimage: newimage,
newage: newage,
newbio: newbio }
...
});
Update this line:
$newbio = $_POST['newabout'];
to
$newbio = $_POST['newbio'];
And it should work.
I have a question about using ajax.I want to delete something of my screen (to be clear, some articles) I'm generating content (the articles) on the screen with this code:
while($test = $allArticles->fetch_assoc())
{
echo "<div class='metfoto'>";
echo "<h1 name='tt' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<form method='post' action=''>";
echo "<input type='submit' class='delete' name='verwijder' value='verwijder'>";
echo "</form>";
//echo "<h1>".$test['id']."</h1>";
echo "</div>";
}
This all is working very well without ajax. But I want to make this(the delete with the button) happen without a page refresh.
When i for example check the content of $test['id'], i receive one number. My problem with the code below is that when i want to put the title into variabel (var titel) for ajax, it loads all the titels from my page.
<script type="text/javascript">
$(document).ready(function(){
$(".delete").click(function(){
var titel = $(".titelopmaak").text();
var artikel = $(".artikelopmaak").text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$(".titelopmaak").fadeOut();
}
else
{
}
}
});
return false;
})
});
</script>
EDIT
I hope i explained my question in a better way now
Your problem is here
var titel = $(".titelopmaak").text();
You get all the values of the elements with class .titelopmaak but you only need one.
This is the correct one, we go up the tree and then find the item.
var titel = $(this).closest('.metfoto').find('.titelopmaak').text();
But, control elements by the title its very bad practice, use id instead of.
<script>
$(document).ready( function(){
$('.delete').submit( function() {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: $(this).attr('method'),
success: function(data, status, jqXHR) {
$(".titelopmaak").fadeOut();
},
error: function(jqXHR, textStatus, errorThrown) {
}
);
});
});
</script>
<? while($test = $allArticles->fetch_assoc()) { ?>
<form method="POST" action="" class="delete">
<input type="hidden" value="<?=$test['id']?>" name="delete">
<input type="submit" value='verwijder'>
</form>
<? } ?>
You can try like this....
You have to specify individual id for each html elements
while($test = $allArticles->fetch_assoc())
{
$cid = $test['id'];
echo "<div id='div$cid' class='metfoto'>";
echo "<h1 name='tt' id='h1$cid' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p id='para$cid' class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<input type='submit' class='delete' name='verwijder' id='verwijder$cid' onclick='deleteValue($cid);' value='verwijder'>";
echo "</div>";
}
javascript function
Refer the h1 and div by their ids.
<script type="text/javascript">
function deleteValue(cid)
{
var titel = $("#h1"+cid).text();
var artikel = $("#para"+cid).text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$("#h1"+cid).fadeOut();
}
else
{
}
}
});
return false;
})
}
</script>
deleteArticle.php
include "connection.php";
$title = $_POST['titelA'];
$ok = mysql_query("delete from yourtable where title='$title');
echo "your msg here";