Creating an option select from db using ajax - javascript

I am trying to create an additional form text field on click of a button which wotrtks fine, my only problem is that the select option is blank and when I inspect element I see that NAN is added to it.
Here is the design for the dynamic form elements container
<div class="col-sm-6" id="prescription-container">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="drug" class="form-label">Medicine </label>
<select name="drug[]" class="form-control search-select">
<?php echo $drug_drop_down; ?>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Comment</label>
<div class="phone-icon">
<input type="text" class="form-control" name="diagnosis">
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<a href="#" id="add_prescription" class="btn btn-warning"><i class="fa fa-plus"></i>Add
prescription</a>
</div>
</div>
This is how I have implemented the onclick listener for the add prescription button
<script>
$("#add_prescription").click(function(e) {
e.preventDefault();
var result="<option value=''>Select Drug<option>";
$.ajax({
type: 'GET',
url: 'drugs',
success: function(data) {
if (data.length > 0) {
$.each(data, function(i, item) {
result += "<option value='" + data.id + "'>"+data.name+"<option>";
})
} else{
result += "<option value='" + data.id + "'>"+data.name+"<option>";
}
$('#prescription-container').append(" <div class='row'> <div class='col-md-6'>" +
"<div class='form-group'>" +
"<label for='drug' class='form-label'>Medicine </label><select name='drug[]'' class='form-control'>" +
+ result +
"</select>" +
"</div>" +
"</div>" +
"<div class='col-sm-6'>" +
"<div class='form-group'>" +
"<label>Comment</label>" +
"<div class='phone-icon'>" +
"<input type='text' class='form-control' name='diagnosis'>" +
"</div>" +
"</div>" +
"</div>" +
"</div>")
}
})
})
</script>
Finally this is the controller sending back data
function () {
$drugs = Medicine::get();
return response()->json( $drugs);
}
Now my problem is that when i alert(data) I get [object Object],[object Object]. This made me modify the controller as follows
function () {
$drugs = Medicine::get();
$drug_drop_down = "<option>Select drug</option>";
foreach($drugs as $drug){
$drug_drop_down .="<option value='".$drug->id."'>$drug->name</option>";
}
return response()->json( $drug_drop_down);
}
and the onclick listener to
<script>
$("#add_prescription").click(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'drugs',
success: function(data) {
$('#prescription-container').append(" <div class='row'> <div class='col-md-6'>" +
"<div class='form-group'>" +
"<label for='drug' class='form-label'>Medicine </label><select name='drug[]'' class='form-control'>" +
+ data +
"</select>" +
"</div>" +
"</div>" +
"<div class='col-sm-6'>" +
"<div class='form-group'>" +
"<label>Comment</label>" +
"<div class='phone-icon'>" +
"<input type='text' class='form-control' name='diagnosis'>" +
"</div>" +
"</div>" +
"</div>" +
"</div>")
}
})
})
</script>
Now if I alert(data) I get <option>Select drug</option><option value='1'>Quinine</option><option value='2'>Malariaquine</option> but the select is still being added without options and the following appear on inspect element for the added filed
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="drug" class="form-label">Medicine </label>
<select name="drug[]" '="" class="form-control">NaN</select>
</div>
</div>
</div>
What could I be doing wrong here?

After some searching just realized that the second way was supposed to work except that this + + data + "</select>" + means I am using + as an addition operator and not a concatenator, changing it to + data + "</select>" + solved my problem. I do not still understand what the issue could have been with the first approach

Related

Editing data with jQuery in modal won't work

