on adding the item, datagrid doesn't update automatically. On refreshing only record appears.
what needs to be done in the below code to auto update the table withou refreshing.
The url is the rest api I call to add the item
function addItem(){
var data = null;
var addItem = new XMLHttpRequest();
addItem.withCredentials = true;
var eName = $('#txtempname').val();
var eDesg = $('#txtdesignation').val();
addItem.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
addItem.open("POST", "url");
addItem.setRequestHeader("authorization", "Basic cGR4OnBkeA==");
addItem.setRequestHeader("name", eName);
addItem.setRequestHeader("description",eDesg );
addItem.setRequestHeader("cache-control", "no-cache");
addItem.setRequestHeader("postman-token", "320fb698-18d9-790b-3471-3528ec60d948");
addItem.send(data);
$.ajax(
{
type:'POST',
url: 'url',
success:function(){
//s console.log("added succesfully");
swal("Added!", "Catalog Added successfully", "success");
getItems();
if ($.fn.DataTable.isDataTable('#subsiteList')) {
$('#subsiteList').DataTable().destroy();
}
$('#subsiteList tbody').empty();
},
error:function(){
console.log("error");
}
}
);
}
maybe you should take refrence from my solution to a similar question posted below : - Refrence link
Related
I have an implementation of AJAX, How to exactly replicate this with jQuery AJAX
var request;
function sendInfo()
{
var id = document.form.bid.value;
var url="retrieve.jsp?bid="+id;
if(window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
request=new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
request.onreadystatechange=getInfo;
request.open("GET",url,true);
request.send();
} catch (e)
{
alert("Unable to connect to server");
}
}
I need to send a data bid onkeyup, display some data into the 'dispArea'
function getInfo()
{
if(request.readyState==4)
{
var val = request.responseText;
document.getElementById('dispArea').innerHTML=val;
}
}
Implement the same using jQuery AJAX
What I have tried ::
$(document).ready(function(){
$('#bookid').keyup(function(){
$.ajax({
url : 'retrieve.jsp',
data : {
bid : $('bookid').val()
},
success : function(responseText){
$('#dispArea').text(responseText);
}
});
});
});
bid is not available in the retrieve jsp file.
I didnt use # symbol in referring to the id "#bookid".
and to receive the text as html.
$(document).ready(function(){
$('#bookid').keyup(function(){
$.ajax({
url : 'retrieve.jsp',
type : 'POST',
async : 'false',
data : {
bid : $('#bookid').val()
},
success : function(responseText){
$('#dispArea').html(responseText);
}
});
});
});
I want to pass options' values to the URL whenever the users select an option. For example these are the options:
Option 1
Option 2
Option 3
And this is the URL: http://example.com/products
When he selects an option among those 3, the URL changes into this: http://example.com/products?option=option1
I tried vanilla Javascript XMLHttpRequest for this, and this is my code:
function ajaxFormValidate(_method, _url, _callback, _fallback, _sendItem) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState < 4) {
return;
}
if(xmlHttp.status !== 200) {
_fallback(xmlHttp.response);
return;
}
if(xmlHttp.readyState === 4) {
_callback(xmlHttp.response);
}
};
xmlHttp.open(_method, _url, true);
xmlHttp.send(_sendItem);
} //Set a function for AJAX Request
//Actual performance
window.addEventListener('load', function(){
var _sort = document.getElementById('sort'), _filter = document.getElementById('filter'); //Get the elements
_sort.addEventListener('change', function(){ //If the value of the field changes
var _frmData = new FormData(); //Create a new FormData object
_frmData.append('sort', _sort.value); //Append the value to this object
ajaxFormValidate('GET', location.href, function(response){
//Perform the redirection here (without reloading the page)
}, function(response){
alert("Request cannot be sent!");
}, _frmData);
}, false);
});
Recently, I don't have any ideas for this. Any help is appreciated. Thanks
This is a good way of using GET in pure Javascript:
var ajax = new XMLHttpRequest();
ajax.open("GET", "example.com/products.php?option=YOUR OPTION VALUE GOES HERE", true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
console.log(data);
}
}
And this is the jQuery way (my preferred method):
var myOption = $('.your-elenet-calss-name').val();
var myurl = "http://example.com/products.php";
var dataString="&option="+myOption+"&check=";
$.ajax({
type: "GET",
url: myurl,
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function(){//Do some stuff here. Example: you can show a preloader///},
success: function(data){
if(data =='success'){
alert('done deal...');
}
}
});
I stucked on one thing. I have a 2 grid inside checkboxes. When I selected that checkboxes I want to POST that row data values like array or List. Actually when i send one list item it's posting without error but when i get more than one item it couldn't post values.
Example of my grid
Here my ajax request and how to select row values function
var grid = $("#InvoceGrid").data('kendoGrid');
var sel = $("input:checked", grid.tbody).closest("tr");
var items = [];
$.each(sel, function (idx, row) {
var item = grid.dataItem(row);
items.push(item);
});
var grid1 = $("#DeliveryGrid").data('kendoGrid');
var sel1 = $("input:checked", grid1.tbody).closest("tr");
var items1 = [];
$.each(sel1, function (idx, row) {
var item1 = grid1.dataItem(row);
items1.push(item1);
});
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
data: JSON.stringify({ 'items': items, 'items1': items1, 'refnum': refnum }),
contentType: 'application/json',
traditional: true,
success: function (msg) {
if (msg == "0") {
$("#lblMessageInvoice").text("Invoices have been created.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
var del1 = $("#InvoiceDetail").data("kendoWindow");
del1.center().close();
$("#grdDlvInv").data('kendoGrid').dataSource.read();
}
else {
$("#lblMessageInvoice").text("Problem occured. Please try again later.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
return false;
}
}
});
This is my C# part
[HttpPost]
public string CreateInvoice(List<Pm_I_GecisTo_Result> items, List<Pm_I_GecisFrom_Result> items1, string refnum)
{
try
{
if (items != null && items1 != null)
{
//do Something
}
else
{
Log.append("Items not selected", 50);
return "-1";
}
}
catch (Exception ex)
{
Log.append("Exception in Create Invoice action of HeadOfficeController " + ex.ToString(), 50);
return "-1";
}
}
But when i send just one row it works but when i try to send more than one value it post null and create problem
How can i solve this? Do you have any idea?
EDIT
I forgot to say but this way is working on localy but when i update server is not working proper.
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
async: false,
data: { items: items, items1: items1 }
success: function (msg) {
//add codes
},
error: function () {
location.reload();
}
});
try to call controller by this method :)
function update(){
var name= document.getElementById("TextBox").value;
$.ajax({
url: '....',
type: 'post',
data: {....//many data include// 'name' : name, ....},
success: function(data) {
var replacevalue=data.replace(/[\[\]']/g,'' );
alert(replacevalue);
var stringstatus=replacevalue.replace(/['"]+/g, '');
alert(stringstatus);
if(stringstatus == "success"){
alert ("Successfully Update ")
}
else{
alert("Failed!");
return ;
}
returnToDisplayPage();
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}
function returnToDisplayPage(){
var id = document.getElementById("TextBox").text;
window.location = './DisplayPage.php?Name='+id;
}
Please suggest me. How should I do to get the updated data when click update button and refresh or reload page ? In function returnToDisplayPage() methods. I got only the name of update data and other related fields data didn't get back.
Try something like this:
$.post('url', {params}, function(response){
//Here you check if you got response from url
// And then you can do whatever you like to do with received data
if(response == 'ok'){
//do your stuff
//then
window.location.reload();
}
}
When we will get result in response then After 5 seconds page will be refresh..
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}
What I am Trying to Do:
I am trying to use settimeout to loop/run after a function is called to automatically update/refresh a div.
What Isn't Working:
To be clear settimeout is working, but the div is not automatically refreshing/updating when I enter new test data into the db. In other words, If I refresh the page, I see the new test data, but not if I let the update function run.
Code:
function update(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
console.log("Queried Database...");
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#login-box").hide();
//$("#trades").html(' ');
localStorage.setItem("wings_lastsignal", v.candel);
var lastsignal = localStorage.getItem("wings_lastsignal");
console.log(v.candel);
if(lastsignal == v.candel) {
console.log("No New Signals");
localStorage.getItem("wings_currentsignals");
if(v.signal == 'Buy') {
console.log("Current Buy Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowup"></span>'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span> <button class="tsym" id="sym_'+v.epoch+'" onClick="var a = this.innerHTML; tsclick(a);" value="'+v.symbol+'">'+v.symbol+'</button> '+v.price+' '+v.timeframe+'</span>');
} else {
console.log("Current Sell Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowdown"></span>'+v.time+'<span style="color:#fb5350;"> '+v.signal+'</span> <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button> '+v.price+' '+v.timeframe+'</span>');
}
} else {
playChing();
console.log("New Signal");
if(v.signal == 'Buy') {
console.log("Buy Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowup"></span>'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span> <button class="tsym" id="sym_'+v.epoch+'" onClick="var a = this.innerHTML; tsclick(a);" value="'+v.symbol+'">'+v.symbol+'</button> '+v.price+' '+v.timeframe+'</span>');
} else {
console.log("Sell Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowdown"></span>'+v.time+'<span style="color:#fb5350;"> '+v.signal+'</span> <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button> '+v.price+' '+v.timeframe+'</span>');
}
}
});
}
//alert(response);
//console.log(response);
}
}).then(function() { // on completion, restart
var a = localStorage.getItem("wingsaccnum");
//setTimeout(update, 10000);
setTimeout(function(){ update(a) }, 20000); // function refers to itself
console.log("Timeout");
});
}
This function is called when I a button is pressed, using this Jquery snippet:
$( "#rbuttonon" ).click(function() {
var acc = localStorage.getItem("wingsaccnum");
//refresh_box();
update(acc);
console.log('Interval set');
});
Other Notes:
To be clear, I don't mind if there is a way to always make sure this div is updated every xx amount of time, without the need to press any buttons. I believe the problem is in my code's logic, but I would greatly appreciate some assistance!