Ajax call - Which button pressed? - html

<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.js">
</script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
txtname=$("#btn1").val();
$.ajax({url:"doSome.php",data:{name:txtname},success: function(ajaxresult){
$("#ajaxrequest").html(ajaxresult);
}});
});
});
</script>
</head>
<body>
<button id="btn1" value="myButton">Click to send1</button>
<button id="btn2" value="myButton2">Click to send2</button>
<div id="ajaxrequest"></div>
</body>
</html>
How can I recognize which button pressed in line: $("#btn1").click(function(){
without having to write again the same code for btn2?

You can use a selector on all buttons and then get back the ID when clicked
$('button').click(function()
{
alert( $(this).attr('id') ); // Button ID clicked
});

You can use
$( '#btn1' ).click(function(){
submitForm( 'btnOne' );
});
$( '#btn2' ).click(function(){
submitForm( 'btnTwo' );
});
And then pass your parameter in a single function:
function submitForm( type ){
var dataString = $('#form_confirm_delete').serialize();
dataString += "&type=" + type;
$.ajax({
type: "POST",
url: "doSome.php",
data: dataString,
dataType: 'json',
cache: false,
success: (function(response)
{
alert('Yes');
})
});
}

Actually, simply use multiple selectors:
$('#btn1, #btn2').click(function(e) {
var btn1Clicked = $(this).is('#btn1');
var btn2Clicked = $(this).is('#btn2');
});

Related

Display ajax in html page

I'm using flask as a backend, and one of my endpoints is objectList, which returns data in this format:
[{name1:value1, name2:value2}, {name1:value3, name2:value4}]
In order to display this data on my html page, I'm using the following code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function){
$.ajax({
url: 'localhost:5000/objectList',
method:"GET",
success: function(result){
$("#div1").html(result);
};
});
};
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
This doesn't display any data. What am I doing wrong and how can I fix this?
Edit: just a clarification, I want the data to load when the page loads, not on a button or a click
After our discussion, I find this code works properly
You have to close the parenthesis in the function ajax, and allow the access-control in the server side with this line
header("Access-Control-Allow-Origin: *");
// or replace the star with the server where you have the html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'localhost:5000/objectList',
method:"GET",
success: function(result){
// to verifiy the result
console.log(result);
var htmlOutput = '';
// the iteration of your result because you have many entries
$.each(result, function(i, item) {
htmlOutput += ''+
'<ul>'+
'<li>name1: '+item['name1']+'</li>'+
'<li>name2: '+item['name2']+'</li>'+
'</ul>';
});
$("#div1").html(htmlOutput);
}, error: function(jqXHR, textStatus, error) {
// to verifiy either there is an error or not
console.error(textStatus);
}
});
});
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>

how to display data from database into an option tag html?

any one can help me with this?
i want to displaying my database data into a option tag but it not showing anything. i have try to make a code for that but that code not work to display my data into html option tag. someone please help me to solve my problem.
this is my code that i make
// JavaScript Document
// for make the option tag
$(function() {
$('#chkveg').multiselect({
includeSelectAllOption: true
});
});
// for call the data from my database
$(document).on('click','#nama_check',function(e){
$.ajax({
type:"POST",
url:"../php/absen/absen_karyawan_autocomplete.php",
success: function(data){
var list = JSON.parse(data);
for(var i=0; i < list.length; i++){
$('#chkveg').val((list[i]['bagian']));
}
return false;
}
});
});
<script src="https://davidstutz.github.io/bootstrap-multiselect/docs/js/bootstrap-3.3.2.min.js"></script>
<link href="https://davidstutz.github.io/bootstrap-multiselect/docs/css/bootstrap-3.3.2.min.css" rel="stylesheet"/>
<link href="https://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" rel="stylesheet"/>
<script src="https://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>
<form id="form1" method="post">
<div style="padding:20px">
<select id="chkveg" multiple="multiple">
</select>
</div>
</form>
You have two issues here. Firstly to add values to the select you need to append new option elements to it, not repeatedly set the val(). Secondly, you should call multiselect() after the options have been added.
Also note that you can place all code within a single document.ready handler. Try this:
$(function() {
$(document).on('click','#nama_check',function(e){
$.ajax({
type: "POST",
url: "../php/absen/absen_karyawan_autocomplete.php",
dataType: 'json',
success: function(data) {
var html = '';
for(var i = 0; i < data.length; i++) {
html += '<option>' + data[i]['bagian'] + '</option>';
}
$('#chkveg').html(html).multiselect({
includeSelectAllOption: true
});
}
});
});
});
Use .append().
Try to check this documentataion: http://api.jquery.com/append/
dataType: 'json',
success: function(data){
var list = JSON.parse(data);
for(var i=0; i < list.length; i++){
$('#chkveg').append($('<option>'+ list[i]['bagian'] +'</option>'));
}
return false;
}

