moving data to $.ajax's out? - javascript

I want to move "data" variable to out of success function for other operation.
$("a[class=note]").click(function( evt ){
var note = $(this).attr("value");
var preid = $(this).attr("id");
$.ajax({
type: 'GET',
url: 'style/ajax.php',
data: 'do=note&value=' + note + '&preid=' + preid,
success: function(data)
{
alert(data);
}
});
});
For example php have Global pharase..

global var(which is the worse solution, but this is what you asked for):
$("a.note").click(function( evt ){
var note = $(this).attr("value");
var preid = $(this).attr("id");
$.ajax({
type: 'GET',
url: 'style/ajax.php',
data: 'do=note&value=' + note + '&preid=' + preid,
success: function(data)
{
window.data = data;
alert(data);
}
});
});
global variable are dangerous, Maybe variable outside the success scope is enough?
Var outside the success callback:
$("a.note").click(function( evt ){
var note = $(this).attr("value");
var preid = $(this).attr("id");
var dataFromServer = null;
$.ajax({
type: 'GET',
url: 'style/ajax.php',
data: 'do=note&value=' + note + '&preid=' + preid,
success: function(data)
{
dataFromServer = data;
alert(data);
}
});
});
Last option is to have a hidden input that will store the data;
success: function(data)
{
$('#hiddenFieldId').val(data);
alert(data);
}
Things to notice:
I changed your selector from a[class=note] to a.note which is better.
success is a callback which means it will not be fired until the response reach the client, until then your global\outside var\hidden input value will be null. if you don't want the ajax to be asynchronous you can define it in the options like this:
$.ajax({
async: false, // <---
type: 'GET',
url: 'style/ajax.php',
data: 'do=note&value=' + note + '&preid=' + preid,
success: function(data)
{
dataFromServer = data;
alert(data);
}
});

$("a[class=note]").click(function( evt ){
var note = $(this).attr("value");
var preid = $(this).attr("id");
$.ajax({
type: 'GET',
url: 'style/ajax.php',
data: 'do=note&value=' + note + '&preid=' + preid,
success: function(data)
{
window.data = data;
}
});
});
Of course you can't use it until the callback fires.

Define var data = null; above all your code, that would be global variable. After that, rename argument for process function and in function body window.data = response;.
EDIT
You can define function to trigger data changes, for example:
var data = null;
function setGlobal(v) {
window.data = v;
alert(window.data);
}
$("a[class=note]").click(function( evt ){
var note = $(this).attr("value");
var preid = $(this).attr("id");
$.ajax({
type: 'GET',
url: 'style/ajax.php',
data: 'do=note&value=' + note + '&preid=' + preid,
success: function(data){
setGlobal(data);
}
});
});
Try it...

Related

Jquery, Why last function in script not work?

please tell me where I am making a mistake in this code, all functions except the last one are being processed, I can not understand why. The first 3 functions correctly submit the form and receive a response, the latter also submits the form, but for some reason the response opens on a new page.
jQuery(document).submit(function(e){
var form = jQuery(e.target);
var id = form.attr("action");
var ret = id.replace('/changepswd/','');
if(form.is("#changepswd")){
e.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
document.getElementById("changepswdbtn" + ret).value = '';
alertTimeout(data,1000);
}
});
}
});
jQuery(document).submit(function(n){
var form = jQuery(n.target);
var id = form.attr("action");
var ret = id.replace('/changeemailpass/','');
if(form.is("#changeemailpass")){
n.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
document.getElementById("changeemailpassbtn" + ret).value = '';
alertTimeout(data,1000);
}
});
}
});
jQuery(document).submit(function(q){
var form = jQuery(q.target);
var id = form.attr("action");
var ret = id.replace('/changename/','');
var btns = document.getElementById("changenamebtn" + ret).value;
if(form.is("#changename")){
q.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
if (data == "Имя Успешно Изменено!"){
document.getElementById("changenamelbl" + ret).innerText = btns;
document.getElementById("changenamebtn" + ret).value = '';
alertTimeout(data,1000);
}
else{
alertTimeout(data,1000);
}
}
});
}
});
jQuery(document).submit(function(o){
var form = jQuery(o.target);
var id = form.attr("action");
var ret = id.replace('/changeemail/','');
var btns = document.getElementById("changeemailbtn" + ret).value;
if(form.is("#changeemail")){
o.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
if (data == "Email Успешно Изменен!"){
document.getElementById("changeemaillbl" + ret).innerText = btns;
document.getElementById("changeemailbtn" + ret).value = '';
alertTimeout(data,1000);
}
else{
alertTimeout(data,1000);
}
}
});
}
});

