Ajax call isn't returning anything - javascript

I'm pretty much a complete beginner at javascript and jQuery, so please bear with me.
I have a Spark-API running, and a web front-end that uses it through ajax calls.
I'm trying to call this function
function getSpotifyURL(ms, name) {
$.ajax({
url: "http://localhost:8081/playlist?ms=" + ms + "&name=" + name,
dataType: "json",
})
.done(function( data ) {
console.log(data);
})
}
The method is placed outside of:
$(document).ready(function() {
The reason it's outside is that I get an error upon calling it saying it's "undefined" if it's within $(document).ready.
The Spark-method is supposed to return a String (and it does when you try it directly through the browser).
The way I'm calling the getSpotifyURL-method is through a html button's "onclick". Like this:
<a href='#' onclick='getSpotifyURL(" + data[i].duration + ",\"" + data[i].destination + "\")'>Create Spotify playlist for this trip</a>"
The problem:
The .done-block does nothing in my code. Nothing is printed to console.
What I've tried:
Using "success" within the ajax part instead of .done
Placing the function with $(document).ready(function() { ... }
I understand that you might need more information to be able to help me, but I'm not sure what else information to provide right now. So if there's something you need to know, just ask.
Ideas?
SOLVED!
I'm a dumb person and forgot to remove dataType: "json", as the Spark-server in this instance returned a String, not a json object. Anyway, thanks for your input everybody. Much appreciated.

I think the problem is when you bind your function onclick. There is a syntax error, as you can see on the browser console
function getSpotifyURL(ms, name) {
console.log("http://localhost:8081/playlist?ms=" + ms + "&name=" + name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' onclick='getSpotifyURL(" + data[i].duration + ",\"" + data[i].destination + "\")'>Create Spotify playlist for this trip</a>"
I guess data is a variable, so you should call it without brackets
<a href='#' onclick='getSpotifyURL(data[i].duration, data[i].destination)'>Create Spotify playlist for this trip</a>

The reason you are getting undefined method when you are placing the function inside the $(document).ready(function() { ... }); call is because you are using the onclick attribute to call the function. $(document).ready(...) is not in global context as to where you onclick attribute is, and would therefore not recognize it from within the document.ready resulting in your undefined method error.
When sending your Ajax request, you also need to specify a type of request (GET or POST) that you are making. I would also suggest restructuring your ajax call to look more like #Moe's answer.
If you want to get it inside the DOM, consider doing the following:
HTML
<!-- I gave the link a class name and removed the onclick= attribute -->
Create Spotify playlist for this trip
JavaScript
$(document).ready(function() {
// I gave the <a> link a click handler
$(".create-spotify-playist").on("click", function(e) {
e.preventDefault(); // prevents link from requesting
var ms = ?? //I'm not sure where you're getting your parameters from,
var name = ?? //so you will probably have to figure out how to get those in here yourself
$.ajax({
type: "GET",
url: "http://localhost:8081/playlist",
data: { ms: ms, name: name },
success: function(data) {
console.log("Success: " + data);
},
error: function(data) {
console.log("Error: " + data);
}
});
});
});
I gave the link a click handler and placed it inside the $(document).ready, and by removing the onclick attribute from earlier, it can now be triggered from inside $(document).ready.

Related

Ajax call inside of function

I am working inside of an Oracle package. I am trying to use an AJAX call to call a procedure from a button click. The ajax call is inside of a function. I am not getting any syntax errors from Oracle or when I'm using the browsers debug mode so I'm not sure what the problem is. Function is below.
htp.p('
function ApplyTest(_ht) {
var _inst = "";
var _pidm = '||v_web_pidm||';
var _inst = document.getElementById("Test").value;
alert("Heat Ticket value is: " + _ht);
alert("the instance is: " + _inst);
var resp = confirm("Are you sure you want patch applied to TEST8?");
if (resp == true) {
alert ("user pidm is: " + _pidm);
return $.ajax ({
type: "POST",
cache: false,
dataType: "json",
url: "gyapatch.p_update",
data: {"v_instance" : _inst, "v_ht" : _ht},
success : function(data) { alert("success"); }
});
alert("Got here");
alert("value: " + _inst);
window.location.reload;
alert("got to the end");
} else {
return;
}
}
');
code for the button is:
<button name="TestApply" id = "Test" onclick="ApplyTest('||val_patch.heat_ticket||')" type="button" value="T">Apply to TEST8</button>'
When I try to return the ajax call nothing is happening and I can't even reach the "Got Here" alert. When I remove the "return" keyword, I can reach the alerts but either way, nothing is happening. GYAPATCH.p_update is the package/procedure I wish to have executed when this is ran
I'm not sure what the problem is. Any help on this would be greatly appreciated. Thanks in advance.
So after a couple of hours, I had figured out the problem. This was more of a learning lesson as the issue was pretty simple. I needed to remember that I was working inside of an Oracle database AND also using WebTailor. The code posted above is correct. It turns out that the procedure I was trying to call (p_update) was not registered.
WebTailor allows you to build web applications utilizing Banner. In WebTailor, any pages that are used (usually stemming from a package.procedure), need to be registered or else they are not recognized.
I found this while debugging. Under the Network tab in my debugger, I noticed that when I click my button, I am getting a 404 error when my package.procedure is called. So I then realized it couldn't find my package and then proceeded to check if it was registered. This was a simple, silly error on my part. I am grateful for the feedback, but this will probably serve as a learning lesson or reminder to anyone trying to use ajax while working with Banner data.

PHP code and JQuery within onclick event [duplicate]

I have a link, which links to domain.com , when a person clicks, I want it to do an ajax call to counter.php and post 2 variables to it, so it can add 1 to the views for that link.
I have a link:
Link Title
How would I do this with jquery?
EDIT:
I tried something like this
function addHit(str, partNumber){
$.get("counter.php", { version: str, part: partNumber })
}
It seems to work, but in firebug, the request never completes... it just does that "working..." animation. counter.php echos out some text when its done (doesnt need to show up anywhere).
From the jQuery documentation: http://api.jquery.com/jQuery.ajax/
function addHit(data1, data2)
{
$.ajax({
type: "POST",
url: "http://domain.com/counter.php",
data: "var1=data1&var2=data2",
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
}
You need to add a callback on success
function addHit(str, partNumber){
$.get(
"counter.php",
{
version: str,
part: partNumber
},
function(data){
alert("Data Loaded: " + data);
})
)};
In the case of an anchor, you're leaving the page, so firebug's going to show some weird behavior here as it thinks execution would stop. Unless you're also preventing the default event behavior of the anchor...you're leaving the page and the request (in firebug's view) is discarded.

Ajax/Jquery calling a webmethod/service every 'interval' seconds

I have a ASP.Net web app with jquery implemented on the client side. The client side jquery script makes an asynchronous call to a web method in the server side code. The call returns the status open record(active/inactive) which jquery uses to update the user. The goal is to have jquery repeatedly call the server, once open record is inactive, then we need to display message to user so that you're no longer associated to this record..I set up the TimeInterval in one off the HiddenFieldValues and passing to the Jquery/ajax Function.
This function is written In a separate JavaScript file and it has been referred in my ASPX page Script Manager. I have to pass 'interval' from the server side, which is configured in the .config file.
function myWebServiceFunction(val1, val2, val3, interval) {
$.ajax({
type: "POST",
url: "/Application/WebServices/MyService.asmx/CheckFunction",
data: "{'val1':'" + val1 + "','val2':'" + val2 + "','val3':'" + val3 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
debugger;
var obj = function callbackfunction() {
myWebServiceFunction(HealthCarrierShortName, authID, networkID, interval)
}
if (!msg.d) {
window.setTimeout(obj, interval);
}
else {
// Still need to implement how to display to user if the record is not long associated to that user. help me in this too
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('AJAX failure');
}
});
}
In my Server Side, I Used RegisterStartUpScript at the end of Page_load method and calling that JQuery Function
ScriptManager.RegisterStartupScript(Me.Page, Page.GetType(), "AuthLockPolling", " myWebServiceFunction('" + val1HiddenField.Value + "','" + val2HiddenField.Value + "','" + val3HiddenField.value+ "','" + val4HiddenField.value+ ");", True)
But it is not working properly(Don't know exactly the reasons). My Jquery function is not being called at all. I testing by placing debugger into my script and it is not been hit.
Still need to implement how to display message to user if the that record is not long associated to that user like in a alert window/pop-up window. Please help me in this part too.
Please Advise me what went Wrong and How to solve this. Thanks In advance!
How to solve this:
RegisterStartupScript can be confusing (ask me how I know!). Are you using this on a page that uses partial-page updates (i.e., has UpdatePanel controls)? If not, you should use the method in the ClientScriptManager (instead of ScriptManager) class.
If it is used on a page with partial-page updates for a control that's inside an UpdatePanel, the first parameter should be a control within the UpdatePanel, rather than the Page.
And a debugging tip: Test by passing in JavaScript code that's drop-dead simple, like alert('Hello, World!');. This can help you tell if the problem is in the RegisterStartupScript call or in your myWebServiceFunction function.
Finally, here's the Microsoft documentation: https://msdn.microsoft.com/en-us/library/bb310408(v=vs.110).aspx. Because there are methods of the same name in different classes, read the documentation verwy, verwy, carefulwee.

.when Ajax success is done run another function with some jquery, almost working?

After a submit event runs with prevent default (to avoid the submit page refresh) along with some algorithms, the oneStory(id) function is called on success for sending the updated .put data to the node.js API.
At this moment, the fields that were toggled-open (by the jquery below) to be updated, undesirably toggle-closed because the whole html template is refreshed (seemed the best way to give handlebars.js the new db data), but I would like these comment fields to remain in view throughout the update (thus reflecting the realtime update).. should .live be implemented somewhere?
Am sure there is a better way to do this realtime update, but thought to have all the stories refresh, and .when done, .then pass the id of the updated comment to jQuery to toggle open the comments section for the particular story that had a comment updated. Right now though, this .then jQuery logs Object (of the resJSON) comments for: Object are open (instead of the _id)
What's more, with the success call refreshStory(id) from oneStory(id) from the .put AJAX (which does .put because the update is stored in the db), the view appears to have refreshed the content because the console logs everything of the foundAllSuccess function and the story's comments toggle-close, but unless I instead call foundAllSuccess as the actual success call of the refreshStory(id) function, the async repopulation of content doesn't include the updated comment!?
function oneStory(id) {
$.ajax({
url:"http://localhost:4200/api/v1/stories/" + id,
method:'get',
success: refreshStory(id), //foundAllSuccess does work here
error: foundError
})
}
function refreshStory(id) {
var thisID = '#' + id;
console.log(thisID);
$.when($.ajax({
url:"http://localhost:4200/api/v1/stories",
method:'get',
success: foundAllSuccess,
error: foundError
}).then(function(thisID){
console.log(thisID);
$(thisID).parentsUntil( ".comments" ).parent( ".comments" ).slideToggle();
console.log("comments for: " + thisID + " are open");
})
)}
function foundAllSuccess(resJSON) {
var templateSource = $("#storiesTemplate").html();
console.log('Getting All the Stories..');
console.log(templateSource);
var template = Handlebars.compile(templateSource);
var storiesHTML = template({stories: resJSON});
$('#allTheStories').html(storiesHTML);
console.log('Got All of the Stories..');
}
Here's the HTML (maybe there's a better way to refrence this too, than the parentUntil.parent)
<div class="comments" style="display:none;">
\{{#each comments}}<div class="comments-frame">
<input type="hidden" name="id" id="\{{_id}}" />
And the jQuery that accurately toggles open the comments to begin with:
$(document).on("click", ".storyTitle", function () {
var $that = $(this).closest('.story').find('.comments')
$that.slideToggle();
});
}).then(function(thisID){
console.log(thisID);
$(thisID).parentsUntil( ".comments" ).parent( ".comments" ).slideToggle();
console.log("comments for: " + thisID + " are open");
})
thisID inside this method is NOT as same as the one outside it. Just remove the parameter and you will be fine.

AJAX POST not getting through to PHP

At the moment I have multiple forms, and am writing the JavaScript out very simply. I want to create a simple comment system using the following AJAX, but am running into troubles that I cannot sort out..
The AJAX call looks like this:
var dataString = 'commentauthor=' + commentauthor + '&parentid=' + parentid +'&linkid='+
linkid + '&comment=' + comment + '&location=' + location;
alert("check : " + dataString)
$.ajax({
type: "POST",
url: "comments/addcomment.php",
datatype: "html",
data: dataString,
success: function(){
alert('comment added!');
},
error: function(){
alert('failed adding comment!' +dataString);
}
The dataString at all times pulls out the correct information from the forms. Also, the PHP the AJAX is sending it to already works when it's set as the forms action, and all the $_POST[''] names match up.
I've been looking around but can't figure it out. Am I encoding the data wrong or something? The PHP side of things doesn't even get to the AJAX response, so it's got to be just failing to send right?
Also, is there a better way to check JavaScript errors? I've been using the google chrome console but half the time when something goes wrong it doesn't through up an error anyway (like this time)
Is addcomment.php printing anything out? I vaguely remember having a similar problem which was because the PHP file wasn't returning anything. If it isn't, try this before the end of the file:
echo 1;

Categories

Resources