Select option based on data that comes with ajax - javascript

I have a form I created for editing style on my html page. I pull the data into this form with ajax. And in my select box list, I want whatever data in the database is selected. Others will not disappear. The list will remain the same, but the data in the database will be selected. Somehow I couldn't. How can I do it?
read.php
case "magaza":
if(isset($_REQUEST["id"])){
$result = $mk_db->oku("magaza", " id='$id' ", "", "", "");
if(!empty($result)) {
$responseArray["marka_adi"] = $result[0]["marka_adi"];
$responseArray["resim"] = $result[0]["resim"];
$responseArray["durum"] = $result[0]["durum"];
$responseArray["sira"] = $result[0]["sira"];
echo json_encode($responseArray);
}
}
break;
$(document).ready(function() {
/********************** MODAL AÇMA **********************/
$(document).on('click', '.bn-edit', function() {
var id = this.id;
console.log("id:" + id + ",type:magaza");
$.ajax({
type: "GET",
url: "read.php?id=" + id + "&type=magaza",
success: function(response) {
$("#edit-modal").modal('show');
$.each(response, function(key, value) {
console.log("key:" + key + ",value:" + value);
})
$("#duz_sira").val(response.sira);
$("#duz_durum").val(response.durum);
$("#id").val(id);
}
});
});
});
<div class="modal fade duzenle" id="edit-modal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title pl-3" id="exampleModalScrollableTitle">Markayı Düzenle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="text-white">×</span>
</button>
</div>
<form method="post" id="frmedit" enctype="multipart/form-data">
<div class="modal-body pre-scrollable">
<input type="hidden" name="id" id="id" class="form-control">
<div class="form-group form-float mt-3">
<div class="form-line">
<input type="text" class="form-control" id="duz_sira" name="duz_sira" required>
<label class="form-label">Sıra</label>
</div>
</div>
<select class="form-control" name="duz_durum" id="duz_durum" required>
<option>Durum Seçiniz</option>
<option value="aktif">Aktif</option>
<option value="pasif">Pasif</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn bg-grey waves-effect iptal-butonu" data-dismiss="modal">İptal</button>
<input type="submit" id="update" class="btn bg-purple waves-effect kaydet-butonu" value="Kaydet">
</div>
</form>
</div>
</div>
</div>
My console request:

Please study the post I made - it is a [mcve] without any needless AJAX if the PHP works, it works and is not needed in the question
You need an ID on the select:
$("#duz_durum") uses the id. if you need name, you need $("[name=duz_durum]")
const response = {
"marka_adi": "Marka 2",
"resim": "",
"durum": "aktif",
"sira": "3"
}
// $("#edit-modal").modal('show');
$.each(response, function(key, value) {
console.log("key:" + key + ",value:" + value);
})
$("#duz_sira").val(response.sira);
$("#duz_durum").val(response.durum);
// $("#id").val(id);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="modal fade duzenle" id="edit-modal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title pl-3" id="exampleModalScrollableTitle">Markayı Düzenle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="text-white">×</span>
</button>
</div>
<form method="post" id="frmedit" enctype="multipart/form-data">
<div class="modal-body pre-scrollable">
<input type="hidden" name="id" id="id" class="form-control">
<div class="form-group form-float mt-3">
<div class="form-line">
<input type="text" class="form-control" id="duz_sira" name="duz_sira" required>
<label class="form-label">Sıra</label>
</div>
</div>
<select class="form-control" name="duz_durum" id="duz_durum" required>
<option>Durum Seçiniz</option>
<option value="aktif">Aktif</option>
<option value="pasif">Pasif</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn bg-grey waves-effect iptal-butonu" data-dismiss="modal">İptal</button>
<input type="submit" id="update" class="btn bg-purple waves-effect kaydet-butonu" value="Kaydet">
</div>
</form>
</div>
</div>
</div>

Related

the ajax code didn't work on a django app

