Js variable does not update in ajax - javascript

I use jstree and want to reload it with new data but I cannot send it to new data.
var $driver = 0;
$(document).ready(function () {
$('#tree_folder').jstree({
'core': {
'check_callback': true,
"themes": {
"responsive": false
},
'data': {
type: "POST",
url: "Doc.aspx/Folder",
data: function () { return '{"driver":"' + $driver + '"}' },
contentType: "application/json"
}
}
});
});
$(document).on('click', '.tile', function () {
var $item = $(this);
var $driver = $item.attr('data-driver');
// alert($driver);
$('#tree_folder').jstree('refresh');
});
I got the new value when clicked, it send old default data every time. Above in alert function, it can give me the right value although json post send default one even data is written with function
function () { return '{"driver":"' + $driver + '"}' }
How can I get the new value from variable?

Remove var before $driver from .tile click function as you are created global previously,
Try this,
$(document).on('click', '.tile', function () {
var $item = $(this);
$driver = $item.attr('data-driver'); // remove var from this line
// alert($driver);
$('#tree_folder').jstree('refresh');
});
Also use cache:false in jstree like,
function getDriver() {
return '{"driver":"' + $driver+ '"}';
}
$(document).ready(function () {
$('#tree_folder').jstree({
'core': {
'check_callback': true,
"themes": {
"responsive": false
},
cache: false, // cache false
'data': {
type: "POST",
url: "Doc.aspx/Folder",
data: getDriver(), // get updated driver
contentType: "application/json"
}
}
});
});
Also take a look on change ajax options in jstree from server

Related

Reload DATATABLE inside AJAX success without refreshing page

I have a table using Datatable plugin. I have filtered what I want to delete and after deletion, I manage to empty the value.
After that, if I want to filter using the same text again, for example, I have ba 1 and ba 2 and after deleting ba 1, it still shows the cell when I entered ba on the filter textarea field. It suppose to display the remaining ba which are not deleted yet.
For your information, I'm not using built in Datatable Ajax method.
what I'm trying to do is I want it to reload the table with the new data without refreshing the page after ajax on success. How to do that?
My datatable :
var table1 = $('#table1').DataTable(
{
pageLength : 500,
lengthChange: false,
deferRender: true,
scrollY: 800,
scrollCollapse: true,
scrollX: true,
bSort: false,
cache: true,
autoWidth: false,
columnDefs: [
{
targets: 0,
checkboxes:
{
selectRow: true
}
}
],
select: {
style: 'multi',
selector: 'td:not(:nth-child(4), :nth-child(5), :nth-child(6), :nth-child(9), :nth-child(10), :nth-child(13), :nth-child(14), :nth-child(15), :nth-child(16), :nth-child(17), :nth-child(18), :nth-child(19), :nth-child(20), :nth-child(21), :nth-child(22), :nth-child(23), :nth-child(24), :nth-child(25))'
}
});
Here's my filtering function code :
table1.columns().every(function ()
{
var table = this;
$('.filter', this.header()).on('keyup change', delay(function (settings, data, dataIndex)
{
if (table.search() !== this.value)
{
table.search(this.value).draw();
}
}, 500));
});
Here's my AJAX success code for deletion based on selected checkbox:
$('.btnN2').click(function(){
var answer = confirm('Delete N2 : Are you sure you want to delete selected items?');
if (answer)
{
console.log('yes');
var rows = $(table1.rows({selected: true}).$('input[type="checkbox"]').map(function()
{
return $(this).prop("checked") ? $(this).closest('tr').attr('data-getstockcode') : null;
}));
var getstockcodes = [];
$.each(rows, function(index, rowId)
{
console.log(rowId)
getstockcodes.push(rowId);
});
$.ajax({
url: 'del_n2',
type: 'GET',
data: {"getstockcodes": JSON.stringify(getstockcodes)},
dataType: 'JSON',
success:function(data){
console.log(data);
$(table1.rows({selected: true}).$('input[type="checkbox"]').map(function()
{
if($(this).prop("checked"))
{
$(this).parents("tr:eq(0)").find(".note2").val('');
console.log('reset');
}
}));
}
});
}
else
{
console.log('cancel');
}
});
Here's my insert data based on keyup event
$(".note2").keyup(delay(function()
{
var stockcode = $(this).data("stockcode");
var stockname = $(this).data("stockname");
var value = $(this).val().replace(/(\r\n|\n)/g, "\\n");
$.ajax({
url: 'saveNote2',
type: 'GET',
data: 'stockcode='+stockcode+'&stockname='+stockname+'&value='+value,
dataType: 'JSON',
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
}, 300));
Just add this in your success function
table1.ajax.reload()
If you are using ajax datatable or local you need to make it like this
table1.clear();
table1.rows.add(your response data array);
table1.draw()

Storing JSON result from ajax request to a javascript variable for Easyautocomplete

I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});