How to implement cancel functionality using knockout.js

I am working on a asp.net MVC project. and i am using knockout.js on my view page.
I am trying to develop a data entry grid. Everything works fine except Cancel button.
If i change something on my UI ( view) and clicked on cancel , It is not showing me old values .it only show me the latest values.
Steps:
When i click on edit button it display update and cancel button.
Let us say i have edited data and click on cancel , it should not reflect on my UI.
Right now , even if you edit and click on cancel button , it is able to revert to old state.
I am not going back to old state when i clickd on cancel button.
Please suggest me some examples .
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Type Lookup....</title>
<script src="~/Scripts/jquery-2.1.0.js"></script>
<script src="~/Scripts/knockout-3.0.0.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script type="text/javascript">
viewModel = {
lookupCollection: ko.observableArray()
};
//wrapper to an observable that requires accept/cancel
ko.protectedObservable = function (initialValue) {
//private variables
var _actualValue = ko.observable(initialValue),
_tempValue = initialValue;
//computed observable that we will return
var result = ko.computed({
//always return the actual value
read: function () {
return _actualValue();
},
//stored in a temporary spot until commit
write: function (newValue) {
_tempValue = newValue;
}
});
//if different, commit temp value
result.commit = function () {
if (_tempValue !== _actualValue()) {
_actualValue(_tempValue);
}
};
//force subscribers to take original
result.reset = function () {
_actualValue.valueHasMutated();
_tempValue = _actualValue(); //reset temp value
};
return result;
};
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Home/GetIndex",
}).done(function (data) {
$(data).each(function (index, element) {
var mappedItem =
{
Id: ko.observable(element.Id),
Key: ko.observable(element.Key),
Value: ko.observable(element.Value),
Mode: ko.observable("display")
};
viewModel.lookupCollection.push(mappedItem);
});
ko.applyBindings(viewModel);
}).error(function (ex) {
alert("Error.....");
});
$(document).on("click", ".kout-edit", null, function (ev) {
var current = ko.dataFor(this);
current.Mode("edit");
});
$(document).on("click", ".kout-update", null, function (ev) {
var current = ko.dataFor(this);
saveData(current);
current.Mode("display");
});
$(document).on("click", ".kout-cancel", null, function (ev) {
var current = ko.dataFor(this);
current.Mode("display");
});
$(document).on("click", "#create", null, function (ev) {
var current = {
Id: ko.observable(0),
Key: ko.observable(),
Value: ko.observable(),
Mode: ko.observable("edit")
}
viewModel.lookupCollection.push(current);
});
function saveData(currentData) {
var postUrl = "";
var submitData = {
Id: currentData.Id(),
Key: currentData.Key(),
Value: currentData.Value()
};
if (currentData.Id && currentData.Id() > 0) {
postUrl = "/Home/Edit"
}
else {
postUrl = "/Home/Create"
}
$.ajax({
type: "POST",
contentType: "application/json",
url: postUrl,
data: JSON.stringify(submitData)
}).done(function (id) {
currentData.Id(id);
}).error(function (ex) {
alert("ERROR Saving....");
})
}
});
</script>
</head>
<body>
<div>
<p>
<button class="btn btn-primary" id="create">Create</button>
</p>
<table class="table">
<tr>
<th>Key
</th>
<th>Value
</th>
<th>Action
</th>
</tr>
<tbody data-bind="foreach: lookupCollection">
<tr data-bind="template: { name: Mode, data: $data }">
</tr>
</tbody>
</table>
<script type="text/html" id="display">
<td data-bind="text: Key"></td>
<td data-bind="text: Value"></td>
<td>
<button class="btn btn-success kout-edit">Edit</button>
<button class="btn btn-danger kout-delete">Delete</button>
</td>
</script>
<script type="text/html" id="edit">
<td>
<input type="text" data-bind="value: Key" /></td>
<td>
<input type="text" data-bind="value: Value" /></td>
<td>
<button class="btn btn-success kout-update">Update</button>
<button class="btn btn-danger kout-cancel">Cancel</button>
</td>
</script>
</div>
</body>
</html>
I have modified your code little bit.
var mappedItem =
{
Id: ko.observable(element.Id),
Key: ko.observable(element.Key),
Value: ko.observable(element.Value),
Mode: ko.observable("display"),
oldData: ko.observable()
};
I have added oldData observable to retain previous data when edit button clicked. So now when you click on cancel data will be restored by "olData" observable.
see the below code.
$(document).on("click", ".kout-edit", null, function (ev) {
var current = ko.dataFor(this);
current.oldData(ko.toJS(current));
current.Mode("edit");
});
$(document).on("click", ".kout-update", null, function (ev) {
var current = ko.dataFor(this);
current.oldData(null);
saveData(current);
current.Mode("display");
});
$(document).on("click", ".kout-cancel", null, function (ev) {
var current = ko.dataFor(this);
current.Id(current.oldData().Id);
current.Value(current.oldData().Value);
current.Key(current.oldData().Key);
current.Mode("display");
current.oldData(null);
});
Here is working example on Jsfiddle
Use this
ko.observable.fn.revertable = function () {
var self = this, originalValue = self();
if (!originalValue) {
self.subscribe(function () {
originalValue = originalValue || self();
});
}
self.commit = function () {
originalValue = self();
};
self.revert = function () {
self(originalValue || '');
};
self.isDirty = function () {
return (self() != originalValue);
};
return self;
};
and your observables like this
this.text=ko.observable().revertable();
i assume you have cancel function so in that you can do it like
this.text.revert();
and if you want to save those changes then
this.text.commit();
You have the protectedObservable in your code, but you're not using it. Turn your 'model' (the data you want to 'cancel') into a protectedObservable. On cancel, call data.reset(). On save, call data.commit().
Little example (not complete):
$(document).on("click", ".kout-cancel", null, function (ev) {
var current = ko.dataFor(this);
current.reset();
current.Mode("display");
});
$(document).on("click", "#create", null, function (ev) {
var current = ko.protectedObservable({
Id: ko.observable(0),
Key: ko.observable(),
Value: ko.observable(),
Mode: ko.observable("edit")
});
viewModel.lookupCollection.push(current);
});

