Javascript code adding empty records to mysql - javascript

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');
}

Related

Creating an option select from db using ajax

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

how to get value from jquery in dynamic input

I'm trying to create a questions with answer or
multiple choice in CodeIgniter, I create the choice using jQuery and now I don't know how to get all value from text input.
can someone help me for this case??
This code:
var choices = [{
id_soal: 'choice1'
}, {
id_soal: 'choice2'
}, {
id_soal: 'choice3'
}];
var html = '';
var i;
for (i = 0; i < choices.length; i++) {
html += '<div class="row">',
html += '<div class="col-xs-8 col-md-4>',
html += '<div class="input-group">',
html += '<span class="input-group-addon" style="background:green"><i class="fa fa-question-circle"></i> Soal' + (i + 1) + '</span>',
html += '<input type="text" name="Question' + i + '" id="Question' + i + '" class="Question form-control" placeholder="Question" required>',
html += '</div></div></div></br>',
html += '<div class="row">',
html += '<div class="col-xs-4 col-md-4">',
html += '<div class="input-group">',
html += '<span class="input-group-addon">A</span>',
html += '<input type="text" name="A_jawaban' + i + '" id="A_jawaban' + i + '" class="form-control A_jawaban" placeholder="Result" required>',
html += '</div></div>'
html += '<div class="col-xs-4 col-md-4">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> B</span>',
html += '<input type="text" name="B_jawaban' + i + '" id="B_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div>',
html += '<div class="col-xs-4 col-md-4">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> C</span>',
html += '<input type="text" name="C_jawaban' + i + '" id="C_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div></div><br>';
html += '<div class="row">',
html += '<div class="col-xs-4 col-md-6">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> D</span>',
html += '<input type="text" name="D_jawaban' + i + '" id="D_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div>'
html += '<div class="col-xs-4 col-md-6">',
html += '<div class="input-group">',
html += '<span class="input-group-addon"> E</span>',
html += '<input type="text" name="E_jawaban' + i + '" id="E_jawaban' + i + '" class="form-control" placeholder="Result" required>',
html += '</div></div></div><br>';
}
$('.judul').html(html);
$('#tambah').click(function(event) {
console.log('THIS CHOICES',choices)
var results = $('.Question').serializeArray();
console.log('FOR QUESTIONS',results)
var resultsAnswearA = $('.A_jawaban').serializeArray();
console.log('FOR QUESTIONS',resultsAnswearA)
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div name="judul" class="judul"></div>
<button id="tambah" name="tambah" class="btn btn-warning"><i class="icon-pencil5"></i> Tambah</button>
UPDATE
wow sorry for my question above, I forgot and just realized I got the answer to use query selector. just check the code
Try:
var allInputsValue = {};
$(".judul input").each(function(){
//Add each input value to all inputs
allInputsValue[allInputsValue.length] = {
"name":$(this).attr("name"),
"value":$(this).val()
};
});
console.log(allInputsValue);

send data from form with <li> attributes

My data in my form will be inserted by javascript. These are li attributes. I want to send the data in these li attributes to an other php page. But that's not possible?
function addProduct() {
//var productid = document.getElementById('product').value;
var product = products[type];
//this is just a product placeholder
//you should insert an item with the selected product info
//replace productId, productName, price and url with your real product info
var productAdded = $('<li class="product" name="product' + i + '">' +
'<div class="product-image">' +
'<a href="image">' +
'<img src="images/' + product + '.jpg" alt="placeholder"></a>' +
'</div>' +
'<div class="product-details">' +
'<a style="color: black;">' + product + '</a>' +
'<span class="price">€ ' + price + '</span><br>' +
'<div class="quantity">' +
'<label>Aantal: ' + qty + '</label> <div class="actions">' +
' <a href="#0" class="delete-item" >Delete</a></div></div></div></li>');
cartList.prepend(productAdded);
}
<div class="cd-cart">
<div class="wrapper">
<header>
<h2>Winkelkar</h2>
<span class="undo">Verwijder product. Ongedaan maken</span>
</header>
<div class="body">
<form id="formtosubmit" class="form-style-12" action="checkout.php" method="post">
<ul name="products">
<!-- products added to the cart will be inserted here using JavaScript -->
</ul>
</form>
</div>
<footer>
<a id="checkoutbtn" class="checkout btn" onclick="document.getElementById('formtosubmit').submit()"><em>Ga verder: €<span>0</span></em></a>
</footer>
</div>
</div>
You can create <input type='hidden'/> element in between those <li> tags and write each product ID or product name to the value of that <input> tag. This way when you submit your form, those values will be captured.
EX:
function addProduct() {
var productid = document.getElementById('product').value;
var product = products[type];
//this is just a product placeholder
//you should insert an item with the selected product info
//replace productId, productName, price and url with your real product info
var productAdded = $('<li class="product" name="product' + i + '">' +
'<div class="product-image">' +
'<a href="image">' +
'<img src="images/' + product + '.jpg" alt="placeholder"></a>' +
'</div>' +
'<div class="product-details">' +
'<a style="color: black;">' + product + '</a>' +
'<span class="price">€ ' + price + '</span><br>' +
'<div class="quantity">' +
'<input type="hidden" value="'+productid+'" readonly name='productid[]'>' +
'<label>Aantal: ' + qty + '</label> <div class="actions">' +
' <a href="#0" class="delete-item" >Delete</a></div></div></div></li>');
cartList.prepend(productAdded);
}
Now you may have noticed what is that name='productid[]' in input tag? That means create an array of every input value particular to that element. More information can be found here.
Another approach would be saving your selected product IDs into a cookie/session variable. Then your server side can access that information and process the cart accordingly. If you were to delete a product from the cart then make sure you update your session/cookie value as well.

Bootstrap buttons not getting highlighted when clicked

I have an app with 3 buttons, the 3 buttons make an AJAX call to retrieve some data and redraw a table with the data. However when clicked the button should be kept highlighted so the user knows which data they are viewing.
This is the JS code that calls the Web API method:
iniciativasEstrategicas.GetVistaActividades = function (filtro) {
var idObjetivoValue = sessionStorage.idObjetivoValue;
$('#tab_vista1').html('<br><br><br><img class="loadImage" src="Images/loader.gif" />');
$.ajax({
url: 'IniciativasEstrategicasWebPart/GetVistaActividades',
type: 'POST',
data: {
idObjetivo: idObjetivoValue,
filtro: filtro
},
success: function (data) {
drawVistaActividades(data);
},
error: function (data) {
showErrorMessage(data);
}
});
}
This is the method that draws the data:
function drawVistaActividades(data) {
resetBreadCrumb();
var html = "";
for (var i = 0; i < data.length; i++) {
html += template.rowVistaActividades
.replace("{0}", data[i].nombreActividad)
.replace("{1}", data[i].iniciativaName)
.replace("{2}", data[i].fechaVencimiento)
.replace("{3}", data[i].fechaRealTerminacion)
.replace("{4}", data[i].responsables);
}
$("#tab_vistaActividades").html("<br>" + "<br>" + template.tableVistaActividades.replace("{0}", html));
}
This is the table template that I use to draw the data, and the buttons are there
tableVistaActividades: "<div>" +
"<div>" +
"<div class=\"btn-group\" role=\"group\" aria-label=\"Basic example\">" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('A tiempo')\">A tiempo</button>" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('Atrasadas')\">Atrasadas</button>" +
"<button type=\"button\" class=\"btn btn-default\" onclick=\"iniciativasEstrategicas.GetVistaActividades('Pendientes')\">Pendientes</button>" +
"</div>" +
"</div>" +
"<table class='table'>" +
"<thead>" +
"<tr>" +
"<th>" +
"Actividad" +
"</th>" +
"<th>" +
"Iniciativa" +
"</th>" +
"<th>" +
"Fecha propuesta" +
"</th>" +
"<th>" +
"Fecha real terminación" +
"</th>" +
"<th>" +
"Responsables" +
"</th>" +
"</tr>" +
"</thead>" +
"<tbody>" +
"{0}" +
"</tbody>" +
"</table>" +"<div>",
and the row template
rowVistaActividades: "<tr>" +
"<td>" +
"{0}" +
"</td>" +
"<td>" +
"{1}" +
"</td>" +
"<td>" +
"{2}" +
"</td>" +
"<td>" +
"{3}" +
"</td>" +
"<td>" +
"{4}" +
"</td>" +
"</tr>",
As you can see in this page.
We are using the same Bootstrap button code and in that page the button remains highlighted when clicked.
This should solve your problem, basically you need to add "active" to selected option and remove "active" from siblings which was previously selected.
$(".btn-group > .btn").click(function(){
$(this).addClass("active").siblings().removeClass("active");
$(this).addClass("active");
});
As #taTrifynor said in the comment, you should simply use Button groups with input type="radio", read about it. For example:
JSFiddle
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked="checked"/>Button 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off"/>Button 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3" autocomplete="off"/>Button 3
</label>
</div>
Or I don't understand what do you want.

When selecting a file, the File upload input doesn't update the value

I'm using Javascript to dynamically add floor plans where a user can add and attach images to hotel floors.
How do I make the File upload input update it's value to what the user chose?
if the button is set on page load, it works fine, but if it's generated by Javascript, then the user's choice of file to upload isn't accepted and put into the VALUE="" field (stays empty).
I recreated it using js fiddle: http://jsfiddle.net/6fays32v/1/
HTML
<div id="floor_plans_container">
<div id="unassigned">
Test
</div>
</div>
Javascript
var floor_number = $('h2').length;
var html = '<div id="0" class="plan_page">' +
' <h2 class="closeable">Floor Plan '+floor_number+'<span class="rooms_count"> </span></h2>' +
' <div class="plan_wrapper form_section">' +
' <div class="plan_form">' +
' <form target="iframe_0" enctype="multipart/form-data" method="post" action="" id="form_0" name="form_0">' +
' <input type="hidden" value="0" id="0" name="plan_id">' +
' <input type="hidden" value="" id="room_ids_db_0" name="room_ids_db">' +
' <div id="buttons_wrapper_plan">' +
' <button class="save_changes" name="plan_save" type="submit">Save</button>' +
' ' +
' </div>' +
' <table border="0" cellspacing="0" cellpadding="0" class="floor_plan">' +
' <tbody><tr>' +
' <td>' +
' <label for="name">Floor Plan Name</label>' +
' </td>' +
' <td>' +
' <input type="text" value="Floor Plan 1" id="name" name="name">' +
' </td>' +
' </tr>' +
' <tr>' +
' <td>' +
' <label for="file">Background Image</label>' +
' </td>' +
' <td>' +
' <input type="file" value="" class="file_upload" name="file_upload"> ' +
' <iframe onload="" src="" id="iframe_0" name="iframe_0" class="iframe"></iframe>' +
' </td>' +
' </tr>' +
' <tr>' +
' <td>' +
' <label for="room_size">Room Size</label>' +
' </td>' +
' <td>' +
' <div class="room_size on"></div>' +
' <input type="hidden" value="1" class="room_size_large" name="room_size_large">' +
' </td>' +
' </tr>' +
' </tbody></table>' +
' </form>' +
' </div>' +
' <div>' +
' <div style="" class="plan image small">' +
' </div>' +
' </div>' +
' </div>' +
' </div>';
$("#floor_plans_container #unassigned").html(html);
If you try to select a file, you'll see that the VALUE="" of the input stays the same - that's the problem.
What am I doing wrong?
Thanks in advance!
JavaScript cannot alter the value of an input of type "file". It's a security thing.
Otherwise you could do something like run all kinds of hidden forms on a page and upload files via Ajax without a user knowing about it.

Categories