Issues with make jQuery ajax call to a rest api - javascript

I am trying to use jquery ajax to make a post request that returns some response but it does not seem to work properly. Sometimes it works after a long wait, other times it does not work at all.This is my code.
<script type="text/javascript">
const id = $('#auth').val();
$("#set").click(function(){
$('.spinner-grow').show();
$.post("https://ravesandboxapi.flutterwave.com/v2/gpx/transactions/escrow/settle",
{
id: id,
secret_key: "FLWSECK-25*******************0628-X"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
$('.spinner-grow').hide();
});
});
</script>
what might be the issue here?

The following is a complete example of a AJAX post is handled via jQuery. Just sharing it for reference.
var url = "api/path/to/your/controller";
var data = {};
data.id = id;
data.secret = 'your-secret';
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (resultObject) {
console.log(resultObject);
},
error: function (err) {
console.log('An error occured');
}
});
If you are getting a 404 error, better check the path to the API. You can use a tool like Postman to validate your requests and then try implementing the same in code.
Also make sure that there is no CORS issue as from your code we cannot understand if your post is triggered from the same domain.

Related

Bing Maps REST - Javascript

I am a beginner with JavaScript and I am facing some issues with parsing JSON and display the data I want to.
When I run the URL manualy in browser I get a correct result back.
The JavaScript code looks like this:
request = "URL"
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
var results = data.resourceSets;
console.log(r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + JSON.stringify(e));
console.log("Error" + e.message);
}
});
}
When I run this code I get no error in the console but I still get an alert via the error function: "status":200,"statusText":"OK"
Why do I get this?
And thats why I cannot get my data displayed, what I am doing wrong?
EDIT
so I was able to make a working code out of it, but I still get messages from SUCCESS and ERROR at the same time and I also get my data back?!
<script>
var request = "URL";
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
console.log("working" + r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + e.message + JSON.stringify(e));
console.log("message: " + e.message);
console.log("readyState: " + e.readyState);
console.log("responseText: "+ e.responseText);
console.log("status: " + e.status);
}
});
}
CallRestService(request, GeocodeCallback);
function GeocodeCallback(results) {
console.log(results.resourceSets[0].resources[0].travelDurationTraffic);
document.getElementById("sec").innerHTML=Math.round((parseFloat(results.resourceSets[0].resources[0].travelDurationTraffic) / 60));
}
</script>
Assuming that you put an actually URL into the request parameter this looks fine. A 200 status means it was successful and this likely called the console from your success function. I know you said you removed it to be sure, but the page could of been cached. If you take a look at the network request you will likely see that it was successful as well. Ifs possible that an error in your success function is occurring and triggering the error function. Have you tried adding break points inside of the two functions?
Here is a blog post that shows how to access the Bing Maps REST services using jQuery and other frameworks: https://blogs.bing.com/maps/2015/03/05/accessing-the-bing-maps-rest-services-from-various-javascript-frameworks/ It looks like your code is very similar.

Extract data from current URL and use it in ajax call as a paramenter

I am developing a website in which only 1 html page is there in which I first fethch the url & gets the id from url and send it to api using ajax call. On success, I displays data of the given id from url.My code is as-
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#main').hide();
var url = window.location.href;
var formno = url.substr(url.lastIndexOf('/') + 1);
if (formno != 'Login.html') {
var apiUrl = 'http://localhost:801/api/api/Patient/Get';
$.ajax({
url: apiUrl,
crossDomain: true,
contentType: "application/json",
type: 'GET',
data: { formNo: formno },
success: function (result) {
$('#main').show();
alert("Success" + result)
},
error: function (result) {
alert("error :: " + JSON.stringify(result))
}
});
}
});
</script>
when I use the url as abc.in#1 it displays the success alert but I want to give the url in format abc.in/1 at that time it gives
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Why it can not find the page? Is there any solution for this?
I want to give plain url as abc.in/1 where 1 is id and which is dynamic.
Is there any solution?
Your browser is probably trying to access document on location abc.in/1, which doesn't exist. You will need some server side logic for this, e.g. php router which will always serve your document, and additonal parameters will be processed by it. abc.in#1 anchor is different type of url parameter, which purpose is to be processed by document or javascript on client side.

Javascript pull search completion from web service

I'm a bit new to Javascript and I want to do something I feel like should be pretty simple. I have a web completion service built and I just need to get those completions into the page. I basically want something like this:
<script>
function(search_string){
http.request('www.fake.com/search_complete/' + search_string, function(response) {
response = JSON.parse(response);
//do something with parsed data
});
}
</script>
<input type="search" placeholder="Search..." />
Are you just trying to make a request and use the data returned? If so, just make an ajax request and update the html with the data you get back
var request = new XMLHttpRequest();
request.open('POST','http://www.fake.com/whatever.php?val1='+search_string,true);
request.send();
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status=200){
//The request has been completed, handle the data
var data = JSON.parse(request.responseText);
}
}
This must help. Example integration of jQuery UI autocomplete from remote web service.
http://salman-w.blogspot.in/2013/12/jquery-ui-autocomplete-examples.html
Use jquery:
$.ajax({type: "GET", dataType: 'json', contentType: "application/json", url: "yoururl", success: function (data) {
//data is a javascript object that contains the data returned by your webservice json
}, error: function(xhr, status, error) {
// Display a generic error for now.
alert("Error: " + xhr + " " + status + " " + error);
}});
This code will make a call to a webservice using ajax and javascript. It will return the data from the webservice in the data object.

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);
}
});

getJSON is not calling the controller action

I don't know why this is happening since there are other functions in this page that use also getJSON and they do work. I have the following JavaScript Code
function openSOPNotesDialog() {
var url = '<%: Url.Action("GetSOPNote", "SalesOrder") %>';
var id = <%: Model.SodID %>;
$.getJSON(url, { sodId : id }, function(data) {
alert("data: " + data);
$("#hidSOPSODId").val(data.SodID);
$("#hidNoteId").val(data.NoteID);
$("#txtSOPNotes").val(data.Description);
$("#sopNotesDialog").dialog("open");
});
}
and then I have this method on the SalesOrderController class
public JsonResult GetSOPNote(int sodId)
{
var service = new SodSrv();
var note = service.GetSOPNotes(sodId);
return Json(note, JsonRequestBehavior.AllowGet);
}
However, the method is never called in the debugger and data is returned as null (which is what I'd expect). As I said before there are other calls in this page and they are also doing GET requests so I don't know what may be the cause.
Sounds like the browser is pulling the data from the cache since it is a get request. Make sure to set no cache headers on the server if it is not meant to be cached.
Try adding an error handler to try to track down what the issue is:
$.ajax({
dataType: 'json',
url: url,
data: { sodId : id },
success: function(data) {
alert("data: " + data);
$("#hidSOPSODId").val(data.SodID);
$("#hidNoteId").val(data.NoteID);
$("#txtSOPNotes").val(data.Description);
$("#sopNotesDialog").dialog("open");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("oops: " + textStatus + ": " + jqXHR.responseText);
}
});
I suspect that the reason is that getJSON uses get method and controllers normally allowed to accept only post methods. It's ease to check using any browser firebug for example.

Categories

Resources