ajax delete after success text field should be empty

this my j query code for delete request
i want after delete text field will be empty
$(document).on('click','.yes_confirm',function() {
var relf=$(this).attr('data-rel');//alert(relf);
if(relf != ''){
var $that = $(this);
event.preventDefault();
var cotext_id = $('input[id="cotext_id_'+relf+'"]').val();
var object_id = $('input[id="object_id_'+relf+'"]').val();
var object_origen = $('input[id="object_origen_'+relf+'"]').val();
jQuery.ajax({
type: "POST",
url: $.ISA.options.base_url + "contest/admin/delete_note/",
dataType: 'json',
data: { cotext_id: cotext_id, object_id: object_id, object_origen: object_origen },
success: function(data) {
$('.popup_main').css('display','none');
$(this).closest('.del_edit_opt').find('input[name="name"]').val('');
},
});
}
});
this is my text field
" value="">

Ajax inside a While Loop Crashes in Javascript

I want a while loop that iterates if the amount paid is greater than zero. But running the code crashes the browser.
var amount = Number($('#payment1').val());
while (amount > 0){
$.ajax({
type: "POST",
url: baseurl + "collection/getSingleAmort",
data: {'contractid':contractID},
success: function(result){
var data = jQuery.parseJSON(result);
console.log(data);
var amortizationAmount = Number(data['amortization'][i].amortization_amount);
amount = amount -amortizationAmount;
},
error: function (errorThrown){
//toastr.error('Error!', 'Operation Done');
//console.log(errorThrown);
}
});
}
function xyz(amount){
$.ajax({
type: "POST",
url: baseurl + "collection/getSingleAmort",
data: {'contractid':contractID},
success: function(result){
var data = jQuery.parseJSON(result);
console.log(data);
var amortizationAmount = Number(data['amortization'][i].amortization_amount);
amount = amount -amortizationAmount;
if(amount>0)
xyz(amount);
},
error: function (errorThrown){
//toastr.error('Error!', 'Operation Done');
//console.log(errorThrown);
}
});
}
var amount = Number($('#payment1').val());
xyz(amount);
Try something like this. Instead of looping recursion is used.
Add async:false
var amount = Number($('#payment1').val());
while (amount > 0){
$.ajax({
type: "POST",
url: baseurl + "collection/getSingleAmort",
data: {'contractid':contractID},
async:false,
success: function(result){
var data = jQuery.parseJSON(result);
console.log(data);
var amortizationAmount = Number(data['amortization'][i].amortization_amount);
amount = amount -amortizationAmount;
},
error: function (errorThrown){
//toastr.error('Error!', 'Operation Done');
//console.log(errorThrown);
}
});
}

dynamic select box duplicating results

I'm trying to build mutiple select boxes that dymaically populate then next select box based on the option selected.
it seems to be working but the 3rd select box has duplicate results and i can't see why
here is the JS
$(document).ready(function() {
$('.selectchange').one('change', function() {
var x = $(this).children(":selected").attr("value");
console.log(x)
$.ajax({
type: "POST",
data: "id=" + x,
url: "../complaints/index.php/complaint/get_complaint_sub_types",
dataType: "json",
success: function(data) {
var x = $(this).children(":selected").attr("id");
$.each(data, function(id, value) {
var opt = $('<option />');
opt.val(value.id);
opt.text(value.name);
$('.selectchange1').append(opt);
$('.selectchange2').one('click', function(event) {
var y = $(this).children(":selected").attr("value");
$.ajax({
type: "POST",
data: "id=" + y,
url: "../complaints/index.php/complaint/get_complaint_description",
dataType: "json",
success: function(data1) {
if (data1 != " ") {
var z = $(this).children(":selected").attr("id");
console.log(z);
$.each(data1, function(id, value) {
var opt = $('<option />');
opt.val(value.id);
opt.text(value.name);
$('.selectchange2').append(opt);
})
};
}
})
});
});
}
});
});
})
here is the jsfiddle http://jsfiddle.net/7mg3ume5/2/