I'm currently working on something to store matches/events in a database. I like to note that this is my first use of jQuery. Everything is pretty much done, expect this problem.
I use PHP to create a list of teams. When a 'team' is selected, the matches of that team are loaded into div "display". Every match has a id, title, date and time field.
<?php
// show_overview.php
$event_info = mysqli_query($conn, "SELECT e.match_id, e.title, e.date, e.starttime
FROM matches AS e
WHERE e.team_id = '$team' AND e.date >= CURDATE()
ORDER BY e.date asc;");
foreach($event_info as $row) {
$events[] = array('match_id' => $row['match_id'], 'title' => stripslashes($row['title']), 'date' => $row['date'], 'starttime' => $row['starttime']);
}
$data['events'] = $events;
echo json_encode($data);
?>
Here we have the body of the page. In the dropdown box you can select your team.
<!-- BEGIN MATCHES -->
<div class="form-group row">
<label for="team-matchlist" class="col-sm-8 col-md-7 col-form-label">Kies van welk team je de wedstrijden wilt zien:</label>
<div class="col-sm-2 col-md-3 mb-5">
<select class="form-control" id="team-matchlist" name="team-matchlist">
<?php
// Create a list of teams to select the matches. This is loaded in the header. The list is correctly showing.
// $teams = mysqli_query($conn,"SELECT * FROM teams ORDER BY team;");
if ($hierarchy_session >= 3):
while($team = mysqli_fetch_assoc($teams)):
echo '<option value="' . $team['team_id'] . '">' . $team['team'] . '</option>';
endwhile;
mysqli_data_seek($teams, 0);
else:
echo '<option value="' . $team_id_session . '">' . $teamname_session . '</option>';
endif;
?>
</select>
</div>
<!-- Here is the match data loaded -->
<div id="display" class="container"></div>
</div>
</div>
<!-- END MATCHES -->
In are the matches loaded. There are two buttons created for editing a match. It won't connect the data to the modal. I can't get my head around it. I think it's a binding problem, but I can't make it to work.
If I use php directly to export the data, it works. But when I load the data in jQuery. It won't load the data in the body of the modal.
I looked at bind, but I couldn't make that work. I hope someone can make me look in the right direction. I tried to make the code as little as possible.
$(document).ready(function() {
// BEGIN SHOW MATCHES
// Create a list of all the matches from database
// When a team is selected
$("#team-matchlist").change(function () {
var team = $(this).val();
$.ajax({
url: "show_overview.php",
type: "POST",
dataType: "json",
data: {
team: team
},
success: function(response) {
var i;
var display = document.getElementById("display");
if (response.events.length > 0) {
display.innerHTML = "";
var user_hierarchy = '<?php echo $hierarchy_session;?>';
var user_team = '<?php echo $team_id_session;?>';
for (i = 0; i<response.events.length; i++) {
display.innerHTML += (
"<form method='post' class='mb-5 text-md-right'>" +
"<div class='form-group row'>" +
"<label for='firstname' class='col-sm-4 col-md-3 col-form-label'>Titel</label>" +
"<div class='col-sm-8 col-md-9'>" +
"<input type='text' class='form-control' id='etitle-" + response.events[i].match_id + "' name='title' value='" + response.events[i].title + "'>" +
"</div>"+
"</div>"+
"<div class='form-group row'>" +
"<label for='lastname' class='col-sm-4 col-md-3 col-form-label'>Datum</label>" +
"<div class='col-sm-8 col-md-9'>" +
"<input type='date' class='form-control' id='edate-" + response.events[i].match_id + "' name='date' value='" + response.events[i].date + "'>" +
"</div>"+
"</div>"+
"<div class='form-group row'>" +
"<label for='lastname' class='col-sm-4 col-md-3 col-form-label'>Starttijd</label>" +
"<div class='col-sm-8 col-md-9'>" +
"<input type='time' class='form-control' id='estarttime-" + response.events[i].match_id + "' name='starttime' value='" + response.events[i].starttime + "'>" +
"</div>"+
"</div>"+
// Here is the button for editing the match
"<div class='form-group btn-group'>"+
"<button type='button' id='edit_match-" + response.events[i].match_id + "' class='btn btn-primary edit-match' data-toggle='modal' data-target='#modal-edit_match'>" +
"Wijzigen" +
"</button>" +
"</div>"+
"<hr/>"+
"</form>"
);
}
} else {
display.innerHTML = "Er zijn geen wedstrijden voor dit team.";
}
}
});
}).change();
// Show info for confirmation in modal
$('.edit-match').on("click", function() {
var itemID = $(this).attr("id");
var split = itemID.split("-");
var id = split[1];
var title = $("#etitle-"+id).val();
var date = $("#edate-"+id).val();
var starttime = $("#estarttime-"+id).val();
var elem_id = document.getElementById("edit_match");
var title_id = document.getElementById("modal-title-edit_match");
var body_id = document.getElementById("modal-body-edit_match");
var date = new Date(date + "T" + starttime);
const date_options = { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric'};
const time_options = { hour: 'numeric', minute: 'numeric' };
var datestring = date.toLocaleDateString('nl-NL', date_options);
var timestring = date.toLocaleTimeString('nl-NL', time_options);
title_id.innerHTML = "Wedstrijd wijzigen";
body_id.innerHTML = "Titel: " + title +
"<br>Datum: " + datestring +
"<br>Starttijd: " + timestring +
"<br><br>Weet u zeker dat u deze wedstrijd wilt wijzigen?";
$(".edit_match").attr("id", "edit_match-" + id);
});
});
</script>
The confirmation is not applied in the modal.
Below we have the modal. The modal is loaded. Only the javascript is not applied to the modal. It remains empty.
<!-- BEGIN MODALS -->
<!-- Modal after clicking on edit match -->
<div class="modal fade" id="modal-edit_match" tabindex="-1" role="dialog" aria-labelledby="modal-title" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal-title-edit_match">Wedstrijd wijzigen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Sluiten">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modal-body-edit_match">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Annuleren</button>
<button type="button" name="edit_match" id="edit_match" class="btn btn-primary edit_match">Wijzigen</button>
</div>
</div>
</div>
</div>
<!-- END MODALS -->
Does anyone have any ideas?

JavaScript Function not taking the array index returning as undefined

I have created a Crud application and have a data() which accepts Json
user = {name: name, age: age, email: email, dob: do}
as input.
When I call the editUser(), the array index is not being taken.
but when I pass the array index statically through the console, the function works as it should.
How should I correct the mistake?
I also have an updateUser() which also faces the same problem.
function read(users) {
var html = "<table border='1|1' class=\"table container\">";
var userhtml = document.getElementById('user');
userhtml.innerHTML = '';
var t = Object.keys(users[0]);
for (var i = 0; i <= 0; i++) {
html += "<tr>";
html += "<th>" + t[0] + "</th>";
html += "<th>" + t[1] + "</th>";
html += "<th>" + t[2] + "</th>";
html += "<th>" + t[3] + "</th>";
html += "<th>" + " Edit" + "</th>";
html += "<th>" + "Delete" + " </th>";
html += "</tr>"
for (var j = i; j < users.length; j++) {
html += "<tr>";
html += "<td>" + users[j].name + "</td>";
html += "<td>" + users[j].age + "</td>";
html += "<td>" + users[j].email + "</td>";
html += "<td>" + users[j].dob + "</td>";
html += "<td>" + "<a href='#' onclick='editUser()'>Edit</a>" + "</td>";
html += "<td>" + "<a href='#' onclick='deleteUsers()'>Delete</a>" + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("user").innerHTML = html;
}
}
function editUser(index) {
debugger;
var userhtml1 = document.getElementById('edit');
userhtml1.innerHTML = '';
for (var i = 0; i < users.length; i++) {
if (i == index) {
userhtml1.innerHTML += ' <div class="user"> Name :<input id="EditName" type="text" value ="' + users[i].name + '"><br />' +
'Age :<input id="EditAge" type="text" value="' + users[i].age + '"> <br /> ' +
'Email :<input id="EditEmail" type="text" value="' + users[i].email + '"> <br /> ' +
'DOB :<input id="EditDOB" type="text" value="' + users[i].dob + '"> <br /> ' +
'<button class="edit" onclick="updateUser()">Update</button>';
} else {
userhtml1.innerHTML += '';
}
}
}
function updateUser(index) {
debugger;
var updatename = document.getElementById('EditName').value;
var updateage = document.getElementById('EditAge').value;
var updateemail = document.getElementById('EditEmail').value;
var updatedob = document.getElementById('EditDOB').value;
if (updatename == '' || updateemail == '' || updateage == '' || updatedob == '') {
alert("Please Fill the Fields!");
}
else {
users[index].name = updatename;
users[index].email = updateemail;
users[index].age = updateage;
users[index].dob = updatedob;
read(users);
}
}
<form action="#" onsubmit="data(name, age, email, dob)">
<!--data(name, age, email, dob)-->
<!--onsubmit="return validate()"-->
<div class="form-group">
<label class="form-text">Name :</label>
<input type="text" id="Name" placeholder="Enter Name" class="form-control" " />
<span id="ErrorName " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Age :</label>
<input type="text " id="Age " placeholder="Enter Age " class="form-control " />
<span id="ErrorAge " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Email :</label>
<input type="text " id="Email " placeholder="Enter Email " class="form-control " />
<span id="ErrorEmail " class="text-danger " />
</div>
<div class="form-group ">
<label class="form-text ">Password :</label>
<input type="password " id="Password " placeholder="Enter Password " class="form-control " />
<span id="ErrorPassword " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Confirm Password :</label>
<input type="password " id="ConfirmPassword " placeholder="Confirm Password " class="form-control " onblur=" " />
<span id="ErrorConfirmPassword " class="text-danger "></span>
</div>
<div class="form-group ">
<label class="form-text ">Date of Birth :</label>
<input type="date " id="DOB " class="form-control " />
<span id="ErrorDOB " class="text-danger "></span>
</div>
<div class="form-group col-lg-12 text-center ">
<input type="submit " id="Submit " class="btn btn-success " />
</div>
</form>
<div class="container " id="user ">
</div>
<br />
<div class="form-group " id="edit ">
</div>
You just forgot to pass the argument. Try this please:
// Change this line
html += "<td>" + "<a href='#' onclick='editUser()'>Edit</a>" + "</td>";
// For this one
html += "<td>" + "<a href='#' onclick='editUser("+j+")'>Edit</a>" + "</td>";
Also, note that your for statement only executes once.. you can just remove it leaving the code inside untouched.
// This executes only once, no matter what.
for (var i = 0; i <= 0; i++) { // <-- remove this
// your code..
} // <-- remove this
// Because it would be the same as just doing:
// your code..
Edit for the updateUser problem:
// For the updateUser problem, note that I added the i variable for the call:
userhtml1.innerHTML += ' <div class="user"> Name :<input id="EditName" type="text" value ="' + users[i].name + '"><br />' +
'Age :<input id="EditAge" type="text" value="' + users[i].age + '"> <br /> ' +
'Email :<input id="EditEmail" type="text" value="' + users[i].email + '"> <br /> ' +
'DOB :<input id="EditDOB" type="text" value="' + users[i].dob + '"> <br /> ' +
'<button class="edit" onclick="updateUser('+i+')">Update</button>';

Remove DIV dynamically with JQuery

i have a problem to reference an identifier of a DIV. I allow to add a div with a text field and a button to delete the text field, and i set a id to the DIV like an array with this code:
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso['+$count+']>' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
'<a class="btn btn-default" id="eliminacorso['+$count+']" aria-label="Elimina">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'</a>' +
'</div>' +
'</div>' +
'');
});
So.. if i press on the botton at the at the side of the text area, i'll call a function that will remove it.
The skeleton of the function is the follow:
$('#eliminacorso[]').on('click', function() {
$count --;
$('#corso[]').remove();
});
So my ask is: How can i insert between the square brackets the right identifier of the div?
A better choice is:-
1.Instead of using id use button class
2.And then use event delegation concept like below:-
$(document).on('click','.btn-default',function(){
$(this).closest('.form-group').remove();
});
Reference:- https://api.jquery.com/closest/
Use as below the script that add DIV. Remove '[' from id attribute from div tag and anchor tag as below
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso'+$count+'>' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
'<a class="btn btn-default" id="corso'+$count+'" aria-label="Elimina">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'</a>' +
'</div>' +
'</div>' +
'');
});
And then script to get the clicked id and remove the matched div on click of button as below
$('.btn').on('click', function() {
var selectedId = $(this).attr('id');
$('#'+selectedId).remove();
});
Try below code.It may help you
var $count =0
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso_'+$count+'">' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso_'+ $count + '"/>' +
'<a class="btn btn-default" id="eliminacorso_'+$count+'" aria-label="Elimina" onclick="remove(this);">' +
'Test' +
'</a>' +
'</div>' +
'</div>' +
'');
});
function remove(aRemove){
console.log(aRemove);
var divid = aRemove.id.replace("eliminacorso_","corso_");
$("#" + divid).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="aggiungi"> Click ME </button>
<div id="corsi">
</div>
https://codepen.io/vino4all/pen/vZrQEX
Try this code.
<button id="aggiungi">Click</button>
<div id="corsi"></div>
Add a class attribute to the <a> tag.
var $count = 0;
$('#aggiungi').on('click',function () {
$count ++;
$('#corsi').append(
'<div class="form-group row" id="corso['+$count+']>' +
'<label class="col-sm-2 col-form-label" for="corsi">Corso ' + $count +'</label>' +
'<div class="col-sm-10 form-inline">' +
'<input type="text" class="form-control" id="corso" name="corso['+ $count + ']"/>' +
'<a class="btn btn-default delBtn" id="eliminacorso['+$count+']" aria-label="Elimina"><span>X</span>' +
'<i class="fa fa-times" aria-hidden="false"></i>' +
'</a>' +
'</div>' +
'</div>' +
'');
});
$('#corsi').on('click', '.delBtn', function() {
console.log('this :'+$(this));
$count --;
$(this).parent().parent().remove();
});
Notice the usage of on function.
It should be like below
$('#corsi').on('click', '.delBtn', fun);
You can use something like this
var count = 3;
$('button').click(function(){
count--;
$($('.corso')[count]).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="corso">1. <input type="text" /></div><br />
<div class="corso">2. <input type="text" /></div><br />
<div class="corso">3. <input type="text" /></div><br />
<br />
<button>Remove</button>
Try this:
var $count = 0
$('#aggiungi').on('click', function () {
$count++;
let divId = `input_div_${$count}`;
let html = `<div class="form-group row" id="${divId}">
<label class="col-sm-2 col-form-label" for="corsi">Input ${$count}</label>
<div class="col-sm-10 form-inline">
<input type="text" class="form-control" id="input" name="${divId}"/>
<button type="button" id="remove_btn_${$count}" aria-label="Elimina" onclick="remove('${divId}');">
remove
</a>
</div>
</div>`;
$('#main-div').append(html);
});
function remove(removeDivId) {
console.log(removeDivId);
$("#" + removeDivId).remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="aggiungi"> Click ME </button>
<div id="main-div">
</div>

Vue.js dynamically appending HTML when clicking on a button

So basically what I am trying to achieve is allowing the user to be able to add to an existing set of information that will be passed on to Vue from JSON.
So the following code is my HTML code which comprises of the div element with the id objectiveArea that vue will render to and a hard coded button for the users to add more entries.
<div class="form-group" id="objectiveArea"></div>
<div><input type="button" value="Add Objective" id="addButton" /></div>
And here is my Javascript where I pass the JSON into vue for it to render as well as having an onclick event when the add button is triggered. The function addNewObjectiveRow serves as a template to append when the user clicks add and the objectiveElements is a template for vue to render the existing JSON to the HTML.
function addNewObjectiveRow(value) {
var $divElements = "<div class='row'>"
+ "<div class='form-inline'>"
+ "<br /><div class='form-group'><label class='control-label'>Title</label><div class=''><input type='text' class='form-control objectivetitle' placeholder='Title' /></div></div>"
+ " "
+ "<div class='form-group input-group'><label class='control-label'>Target Completion Date</label><div class=''><input readonly type='text' class='form-control targetdateinput' placeholder='Select Date' /><span class='input-group-addon'><i class='glyphicon glyphicon-calendar'></i></span></div></div>"
+ " "
+ "<div class='form-group'><label class='control-label'></label><div><input type='button' value='Remove Goal' class='btn-remove btn-danger deleteButton' /></div></div>"
+ "</div>"
+ "<br />"
+ "<div class='form-group'><label class='control-label'> Details</label><div><textarea class='form-control text-area-width goaldetails' rows='4' placeholder='Enter details here...'></textarea></div></div><hr />"
+ "</div>"
return $divElements;
}
var objectiveElements = "<div class='row'><div v-for='(objective, index) in objectivesData'>"
+ "<div class='form-inline'>"
+ "<br /><div class='form-group'><label class='control-label'>Title</label><div class=''><input type='text' class='form-control objectivetitle' placeholder='Title' v-model='decodeData(objective.Title)' /></div></div>"
+ " "
+ "<div class='form-group input-group'><label class='control-label'>Target Completion Date</label><div class=''><input readonly type='text' class='form-control targetdateinput' placeholder='Select Date' v-formatdate='objective.TargetDate' /><span class='input-group-addon'><i class='glyphicon glyphicon-calendar'></i></span></div></div>"
+ " "
+ "<div class='form-group'><label class='control-label'></label><div><input type='button' v-if='(index > 0)' value='Remove Goal' class='btn-remove btn-danger deleteButton' /></div></div>"
+ "</div>"
+ "<br />"
+ "<div class='form-group'><label class='control-label'> Details</label><div><textarea class='form-control text-area-width goaldetails' rows='4' placeholder='Enter details here...' v-model='decodeData(objective.Details)'></textarea></div></div><hr />"
+ "</div></div>";
var data = JSON.parse('[{"Title":"Title One","TargetDate":"21 June 2017","Details":"Details One"},{"Title":"Title Two","TargetDate":"22 June 2017","Details":"Details Two"}]');
var Objectives = Vue.extend({
template: objectiveElements,
data: function () {
return {
objectivesData: data
}
}
})
new Objectives().$mount('#objectiveArea');
$('#addButton').on('click', function () {
$('#objectiveArea').append(addNewObjectiveRow(""));
});//end addButton on click
However, the above code renders the existing information from the JSON just fine in the HTML but when I click on the add button, nothing happens at all. Am I missing something or getting it all wrong?
https://v2.vuejs.org/v2/guide/list.html
HTML
<ul id="example-1">
<li v-for="item in items">
{{ item.message }}
</li>
</ul>
<button #click="addItem()">Add new item</button>
JS
var example1 = new Vue({
el: '#example-1',
data: {
items: [
{ message: 'Foo' },
{ message: 'Bar' }
]
},
methods: {
addItem(){
this.items.push({message: 'new message'})
}
}
})
Clicking the button will execute addItem() method which will add a new item into data items and it will automatically render new li
there are many mistakes
the function addNewObjectiveRow(value)you don't use the parameter value.
Vue is data-driven, you should change the objectivesData, not simply append the string. Read the document

Javascript code adding empty records to mysql

I have a short problem.
Here is my form layout:
<form class="form-inline" action="javascript:addRecord();" method="GET">
<div class="row">
<div class="form-group col-lg-4">
<div class="form-group col-lg-6">
<label for="konu">Konu:</label>
<input class="form-control " type="text" name="konu" required="required" placeholder="Bir konu yazın"/>
</div>
</div>
</div>
<br>
<div class="form-group col-lg-5 ">
<button type="submit" class="btn btn-default">Kaydet</button>
</div>
</form>
<div id="add-record-div" class="alert alert-success" hidden="hidden">
<strong>RECORD INSERTED</strong>
</div>
And my javascript code:
function addRecord()
{
$.post('add.php', function(data)
{
trHTML +=
'<tr><td>' + value.id +
'</td><td>' + value.konu +
'</td><td>' + value.aciklama +
'</td><td>' + value.giris_tarih +
'</td><td>' + value.degistirilme_tarih +
'</td><td>' + value.ad_soyad +
'</td><td>' + value.email +
'</td></tr>';
});
getLastRecord();
$('#add-record-div').show('slow').delay('1000');
$('#add-record-div').hide('slow');
}
Databse insert looks like this: http://i.stack.imgur.com/fDiiC.jpg
My problem is this function adds only empty rows to mysql. 'giris_tarih' and 'degistirilme_tarih' are date values. Those are being added correctly but other columns are always empty. There is no problem with add.php page. If I only write: form class="form-inline" action="add.php" it works perfectly. But I couldn't get it worked with javascript function.
You have mismatched actions in your markup and script, and also your data is pointing to value which is not part of the object returned from your add.php (you set your ajax response to the variable data, therefore you must use data.propName...). I also corrected your table formatting a bit and used jQuery like the rest of your module.
function addRecord()
{
$.get('add.php', function(data)
{
$('#your-table').append('<tr>' + data.id + '</td>'
+ '<td>' + data.konu + '</td>'
+ '<td>' + data.aciklama + '</td>'
+ '<td>' + data.giris_tarih + '</td>'
+ '<td>' + data.degistirilme_tarih + '</td>'
+ '<td>' + data.ad_soyad + '</td>'
+ '<td>' + data.email + '</td>'
+ '</tr>');
getLastRecord();
$('#add-record-div').show('slow').delay('1000');
$('#add-record-div').hide('slow');
}

Categories