Getting a 500 internal server error thanks to some javascript in symfony

This is the code:
Controller:
public function isreadAction(Request $request) {
var_dump($request->get('sentValue'));
$em = $this->getDoctrine()->getEntityManager();
$pm = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findBypmid($request->get('sentValue'));
$pm->setIsRead(true);
$em->flush();
return new Response();
}
js:
$(document).ready(function () {
$(".pmcontents").hide();
$(".pmbox").click(function () {
$(this).css("font-weight", "normal");
$(this).next().toggle();
var myValue = $('this').attr('id');
var DATA = 'sentValue=' + myValue;
$.ajax({
type: "POST",
url: Routing.generate('isread'),
data: DATA,
cache: false,
success: function (data) {
alert("database has been updated");
}
});
});
});
Routing:
isread:
path: /game/isread
defaults: { _controller: LoginLoginBundle:Default:isread }
requirements:
options:
expose: true
If i click on the error it says that the variable is undefined:
Parametersapplication/x-www-form-urlencodedNiet sorteren
sentValue undefined
Bron
sentValue=undefined
What is the problem? I have tried some things and it seems that the problem lies within the ajax part of the javascript, but i'm not sure.
Replace
var myValue = $('this').attr('id'); //<- notice quote around this
with
var myValue = $(this).attr('id');

How to finish loading condition that a function to execute another function in jquery?

I have the following script to add a new value to the array of my session variable, and show me the varible totally live session
(function ($) {
Drupal.behaviors.MyfunctionTheme = {
attach: function(context, settings) {
$('.add-music').click(function () {
var songNew = JSON.stringify({
title: $(this).attr('data-title'),
artist: $(this).attr('data-artist'),
mp3: $(this).attr('href')
});
var songIE = {json:songNew};
$.ajax({
type: 'POST',
data: songIE,
datatype: 'json',
async: true,
cache: false
});
var session;
$.ajaxSetup({cache: false})
$.get('/getsession.php', function (data) {
session = data;
alert(session);
});
});
}}
})( jQuery );
the problem is that the POST shipping takes longer than the call GET ALERT then shows me the session variable not updated.
Is there a way to put an IF condition for shipping only when POST is complete return the response I GET?
thanks
Actually, what you want do do is to use a callback - that is, a function that is called as soon as your POST ajax request returns.
Example:
(function ($) {
Drupal.behaviors.MyfunctionTheme = {
attach: function(context, settings) {
$('.add-music').click(function () {
var songNew = JSON.stringify({
title: $(this).attr('data-title'),
artist: $(this).attr('data-artist'),
mp3: $(this).attr('href')
});
var songIE = {json:songNew};
$.ajax({
type: 'POST',
data: songIE,
datatype: 'json',
async: true,
cache: false
})
.done(
//this is the callback function, which will run when your POST request returns
function(postData){
//Make sure to test validity of the postData here before issuing the GET request
var session;
$.ajaxSetup({cache: false})
$.get('/getsession.php', function (getData) {
session = getData;
alert(session);
});
}
);
});
}}
})( jQuery );
Update per Ian's good suggestion I've replaced the deprecated success() function with new done() syntax
Update2 I've incorporated another great suggestion from radi8

How can I assign an HTML5 data value to an element?

I have the following code:
$.modal({
title: title,
closeButton: true,
content: content,
complete: function () {
applyTemplateSetup();
$('#main-form').updateTabs();
$('#main-form').data('action',action);
// updated to line below but still does not work
$('#main-form').data('action','Edit');
},
width: 900,
resizeOnLoad: true,
buttons: {
'Submit': function (win) {
formSubmitHandler($('#main-form'));
},
}
Once my data is loaded I am trying to set the data attribute action. I then have more code that reads it in the submit handler:
var formSubmitHandler = function (form) {
//e.preventDefault();
var $form = form;
var val = $form.valid();
if (!$form.valid || $form.valid()) {
var submitBt = $(this).find('button[type=submit]');
submitBt.disableBt();
var sendTimer = new Date().getTime();
$.ajax({
url: $form.attr('action'),
dataType: 'json',
type: 'POST',
data: $form.serializeArray(),
success: function (json, textStatus, XMLHttpRequest) {
json = json || {};
if (json.success) {
if ($form.data('action') == "Edit") {
$('#modal').removeBlockMessages()
submitBt.enableBt();
} else {
However it seems the value is not being set correctly as when I step through the code this is not getting a true value: $form.data('action') == "Edit". Am I doing something wrong?
This might be the issue.
First you do - $('#main-form').data('action',action);
I'm not entirely sure what the actionvariable holds, but from this line of your code - url: $form.attr('action') I'm going to assume you're giving the form action value. Why you do that is your concern, but I do believe it does not == "Edit".
What value do you get in your $form.data('action') ?

Categories

Resources