Parsing multiple xml files with Jquery

I have multiple xml files that I am trying to parse using JQuery. So far, I've only found success by parsing each file individually. I'm new at this and my code is very long and repetitive. I'd appreciate any help scaling it down. Here is my js:
$.ajax({
type: "GET",
url: "docs/doc1.xml",
dataType: "xml",
success: parseXml1
});
$.ajax({
type: "GET",
url: "docs/doc2.xml",
dataType: "xml",
success: parseXml2
});
$.ajax({
type: "GET",
url: "docs/doc3.xml",
dataType: "xml",
success: parseXml3
});
function parseXml1(xml){
var gen = $(xml).find("subsystem").eq(0);
var title = gen.find("title").text();
var text = gen.find("text").text();
$("#Title01").html(title);
$("#Text01").html(text);
};
function parseXml2(xml){
var gen = $(xml).find("subsystem").eq(0);
var title = gen.find("title").text();
var text = gen.find("text").text();
$("#Title02").html(title);
$("#Text02").html(text);
var sys = $(xml).find("subsystem").eq(1);
var title = sys.find("title").text();
var text = sys.find("text").text();
$("#Title02-1").html(title);
$("#Text02-1").html(text);
};
function parseXml3(xml){
var gen = $(xml).find("subsystem").eq(0);
var title = gen.find("title").text();
var text = gen.find("text").text();
$("#Title03").html(title);
$("#Text03").html(text);
var sys = $(xml).find("subsystem").eq(1);
var title = sys.find("title").text();
var text = sys.find("text").text();
$("#Title03-1").html(title);
$("#Text03-1").html(text);
};
And my xml is set up as follows:
<root>
<subsystem>This is information 1</subsystem>
<subsystem>This is information 2</subsystem>
</root>
So I have multiple nodes with no attributes that I am trying to access one by one within each xml file. Then, I am trying to put that text into a div on my HTML page. There has to be a better way to do this.
Make it a function call
function parseFile( path, titleId, textId) {
function parseXml(xml){
var subSystems = $(xml).find("subsystem");
var gen = subSystems.eq(0);
var title = gen.find("title").text();
var text = gen.find("text").text();
$("#" + titleId).html(title);
$("#" + textId).html(text);
if ( subSystems.length===2 ) {
var sys = subSystems.eq(1);
var title = sys.find("title").text();
var text = sys.find("text").text();
$("#" + titleId + "-1").html(title);
$("#" + textId + "-1").html(text);
}
};
$.ajax({
type: "GET",
url: path,
dataType: "xml",
success: parseXml
});
}
parseFile("docs/doc1.xml", "Title01", "Text01");
parseFile("docs/doc2.xml", "Title02", "Text02");
parseFile("docs/doc3.xml", "Title03", "Text03");
and you can make it smaller, by getting rid of that if check and doing a loop
function parseFile( path, titleId, textId) {
function parseXml(xml){
$(xml).find("subsystem").each(
function(ind) {
var gen = jQuery(this);
var title = gen.find("title").text();
var text = gen.find("text").text();
var ext = ind===0 ? "" : "-" + ind;
$("#" + titleId + ext).html(title);
$("#" + textId + ext).html(text);
}
);
};
$.ajax({
type: "GET",
url: path,
dataType: "xml",
success: parseXml
});
}
parseFile("docs/doc1.xml", "Title01", "Text01");
parseFile("docs/doc2.xml", "Title02", "Text02");
parseFile("docs/doc3.xml", "Title03", "Text03");

Categories