I am working on a machine learning app with Django and I have to pass the data that I wont to use in the model to a views function using ajax and Jquery but the function didn't get called at all so whenever I submit the form is show nothing I've try many solution but didn't work
ps: I am still a beginner in JS
here is the views function:
def Iris_classify(request):
print('called1')
if request.POST.get('action') =='post':
print('caled2')
sepal_length = float(request.POST.get('sepal_lenght'))
sepal_width = float(request.POST.get('sepal_width'))
petal_length = float(request.POST.get('petal_lenght'))
petal_width = float(request.POST.get('petal_width'))
model = pd.read_pickle(r"C:\Users\zakaria\Django\DataProject\Data_science\machinlearning\classifier_model.pickl")
prediction_features=[sepal_length,sepal_width,petal_length,petal_width]
result = model.predict([prediction_features])
classification = result[0]
print(classification)
return JsonResponse({'result': classification, 'sepal_length': sepal_length,
'sepal_width': sepal_width, 'petal_length': petal_length, 'petal_width': petal_width},
safe=False)
and here is the template:
{%extends 'machinlearning/base.html'%}
{%block title%}Iris classification{%endblock %}
{%block content %}
<div class='container pt-5'>
<form action ="" method="POST"id ="input_form">
{% csrf_token %}
<div class="form-group" >
<label for="sepal_length" style="color:white">Sepal Length</label>
<input type="number" step="0.1" class="form-control" id="sepal_length" placeholder="Sepal Length">
</div>
<div class="form-group" >
<label for="sepal_width">Sepal Width</label>
<input type="number" step="0.1" class="form-control" id="sepal_width" placeholder="sepal width">
</div>
<div class="form-group" >
<label for="petal_length">Petal Length</label>
<input type="number" step="0.1" class="form-control" id="petal_length" placeholder="petal_length">
</div>
<div class="form-group" >
<label for="petal_width">Petal Width</label>
<input type="number" step="0.1" class="form-control" id="petal_width" placeholder="petal width">
</div>
<button type="submit" value = "Submit" class="btn btn-primary" data-toggle="modal" data-target= "#modalex">classify</button>
</form>
</div>
<div class="modal fade" id="modalex" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Result</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="modal-body">
<h5>Prediction Input:</h5>
<div>Sepal Length: <span id="sl"></span></div>
<div>Sepal Width: <span id="sw"></span></div>
<div>Petal Length: <span id="pl"></span></div>
<div>Petal width: <span id="pw"></span></div>
<h5 class="pt-3">Prediction Classification:</h5>
<div id="prediction"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"data-dismiss="modal">Try again</button>
</div>
</div>
</div>
</div>
<script>
$(document).on("#input_form",'submit', function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'{%url "mlapps:iris"%}',
data:{
sepal_length:$('#sepal_length').val(),
sepal_width:$('#sepal_width').val(),
petal_length:$('#petal_length').val(),
petal_width:$('#petal_width').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success:function(json){
document.forms["input_form"].reset();
document.getElementByID("prediction").innerHTML=json['result']
document.getElementByID("sl").innerHTML =json['sepal_length']
document.getElementByID("sw").innerHTML=json['sepal_width']
document.getElementByID("pl").innerHTML=json['petal_length']
document.getElementByID("pw").innerHTML=json['petal_width']
},
error : function(xhr,errmsg,err) {
}
});
})
</script>
{%endblock %}

Populate modal with a mysql query reult data

i have an html page that shows data populated from mysql database.
I give to user choice to edit records. I would like to use a modal form that, when pressed edit, it open up and display data result from mysql db and realated to a certain "id".
Can you help me to achieve this?
Reading on web i've understood that i have to use jquery, but i cannot find a way.
For now i tried as following:
<form method="post">
<div class="modal fade" id="edit_grp" tabindex="-1" role="dialog" aria-labelledby="edit_grpLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="edit_grpLabel">Modifica Interno</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Sequenza Chiamata</label>
<input type="text" class="form-control" name="edit_grp_pos" id="edit_grp_pos" value="<?php echo $row[0]['grp_pos']; ?>">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Nome</label>
<input type="email" class="form-control" name="edit_grp_name" id="edit_grp_name" value="<?php echo $row[0]['grp_name']; ?>">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Interno</label>
<input type="tel" class="form-control" name="edit_grp_phone" id="edit_grp_phone" value="<?php echo $row[0]['grp_phone']; ?>">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" name="submit" value="submit" id="submit_edit_grp" class="btn btn-primary" onClick="closeAll()">Modifica</button>
</div>
</div>
</div>
</div>
</form>
EDIT 1:
I'am having some tests.
For now 've changed code like this:
`
<form method="post">
<div class="modal fade" id="edit_grp" tabindex="-1" role="dialog" aria-labelledby="edit_grpLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="edit_grpLabel">Modifica Interno</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="phone_details">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" name="submit" value="submit" id="submit_edit_grp" class="btn btn-primary" onClick="closeAll()">Modifica</button>
</div>
</div>
</div>
</div>
</form>
`
`
$(document).on('click', '.view_phone_data', function(){
var data_id = $(this).attr("id");
$.ajax({
url:"select.php",
method:"POST",
data:{data_id:data_id},
success:function(data){
$('#phone_details').html(data);
$('#edit_grp').modal('show');
}
});
});
`
and select.php
`
<?php
if(isset($_POST["data_id"]))
{
$output = '';
$connect = mysqli_connect("localhost","administrator","psw","db");
$query = "SELECT * FROM gruppioxe WHERE id = '".$_POST["data_id"]."'";
$result = mysqli_query($connect, $query);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">';
while($row = mysqli_fetch_array($result))
{
$output .= '
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Ordine Chiamata</label>
<input type="tel" class="form-control" id="'.$row["grp_pos"].'" name="'.$row["grp_pos"].'">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Nome</label>
<input type="text" class="form-control" id="'.$row["grp_name"].'" name="'.$row["grp_name"].'">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Interno</label>
<input type="tel" class="form-control" id="'.$row["grp_phone"].'" name="'.$row["grp_phone"].'">
</div>
</form>
';
}
echo $output;
}
?>
`
But still no result..
Solved!!!
i've changed select.php as following:
`
$output .= '
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Ordine Chiamata</label>
<input type="tel" class="form-control" id="grp_pos" name="grp_pos" value="'.$row["grp_pos"].'">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Nome</label>
<input type="text" class="form-control" id="grp_name" name="grp_name" value="'.$row["grp_name"].'">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Interno</label>
<input type="tel" class="form-control" id="grp_phone name="grp_phone" value="'.$row["grp_phone"].'">
</div>
</form>
';
}
echo $output;
`

