Ajax.done returning undefined - javascript

I'm a newcomer to JS and Jquery, and I can't figure out how Ajax works for the life of me.
I'm working on a website with flask, and I need a way to send to pieces of data to a url, where they're appended to a list, after which a success message pops up.
However, I can't seem to get this properly.
$(document).ready(function(){
$("#newPatternForm").on("submit", function(event){
var setClass = document.getElementById("classes").value;
var newPattern = $("#newPattern").val();
$.ajax({
data:{
setClass: setClass,
newPattern: newPattern,
},
type: "POST",
url: "/get_pattern",
}).done(function(data){
alert("success")
var successMsg = "<p>Class: " + data + "<br>Pattern: " + data;
$("#newPatternFooter").append($.parseHTML(successMsg));
});
});
});
The Flask code
#app.route('/get_pattern', methods=["POST"])
def get_pattern():
set_class = request.form["setClass"]
new_pattern = request.form["newPattern"]
pattern_suggests.append([set_class, new_pattern])
return set_class, new_pattern
I've tried several combinations while declaring successMsg, but all of them return at least one of them as undefined. How do I solve this?

Related

AJAX: Having trouble retrieving queryset from server and appending to select options

I am able to send the value of the input field with the id datepicker to the server. And with this in the view I filter the time slot by the ones that occur on the same date.
Where I am having difficulties is sending this queryset to the browser and then appending this to the options.
I'm still relatively new to javascript I apologize if this is a newb question. I definitely appreciate any feedback!
My View:
if request.is_ajax():
selected_date = request.POST['selected_date']
slots_on_day = Calendar.objects.filter(date=selected_date)
return HttpResponse(slots_on_day)
My Javascript:
$(document).ready(function() {
$("#datepicker").change(function(){
document.getElementById("display_slots").style.display ="block";
$.ajax({
type: 'POST',
data: {
'selected_date':$('#datepicker').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: function(resp){
for (var i=0; i < resp['slots_on_day'].length;++i){
addOption(
document.getElementById("display_slots"), resp['slots_on_day'][i], resp['slots_on_day'][i]);
}
}
});
});
});
Notes: the id=datepicker field triggers the ajax event. I then want to receive the response from the server and append the options to the input with the id=display_slots
Error:
TypeError: resp.slots_on_day is undefined
Updated ajax success
success: function(data){
$.each(data, function(key, value){
$('select[name=display_slots]').append('<option value="' + key + '">' + value +'</option>');
});
}
from django.forms.models import model_to_dict
if request.is_ajax():
selected_date = request.POST['selected_date']
slots_on_day = Calendar.objects.filter(date=selected_date)
data = []
for cal in slots_on_day:
data.append(model_to_dict(cal))
return JsonResponse(status=200, data={'slots_on_day':data})
It'll send JSON response in frontend and now you can use this data as you want to use. I think, It'll work with your current ajax success method code

Is there a way to send multiple JS requests to an API at once?

I'm trying to verify multiple email-adresses as once using briteverify.
Their example request is:
https://bpi.briteverify.com/emails.json?address=johndoe#briteverify.com&apikey=XXX
It works great for a single adress, now I want to verify more than one mail in one request.
Is there a way to do this?
Im not a programmer by any means, so if its super easy - sorry. :/
Put the addresses in the array and execute this little script
(function(){
var url = "https://bpi.briteverify.com/emails.json?apikey=XXX";
var emails = [
'johndoe#briteverify.com',
'johnsmith#briteverify.com',
'user#briteverify.com'
];
var success = function(data){
console.log(data.address + " is " + (data.valid?"valid":"invalid"));
};
var checkEmail = function(email){
$.ajax({
url: url,
data: {
address: email
},
success: success
});
};
for(var email in emails){
checkEmail(email);
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Using ajax to post a form to php without refresh

I have this written up for send a few variables to a php script:
$(function() {
$('a[class="removeUnread"]').click(function(){
var markedtopicid = $(this).attr("id");
var sessionvar = \'', $context['session_var'], '\';
var sessionid = \'', $context['session_id'], '\';
$.ajax({
url: "index.php?action=quickmod;board=', $context['current_board'], '",
type: "POST",
data: sessionvar + "=" + sessionid + "&topics[]=" + markedtopicid + "&qaction=markread",
});
});
});
I think this is the correct way to send post data via ajax, but it doesn't appear to be sending. Was I right to wrap the code in the ready function?
I can tell you right off the bat you should not have a semicolon between quickmod and board in your URL. I'm answering here because i cannot post comments yet. One good tool to use in web development ESPECIALLY with GET and POST requests is googles PostMan app. Its free to use and what it does is it will show you the exact output of any link you send it. So you can try putting the link that you make via javascript into postman and see what errors it spits out.
In this example i'm pretty sure your URL is all kinds of screwed up though. Try this instead...
"index.php?action=quickmod&?board="+$context['current_board']
fyi, i did not test that link so it may not work. If it doesnt work, google some ajax examples and javascript string concatenation. You're string is not suitable for ajax.
is should be like this...
$.ajax({
url :'index.php',
type : 'POST',
data : { sessionvar: sessionid, topics:markedtopicid},
success : function (data) {
},
error : function () {
}
Try handling the error:
$.ajax({
url: "index.php?action=quickmod;board=', $context['current_board'], '",
type: "POST",
data: sessionvar + "=" + sessionid + "&topics[]=" + markedtopicid + "&qaction=markread",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});

JQuery AJAX function not receiving PHP-returned text

I've been searching for a while for a solution to this problem. I've found many people with the same problem, but not the same solution.
The issue I'm having is that PHP is not returning any data to the AJAX function. The alert spits out data = undefined. As you can see, using return instead of echo is not the problem. I know that the PHP script I call completes correctly because the values are properly inserted into the database. No matter where I place the echo statement, I can't get it to return the value. Am I using the data variable incorrectly? Is returnValue not the proper variable to use? Has any of the functionality I've been trying to use been deprecated? I'm really at a complete loss. I can't see why this is failing.
//AJAX function
$("document").ready(function(){
$("#add_interest_form").submit(function(event) {
event.preventDefault();
$("#output").html("");
var values = $(this).serialize();
$.ajax
({
url: "./php/add_interest.php",
type: "POST",
data: values,
success: function(data) {
alert('data = ' + data.returnValue);
$("#output").html(data.returnValue);
},
error: function() {
alert('failed adding to database. Please try again or contact the Webmaster.');
}
});
});
});
//PHP snippet
echo 'Success!';
Just do alert('data = ' + data); instead of alert('data = ' + data.returnValue);.

Why do I get undefined when displaying value in a global variable?

I just don't get it, obviously. I've tried setters and getters, self invoking functions, you name it. It's like the click handler is returning a value but there's no way for me to keep it?
This is my code in the first file request.js
var testId = (function (inId) {
var citeId = inId;
return citeId;
})();
function mainAjax() {
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
});
}
var promise = mainAjax();
this is the code in my second file requestMain.js,
promise.done(function (json) {
var linkBase = "http://www.sciencebase.gov/catalog/item/";
var link = "";
var itemId = "";
var urlId = "";
$.each(json.items, function(i,item) {
link = linkBase + this.id;
$('#sbItems').append('<li><b>' + this.title + ' - </b>' + this.summary + '</li>');
});
$('#sbItems a').on('click', function (e) {
e.preventDefault();
var str = $(this).attr('id');
if (str.length == 7) {
itemId = str.slice(5,6);
}
else if (str.length == 8) {
itemId = str.slice(5,7);
}
testId = json.items[itemId].id;
alert(testId);
}); // END Click event
}).fail(function() {
alert("Ajax call failed!");
});
This webpage displays a list of links. A link could have some more information that I want displayed on a second webpage or it could have nothing. So when a link is clicked I need to store/save/keep the id from the link so that I can use it in the url to make another ajax request, because until I get the id the ajax request for the next page will have no idea what information to ask for.
For now I'm simply doing this
alert(testId);
But what I'm trying to do is this,
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink/' + testId + '?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
// Then doing something with json.something
testId would be used in the url and it would change depending on the link that was clicked on the previous page. The ajax call is totally dependent on the click event and is displayed on a separate webpage with new information.
And this would be in my third file requestCitation.js which currently gives me a big undefined when doing
alert(testId);
I think this is a scope issue, but how can I store the value returned from a click??? So that I can then use it globally? It seems like the value disappears outside of the scope as if there was never a click at all even thought I'm storing it in a variable?
the html for the first page has script tags for request.js and requestMain.js and the second page has script tags for request.js and requestCitation.js, so they can both see the variable testId.
Thanks for the help!
Here's the jsfiddle
These are the links and when a link is clicked
Your testId is holding the value retuned by the function you're calling, and since the function returns its argument and you've called it without arguments, it will be undefined:
var testId = (function (inId) {
var citeId = inId;
return citeId; //returns the argument
})(); // called with no argument
I'm not entirely sure what you're trying to do but if you're trying to keep the data returned from the AJAX request as a global variable, I would have thought it was done using something similar to the below.
E.g.
var promise = '';
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
data: '';
success: function(data){
promise = data;
}
});
But as I said I'm not understanding fully so I could be very wrong with my answer.

Categories

Resources