I have ajax code:
<script type="text/javascript">
$(".monitor").click(function(){
$("#list-format").html("");
let nama_puskesmas = $(this).data('nama');
let id_puskesmas = $(this).data('id');
let nomor = $(this).data('nomor');
let base_url = '<?php echo base_url();?>'
$.ajax({
url : 'get_data',
method : 'post',
dataType: 'json',
data : {id_puskesmas:id_puskesmas},
success : function(response){
$.each(response, function(i, obj){
$("#list-format").append("<li>"+obj.format+"</li>");
});
$("#title-modal").html(nama_puskesmas);
$("#exampleModalCenter").modal('show');
$("#button-submit").html(`Lihat data`)
$("#button-submit2").html(`Kirim Pesan`)
}
})
})
</script>
If I run this program, it will view like this:
Data yang belum diupload
1.Form Lap PTM
2.Form Lap Posbindu
3.Form Lap IVA
4.Form Lap Jiwa
5.Form Lap Indera dan Gimul
6.Form Lap Diare
7.Form Lap LROA
8.Form Lap Thypoid
9.Form Lap Laporan Hiv Aids dan IMS
10.Form Laporan Hepatitis
I will then echo this data to my another function.
How can I make a variable from this code?
$.each(response, function(i, obj){
$("#list-format").append("<li>"+obj.format+"</li>");
});
To echo on this :
$("#button-submit2").html(`Kirim Pesan`)
Or can I make an echo to this #button-submit2?
<script type="text/javascript">
// this var contains a new element, which is not yet appended to the DOM
var $receivedItems = $('<div></div>');
$(".monitor").click(function(){
$("#list-format").html("");
let nama_puskesmas = $(this).data('nama');
let id_puskesmas = $(this).data('id');
let nomor = $(this).data('nomor');
let base_url = '<?php echo base_url();?>'
$.ajax({
url : 'get_data',
method : 'post',
dataType: 'json',
data : {id_puskesmas:id_puskesmas},
success : function(response){
$.each(response, function(i, obj){
// instead of echoing it directly by appending it to the DOM, store your list items in the hidden or not-appended element in your variable
$receivedItems.append("<li>"+obj.format+"</li>");
$("#list-format").append("<li>"+obj.format+"</li>");
});
// ..... your other stuff
var buttonHtml = `Kirim Pesan`;
var $button2 = $(buttonHtml);
$button2.on('click', function(e) {
// be aware to use href only as a fallback if js does not work. otherwise your url will change and js won’t be executed
e.preventDefault();
// on click, you can append the list items stored in $receivedItems
$("#list-format").append($receivedItems.children());
});
// be aware of nesting a and button tags, you shouldn’t
$("#button-submit2").append($button2);
}
})
})
</script>
I put some comments in the code. In this approach you can store all received items in a jQuery object which is not yet appended to a DOM node. It will be by triggering the on-click event which is added to the submit2 button.
Related
I'm making this Flag/Unflag system, and it works okay. The only thing I'm struggeling with is how to update the Flag_icon, after it's been clicked? It's should be so it just changes after it's been clicked, and if it's clicked again then it changes back. Right now I have to click the flag, and then reload the page manually, and then it's changed.
$FlagStatus[$count] has the value YES/NO, from my database, and $testjobids[$count] is a unique ID from db table. I've been looking at some Ajax and Javascript to do this, but i can't seem to wrap my head around how to implement it right. I just need to be pointed into the right direction, because I'm a bit stuck.
Index.php
if ($FlagStatus[$count] == ('YES')) {
echo'<img class="Unflagging" onclick="changeImage('.$testjobids[$count].')" id="'.$testjobids[$count].'" data-id = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagMarked.png">';
} elseif($FlagStatus[$count] == ('NO')){
echo'<img class="Flagging" onclick="changeImage()" id="'.$testjobids[$count].'" data-id2 = "'.$testjobids[$count].'" src = "../Test/Images/Flag/FlagUnmarked.png">';
}
Flagging.php / Almost same as Unflagging.php
<?php
require("../resources/MysqliHandler.class.php");
require("../resources/layoutfunctions.php");
require("GetData.php");
$ICON_DIMENSION = "16px";
// Used to connect the right server Testreportingdebug or Testreporting
$db = ServerConn();
// -------------------------------------
$MysqliHandler = new mysqliHandler($db);
$MysqliHandler->query("SET NAMES UTF8");
$receiver = $_POST["FlagID"];
$MarkYes = "UPDATE `testreportingdebug`.`testjob` SET `FlagStatus` = 'YES' WHERE id = $receiver";
$query = $MysqliHandler->query($MarkYes);
?>
Ajax
echo'
<script type="text/javascript">
$(document).on("click", ".Unflagging", function(){
var FlagID = $(this).data("id");
$.ajax({
method: "post",
url: "unflagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
$(document).on("click", ".Flagging", function(){
var FlagID = $(this).data("id2");
$.ajax({
method: "post",
url: "flagging.php",
data: { FlagID: FlagID},
success: function(data) {
changeImage();
}
});
});
</script>
';
Plz check this jsfiddle. My results are like this,
http://jsfiddle.net/kz1vfnx2/
i need to store these datas to database(sql server) one by one in each row using PHP Codeigniter. Insert to table looks like
Date Frequency
05-Feb-2019 1st Basic Treatment
12-Mar-2019 2nd Control Treatment
----------------------------------
--------------------------------
when button clicks call the function and insert to datatabase
$('#saveactivityarea').on('click', function(event) { //save new activity area
var act_contractbranch_firstjobdt = "2019-01-01";
var Contractend_firstjobdt = "2020-01-01";
var act_job_freq_daysbtw= "30";
saveschedule(act_contractbranch_firstjobdt,Contractend_firstjobdt,act_job_freq_daysbtw,0);
var contractID = $('#contractID').val();
var act_job_freq_contract = $("#act_job_freq_contract option:selected").val();
$.ajax({
type: "POST",
url: 'activity_submitted',
data: {
//here i need to pass date and frequency. insert to table like one by one row
getcontract_id: contractID,
getcontractbranch_firstjobdt: act_contractbranch_firstjobdt,
//etc....
},
success: function(data) {
alert('success')
}
})
PHP MODAL FUNCTION
$data_jobschedule = array(
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq')
);
$insert_id = 0;
if ($this->db->insert("job_schedule", $data_jobschedule))
$insert_id = $this->db->insert_id();
}
Please find the jQuery Ajax code here
Inside while loop
var dataArray = [];
while(condition) {
details = [];
//do your calculations
details['date'] = date;
details['frequency'] = frequency;
dataArray[] = details;
}
$.ajax({
url: "<?php echo site_url('activity_submitted'); ?>",
data: {dateArray: dataArray},
success: function(data){
alert('success');
},
error: function() { alert("Error."); }
});
In the controller and model, you need to get the data and insert it into the table.
$data = $_REQUEST['dateArray'];
$this->db->insert_batch('mytable', $data);
I have list like this
John
Jack (link)
Husam (link)
Koko (link)
Rami (link)
Loay (link)
and i have dropdown list that has all the names above, when i click on link Husam side i want to displayed his parent (Jack) as selected option in dropdown, so i need pass to function getParentId the id of child whose the link clicked, and this id inside , so how i can pass the attr name of to $_GET['childId'] instead of $_GET['childId'] = 4.
I try to save attr of link inside php variable.
Is it or is it not possible?
This is my code in index.php
$_GET['childId'] = 4; // here i don't want to pass 4 i need to pass $(a).attr('name'); from another page
if ($object->getParentId($_GET['childId'])) {
echo "<script>
function changeParent(){
$(document).ready(function(){
$('a').on('click',function() {
var x = $(this).attr('id');
var y = $(this).attr('name');
$.ajax({
type: 'POST',
url: 'http://test.local/Family.php?action=getId',
data: {'childId' : $_GET[childId]},
success: function(msg) {
document.getElementById('names').value = x;
$('#save').show();
}
});
});
});
}
</script>";
}
This what I want to pass it in Family.php (the name of a href)
function getChild($family_tree,$parent){
$list = "<ul class='listSet' style='list-style-type:none'>";
foreach($family_tree[$parent] as $each_child) {
$list .= "<li>" . $each_child[0]." "."<a onclick='changeParent()' id='$parent' name='$each_child[1]' href='#'>".'Change parent'."</a>";
if(isset($family_tree[$each_child[1]])){...
Ok, so in order to do it you have to make some changes in your functionality.
This condition if ($object->getParentId($_GET['childId'])) you should move from index.php to Family.php
Next inside $('a').on('click',function() { change this line data: {'childId' : $_GET[childId]}, to this data: {'childId' : y},
function changeParent(){
$(document).ready(function(){
$('a').on('click',function() {
var x = $(this).attr('id');
var y = $(this).attr('name');
$.ajax({
type: 'POST',
url: 'http://test.local/Family.php?action=getId',
data: {'childId' : y},
success: function(msg) {
document.getElementById('names').value = x;
$('#save').show();
}
});
});
});
}
Hi I'm new to this javavascript/ajax. I am trying to create a dropdown that dynamically changes the images by the different options as shown in this Fiddle here but the change function does not seem to be working.
I made sure that I am able to get the data from pictureList but the image source did not change successfully as the fiddle.
$('#selectVariant').change(function () {
var sku = $('#selectVariant :selected').val();
var sessionId="<?php echo $sessionId; ?>";
var dataString='sku='+ sku +'&sessionId='+sessionId;
$.ajax({
type:"post",
url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
data:dataString,
cache:false,
dataType: "JSON",
success: function(data){
var pictureList = {};
//example of my data list
//var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
//'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
//};
$.each(data.productVariantImages,function(i, productVariantImages){
pictureList[data.sku] = this.imagePath;
});
console.log(pictureList);
$('.content img').attr({"src":[pictureList[this.value]]});
}
});
return false;
});
However, when I do test it outside the ajax post, it is able to run.
Instance of this is change in ajax success function scope.
In this line $('.content img').attr({"src":[pictureList[this.value]]}); this
is not the instance of selectVariant element.
The usual practice for this is declare a variable that and use that variable in other scope. try the below code.
$('#selectVariant').change(function () {
var sku = $('#selectVariant :selected').val();
var sessionId="<?php echo $sessionId; ?>";
var dataString='sku='+ sku +'&sessionId='+sessionId;
var that = this;
$.ajax({
type:"post",
url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
data:dataString,
cache:false,
dataType: "JSON",
success: function(data){
var pictureList = {};
//example of my data list
//var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
//'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
//};
$.each(data.productVariantImages,function(i, productVariantImages){
pictureList[data.sku] = this.imagePath;
});
console.log(pictureList);
$('.content img').attr({"src":[pictureList[that.value]]});
}
});
return false;
});
I have a function which updates a database via ajax. My issue is then how to update the data displayed on the page to show updated details. The POST data can vary and therefore the datastring would be something like this:
var dataString = '[name resource we are editing]=1' +
'¶1='+ para1 +
'¶2=' + para2+
'¶3=' + para3
I want the function below to split or loop through each of the POST variables in the datastring to update the text of an element on the page. I cannot figure out how.
function editAccount(dataString, details, form){
status = $(".status");
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/edit/",
data: dataString,
success: function(response) {
$.each(response, function(key, value) {
success_code = key;
message = value;
});
if(success_code == 1){
status.text(message).addClass("valid");
//show details and hide form
$("#" + details).show();
$("#" + form).hide();
//HOW to do below?
//update details being displayed with datasource data
//loop through dataString to assign eg. $('#para1')text(para1);
} else {
status.text(message).addClass("invalid");
}
},
error: function(response){
status.text("There was a problem updating your details into our database. Please contact us to report this error.").addClass("invalid");
}
});
}
As mentioned in a previous comment, I would suggest declaring the dataString variable as an object:
var dataString = { '[name resource we are editing]' : 1,
'para1': para1,
'para2': para2,
'para3': para3
}
Now it'll be much easier to loop over the params, just using the function each, for instance, which you already use in your code:
$.each(dataString, function(key, value) {
// Do stuff with each param
});
EDIT:
As #Qpirate suggests, you also can use the javascript for loop:
for(var key in dataString){
// value => dataString[key]
}