Edit/Update item in angularjs

here is the html file
it contains a model popup with fields name and email id. I need to edit and update them
<tr ng-repeat="item in collection">
<a ng-click=readOne(item.id) data-toggle="modal" data-target="#myModal">Edit</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modal-product-title">Edit</h4>
</div>
<div class="modal-body">
<div><b style='color: red'>{{modalstatustext}}</b></div>
<form id="form-dinminder">
<div class="form-group">
<label for="name" class="control-label">Name</label>
<input ng-model="name" type="text" class="form-control" id="form-name" placeholder="Name">
</div>
<div class="form-group">
<label for="email" class="control-label">Email ID</label>
<input ng-model="email" type="text" class="form-control" id="form-email" placeholder="Email ID">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="btn-update-product" type="button" class="btn btn-warning" ng-click="updateProduct()">Save changes</button>
</div>
</div>
</div>
</div>
</td>
</tr>
controller.js
/***********edit************/
$scope.readOne=function(id){
console.log("selected agency id",id)
adminservice.selectedAgency(id).then(function(response){
$scope.aid = response.data[0].id;
$scope.name=response.data[0].name;
$scope.email=response.data[0].webaddress;
//update modal
$('#myModal').modal('show');
},function(error){
$scope.modalstatustext = "Unable to Update data!";
});
}
$scope.updateProduct=function(id){
var Name = $scope.name;
var Email = $scope.email;
service.updateAgency(Name,Email).then(function(response){
//alert(response.data);
$('#myModal').modal('hide');
showAll();//after updating all items are shown
},function(error){
console.log("error in updating ");
});
}
service.js
var updateAgency=function(Name,Email){
return $http({
method: "POST",
url: CONFIG.apiurl + 'edit',
params:{
name:Name,
webaddress:Email
}
});
i have no idea what i have done wrong.
Backend seems to work perfectly.
thanks
Your UpdateProduct function expects a parameter of id,
<button id="btn-update-product" type="button" class="btn btn-warning" ng-click="updateProduct(passidhere)">Save changes</button>
Remove the id parameter from your updateProduct function as this is not used.

Modal bootstrap help does not work with ajax

I have a problem with a small project for class, which does not insert the data to the database, the data I collect with a bootstrap modal and pass them to the php file using ajax. The error comes at the time of using the script, I think it is correct, but I do not execute the actions.
This is the script I use:
<script type="text/javascript">
$(document).ready(function(){
$('#confirm').click(function() {
var tk = $("#task").val();
var dt = $("#date").val();
var at = $("#amount").val();
var st = $("#status").val();
$.ajax({
type: "POST",
url: "insert.php",
data: {"task": tk, "date": dt, "amount": at, "status": st},
success: function (msg) {
$("#task").val("");
$("#date").val("");
$("#amount").val("");
$("#status").val("");
}
});
});
});
</script>
And this is the modal:
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New task</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body" id="task_insert">
<div class="form-group">
<label for="recipient-name" class="form-control-label">Task:</label>
<input type="text" required class="form-control" id="task">
</div>
<div class="form-group">
<label for="recipient-name" class="form-control-label">Date:</label>
<input class="form-control" required type="text" id="date">
</div>
<div class="form-group">
<label for="recipient-name" class="form-control-label">Amount:</label>
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<input type="number" class="form-control" required id="amount">
<div class="input-group-addon">€</div>
</div>
</div>
<div class="form-group">
<label for="recipient-name" class="form-control-label">Status:</label>
<input type="text" class="form-control" id="status" >
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="confirm" class="btn btn-success" data-dismiss="modal">Confirm</button>
</div>
</div>
</div>
</div>
Thanks to everyone for your support
Hope this will help You
add jquery at top of page:
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
then write your ajax script and get your value in insert.php page like:
$task = $_POST['task'];
echo $task;
if still not work then take form inside modal and submit form using jquery.

Jquery .html wont load the css

Says, i write this code :
<div class="modal fade" id="addnewevent">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">×</button>
<h4 class="modal-title">
New Event
</h4>
</div>
<div class="modal-body">
<form name="newevent" id="newevent" action="" method="post">
<div class="form-group">
<label for="eName">Title</label>
<input name="eName" id="eName" class="form-control" type="text">
</div>
<div class="form-group">
<label for="eDate">Date</label>
<div class="input-group date datepicker" data-date-autoclose="true" data-date-format="dd-mm-yyyy">
<input name="eDate" id="eDate" class="form-control" type="text" value="<?=date("d-m-Y",$now)?>"><span class="input-group-addon"><i class="icon-calendar"></i></span></input>
</div>
</div>
<div class="form-group">
<label for="eLevel">Event Level</label>
<select name="eLevel" id="eLevel" class="select2able" >
<option value=""></option>
<option value="1">Normal</option>
<option value="2">Urgent</option>
</select>
</div>
<div class="form-group">
<label for="eDesc">Deskripsi</label>
<textarea name="eDesc" id="eDesc" class="form-control" rows="3" maxlength="150"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="add" type="button">Add</button><button class="btn btn-default-outline" data-dismiss="modal" type="button">close</button>
</div>
</div>
</div>
</div>
This will gave me result like this picture :
http://imageshack.com/a/img542/7466/okj7.png
Then, i use :
function change(id) {
$.post('ajax/change.php', {
data: id,
rand: Math.random()
},
function (html) {
$('#changeform').html(html);
$("#modalchange").modal('show');
});
}
triggered from this button :
<a class="table-actions" href="#" onClick="change('<?=$tm['id']?>');return false;"><i class="icon-pencil"></i></a>
The code for html (from change.php) is like this :
<?php
if(isset($_POST['data'])) {
$id = $_POST['data'];
$evt = mysql_query("select * from cal_event where id = '$id'");
$evt = mysql_fetch_array($evt);
$dt = explode(",",$evt['date']);
?>
<input type="hidden" value="<?=$id?>" name="uid" />
<div class="form-group">
<label for="eName">Title</label>
<input name="eName" id="eName" class="form-control" type="text" value="<?=$evt['title']?>">
</div>
<div class="form-group">
<label for="eDate">Date</label>
<div class="input-group date datepicker" data-date-autoclose="true" data-date-format="dd-mm-yyyy">
<input name="eDate" id="eDate" class="form-control" type="text" value="<?=$dt[2]."-".($dt[1]+1)."-".$dt[0]?>"><span class="input-group-addon"><i class="icon-calendar"></i></span></input>
</div>
</div>
<div class="form-group">
<label for="eLevel">Event Level</label>
<select name="eLevel" id="eLevel" class="select2able" >
<option value=""></option>
<option <?=($evt['level']==1)?"selected":""?> value="1">Normal</option>
<option <?=($evt['level']==2)?"selected":""?> value="2">Urgent</option>
</select>
</div>
<div class="form-group">
<label for="eDesc">Deskripsi</label>
<textarea name="eDesc" id="eDesc" class="form-control" rows="3" maxlength="150"><?=$evt['deskripsi']?></textarea>
</div>
<?php
}
?>
this is modal change
<div class="modal fade" id="modalchange">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">×</button>
<h4 class="modal-title">Change Event</h4>
</div>
<div class="modal-body" >
<form name="changeform" id="changeform" action="" method="post">
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="change" type="button">Change</button><button class="btn btn-default-outline" data-dismiss="modal" type="button">Close</button>
</div>
</div>
</div>
</div>
but the result is different, it's give me like this :
http://imageshack.com/a/img89/3892/tpo5.png
So, how can i solve this problem?
and sorry for my bad in english.
From the picture you posted, the select element should not be just styled with css, there should be some javascript magic (which transform the select element to something else and hide the select element).
So you have to apply the javascript to the new html content again.

Categories

Resources