Can't fadeOut div element with AJAX

I can't understand why I can't fade out div element. I'm trying to delete mysql entry, delete function working fine when I reload a page entry dissapears, but I need that entry dissapear without page refresh. tried to creat new empty div and fade out it after entry deletion, worked fine.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a[id^='delete']").click(function() {
var numrow = $(this).attr("id");
numrow = numrow.substr(6);
var eil = 'id=' + numrow;
$.ajax({
type: 'POST',
url: 'trinti.php',
data: eil,
success: function() {
numrowas = "#d"+numrow;
$(numrowas).fadeOut();
}
});
});
});
</script>
<?php
require_once('db.php');
if (isset($_GET['list'])) {
$query = "SELECT * FROM zinutes";
mysql_query("SET NAMES 'UTF8'");
$uzklausa=mysql_query($query);
$i = 1;
while($lauk = mysql_fetch_array($uzklausa)){
$r = $lauk['id'];
echo '<div id="d$r">'.$i++.'. Name: '.$lauk['name'].' Message: '.$lauk['message'].' Delete</div>';
}
}
?>
try to do the fading from complete: block.
$.ajax({
type: 'POST',
url: 'trinti.php',
data: eil,
success: function() {
}
complete: function() {
numrowas = "#d"+numrow;
$(numrowas).fadeOut();
}
});

jquery form submit action doesn't work on document.ready

I have this jQuery code:
$(document).ready(function() {
$.ajax({
url: "pages/"+page+".php",
cache: false
}).done(function( html ) {
$('#main').html(html).css({"max-height":mH-30,"height":mH-30}).jScrollPane();
$('form').not('#loginf').submit(function(event) {
event.preventDefault();
var inputs = $(this).serialize();
$.ajax({
url: "pages/"+page+".php?"+inputs+'&action='+param,
cache: false
}).done(function( html ) {
update(html);
rs();
}).fail(function (){
window.location = "/CMS/";
});
});
});
So the submit function on the forms doesn't work..
What's intresting is that I also have another ajax on the page when some li element get clicked and on the done function there I also have the form submit function and it works there.
Is there something wrong with this code?
Try this.
$(document).ready(function() {
$.ajax({
url: "pages/"+page+".php",
cache: false
}).done(function( html ) {
$('#main').html(html).css({"max-height":mH-30,"height":mH-30}).jScrollPane();
$('form').not('#loginf').submit(function(event) {
event.preventDefault();
var inputs = $(this).serialize();
$.ajax({
url: "pages/"+page+".php?"+inputs+'&action='+param,
cache: false
}).done(function( html1 ) {
update(html1);
rs();
}).fail(function (){
window.location = "/CMS/";
});
}); });
Never mind, i solved it by looking into this question answers:
problems with ajax request in page with form. jquery
The problam was as they said there with the function(event) so I changed it to function(e) wierd why the first one didn't work.