Sending my variable information to a url - javascript

I am using the following code to prepend information into my list and it is working fine. On top of that, I want to send the 2 variable below (listDescription and payment) to a url too as follows :
http://mywebsite.com/public/user/spent/?amount=listDescription&account=payment
I am trying to use ajax and send the information over with the following code but it is not working and I get no response alerts either way. Can I get some help on this please. Thanks.
$(document).ready( function() {
var listDescription;
var payment;
//prepending - working fine
$('#add_list').click( function() {
listDescription = $('#list_description').val();
payment = $('#payment').val();
$('.expense_list').prepend('<div>' + "\u00A3 " + listDescription + "\t\t\t" + payment + "\t" + '</div>');
//This is not working
$.ajax({
url: "htttp://mywebsite.com/public/user/spent/",
data: {
amount: listDescription,
account: payment
},
type: "GET",
async:true,
cache:false,
success: function (data) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
$('#list_form')[0].reset();
return false;
});
});

$(document).ready( function() {
//prepending - working fine
var listDescription = $('#list_description').val();
var payment = $('#payment').val();
$('#add_list').click( function() {
$('.expense_list').prepend('<div>' + "\u00A3 " + listDescription + "\t\t\t" + payment + "\t" + '</div>');
//This is not working
$.ajax({
url: "htttp://mywebsite.com/public/user/spent/",
data: {
amount: listDescription,
account: payment
},
type: "GET",
async:true,
cache:false,
success: function (data) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
$('#list_form')[0].reset();
return false;
});
});
This should work :)

May be try to add data type JSON in your AJAX Request?
dataType:'json',

Related

Ajax Call not being accessed in most pages

This is a very weird problem but I will provide as much detail as possible. This Javascript function is in a separate .js file and referenced into various HTML pages in a Cordova application. When a push notification, with 2 parameters: id, type, is received into the device, a function called LaunchFromNotif is executed with these 2 parameters passed as arguments.
function LaunchFromNotif(id, type) {
try {
var ebyidurl = url + "ReturnEByID";
var nbyidurl = url + "ReturnNByID";
if (type != null) {
if (type == "n") {
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code here
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "e") {
$.ajax({
type: 'GET',
url: ebyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "a") {
combined(id);
}
}
} catch (exception) {
//window.location = "Warning2.html";
}
}
Combined(id) is another function with 2 Ajax calls. I used when and then, to make sure that the first ajax call completes before starting the second.
function combined(id) {
alert("combined");
$.when(
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
alert("success of first ajax");
},
error: function (xhr, status, error) {
alert('Error 1: ' + error);
}
})
).then(function () {
$.ajax({
type: 'GET',
url: Verifytempurl,
data: { Username: localStorage.getItem('user') },
success: function (data) {
alert("success of second ajax");
},
error: function (xhr, status, error) {
alert('Error 2: ' + error);
}
});
});
The problem is that this is working well in only one HTML page. In 3 other pages in which I tried, it shows the "combined" alert and seems to never access the Ajax call. The logic seems to make sense, especially since it is in working order in one page. What could normally go wrong in something of the sort? I am left with few debugging possibilities, especially since this is a Cordova app and being tested on mobile devices.
Thanks in advance!

Load D3 Url With API key

I am trying to load a dataset from the URL "https://data.raleighnc.gov/resource/5ccj-g2ps.json" but it requires an API key. I have had no luck with D3 or Jquery.
How would I go about doing this so that I can load the dataset in Json format?
I have the following:
$.ajax({
url: "https://data.raleighnc.gov/resource/xce4-kemu.json",
type: "GET",
data: {
"$limit" : 5000,
"$$app_token" : "YOURAPPTOKENHERE"
}
}).done(data) {
alert("Retrieved " + data.length + " records from the dataset!");
console.log(data);
});
It says I have a misplaced "{" but I don't see where.
There are a lot of mistakes in your code...
$.ajax({
url: "https://data.raleighnc.gov/resource/xce4-kemu.json", // didn't you want to get another URL??!?
type: "GET",
dataType: "json",
data: {
"$limit" : 5000, // Does the API require the dollar signs? Looks weird.
"$$app_token" : "YOURAPPTOKENHERE" // Did you actually replace with your API key?
},
success: (data) => {
alert("Retrieved " + data.length + " records from the dataset!");
console.log(data);
},
error: (xhr, textStatus, errorThrown) => {
// error
}
});
Should be working.

JavaScript Display Loader while Controller Response

Hi I have a JQuery Function that is calling a controller when
Controller Response (success()) it is loading an iFrame;
Basically; converter is returning success function after 30 seconds, for that reason I am trying to display a loading image using
beforeSend: function()
{
},
Function I tried a lots but its not working; Could you please give me advice how can I achieve it. My code are given bellow:
var callController = function (FirstName, documentId, fileName, packet) {
$.ajax({
type: "POST",
url: "http://localhost:63902/Home/Preview?DocumentId=" + documentId + "&FileName=" + fileName + "&packet=" + packet,
cache: false,
async: false,
//controller happens...
success: function (returnedValue) {
rememberDocumentId(documentId);
location.reload("#mainIframe");
setTimeout(function () {
}, 3000);
document.getElementById("mainIframe").style.display = "none";
document.getElementById("documentIframe").style.display = "block";
document.getElementById("documentIframe").src = "http://localhost:63902/FileProcessing/PDFProcessing/TempPDF/" + returnedValue;
event.preventDefault();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " " + textStatus + " " + errorThrown);
}
});
};
you can show your loader right after or before $.ajax({...}) but you should never use async:false, this is the root of evil, it will freeze the browser while the request has not succeeded.
like this:
var callController = function (FirstName, documentId, fileName, SL) {
//here
showLoader();
$.ajax({
type: "POST",
url: "http://localhost:63902/Home/Preview?DocumentId=" + documentId + "&FileName=" + fileName + "&SL=" + SL,
cache: false,
//controller happens...
success: function (returnedValue) {
rememberDocumentId(documentId);
location.reload("#mainIframe");
setTimeout(function () {
}, 3000);
document.getElementById("mainIframe").style.display = "none";
document.getElementById("documentIframe").style.display = "block";
document.getElementById("documentIframe").src = "http://localhost:63902/FileProcessing/PDFProcessing/TempPDF/" + returnedValue;
//hide Here
hideLoader();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + " " + textStatus + " " + errorThrown);
//hide Here
hideLoader();
}
});
}

still not call with ajax in separate javascript file

I am new in jquery and ajax but my requirement is calling servlet/jsp through ajax using jquery so that my ajax code dosen't work in separate javascript file
Here is my javascript file that I called ajax through jquery :
function insertData(idvalue)
{
var forsplit = idvalue.id.split("_");
var qtsrl = forsplit[2];
var qtno = forsplit[3];
alert(qtsrl);
alert(qtno);
var queryid=idvalue.id;
var qtsrl_id = document.getElementById("qstn_srl_"+qtsrl+"_"+qtno).value;
var qstn_no_id = document.getElementById("qstn_no_"+qtsrl+"_"+qtno).value;
alert(qtsrl_id);
alert(qstn_no_id);
$.ajax(
{
url: "aftermarksave.jsp",
type: "get",
data:{setvalues : queryid},
dataType: "JSON",
success: function(data)
{
alert('Successful :'+data);
},
error: function(data)
{
alert('Not Successful: '+data);
}
});
}
Still not call to jsp page and I tried for Servlet page also that servlet is not called through ajax.
Try Like
$.ajax({
url: "URL",
type: "GET",
contentType: "application/json;charset=utf-8",
data: {setvalues : queryid},
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});
OR
$.get("URL",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});

Event handlers not getting triggered

I have the following jQuery code and it is not getting triggered on the required actions, when I take out the first 2 $("body").on functions, the third one ie. ($("body").on("click", '.upvote', function(event){) gets triggered. When I put everything back in nothing works.
$(document).ready(function () {
//function 1
$("body").on("change", '.select', function (event) {
$('.row.replace').empty();
$('.row.replace').append("<br><br><br><br><p align='center'><img id='theImg' src='/media/loading1.gif'/></p><br><br><br><br><br><br><br><br>");
var filter = $(this).find(":selected").attr("name");
$.ajax({
type: "POST",
url: "/filter_home/" + filter + "/" + "TrendingNow" + "/",
data: {
'name': 'me',
'csrfmiddlewaretoken': '{% csrf_token %}'
},
//dataType: "json",
success: function (data) {
$('.row.replace').html("mem");
},
error: function (xhr, errmsg, err) {
alert(err);
}
}); //end ajax
return false;
}); //end onchange
//function 2
$("body").on("click", '.sorter', function (event) {
$('.row.replace').empty();
$('.row.replace').append("<br><br><br><br><p align='center'><img id='theImg' src='/media/loading1.gif'/></p><br><br><br><br><br><br><br><br>");
var sort = $(this).attr("name");
var filter = $('.select').find(":selected").attr("name");
$.ajax({
type: "POST",
url: "/filter_home/" + filter + "/" + sort + "/",
data: {
'name': 'me',
'csrfmiddlewaretoken': '{% csrf_token %}'
},
success: function (data) {
$('.row.replace').html(data);
},
error: function (xhr, errmsg, err) {
alert(err);
}
}); //end ajax
return false;
}); //end onclick
//function 3
$("body").on("click", '.upvote', function (event) {
var x = $(this).attr("name");
$.ajax({
type: "POST",
url: "/upvote/" + x + "/",
data: {
'name': 'me',
'csrfmiddlewaretoken': '{{csrf_token}}'
},
dataType: "json",
success: function (json) {
var y = "vote-count" + x;
$('i[class= "' + y + '"]').text(json.vote_count);
//flip button
$('.flip' + x).find('.card').toggleClass('flipped');
},
error: function (xhr, errmsg, err) {
alert("oops, something went wrong! Please try again.");
}
}); //and ajax
return false;
}); //end onclick
}); //end ready
The event handlers (functions 1,2,3) are all returning false. This stops the event from bubbling up the DOM. I'm guessing that they're not being triggered as expected because the first function to handle the event is stopping the propagation. Test this by removing the return statement.
Alternatively, you can try scoping the delegated event handler closer to the target.

Categories

Resources