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.
Related
I'm trying to log my users location using some Ajax code I was able to gather from online. I am trying to pass it to the backend code where I can store the data in my db for analytics. I have never used Ajax before and am not familiar with the syntax for passing through to backend.
Here's my code.
<div>Country: <span id="country"></span>
<div>State: <span id="state"></span>
<div>City: <span id="city"></span>
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function (location) {
$("#country").html(location.country_name);
$("#state").html(location.state);
$("#city").html(location.city);
}
});
I basically need to pass $('#country').html(location.country_name); $('#state').html(location.state); $('#city').html(location.city); to my nodejs code. I've used fetch before in js but not sure if thats the syntax to include the Ajax code in it. Appreciate the help.
If you have some data to be sent to the server using AJAX and if you have something like the HTML that you have got, you can very well use the textContent or .text() (using jQuery) of the element. Here's how you do it.
// Sending data to the server...
var data = {
country: $("#country").text(),
state: $("#state").text(),
city: $("#city").text()
};
console.log("Data to be sent!");
console.log(data);
console.log("Serialised data!");
console.log($.param(data));
// Send data to end point and get JSON value.
$.getJSON("/endpoint?" + $.param(data), function (res) {
console.log(res);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Country: <span id="country">India</span>
<div>State: <span id="state">Tamil Nadu</span>
<div>City: <span id="city">Chennai</span>
In the above example, the contents of the HTML will be sent to the server. Check out the console and network for what is been sent.
Here's from the Network tab of Google Chrome:
To anyone who else who is looking at this question, you may also use javascript within the Ajax function. It may not be the proper way, but it does work.
<script>
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function( location ) {
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
console.log(location)
var locaionValues = location;
var countryNameLocation = location.country_name;
var stateNameLocation = location.state;
var cityNameLocation = location.city;
fetch('/locationTracker', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
locaionValues,
countryNameLocation,
stateNameLocation,
cityNameLocation,
})
})
}
});
this works great, and in my nodejs code, I am logging the code like so:
app.post('/locationTracker', (req, res) => {
var country = req.body.countryNameLocation
var state = req.body.stateNameLocation
var city = req.body.cityNameLocation
console.log("country is " + country)
console.log("state is " + state)
console.log("city is " + city)
I have been working on a project that uses knockout for databinding from javascript to html. I am also reading data from a PLC using ajax, the data from the ajax request will put into the knockout viewmodel and shown on the webpage. I am having some trouble with the updating of the data binding.
I searched on the internet for help but didn't find anything so far that helped me so I hope you can help me further.
I have setup the viewmodel as following inside a javascript file:
function AppViewModel() {
var self = this;
self.hmitags = ko.observableArray(groupDataValues);
self.Capa100 = ko.observable("Cap100");
self.Testvar = ko.observable(50);
}
var viewModel = new AppViewModel();
ko.applyBindings(viewModel);
And have the data binding in the html file:
<span data-bind="text: Testvar></span>
when I now load the html file I see the value 50 as defiened in the viewmodel, so that is working. But now I want to read a variable from my PLC using ajax that is done through a function inside that same javascript file. This is how the function looks:
function ReadVariable()// function for reading out individual variables
{
// list can contain only one variable
var HMIReadList = "&paths=MainInstance.Testvar"
data.length = 0; // get rid of the data from the last query
// issue the data request
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + BearerToken);
}
});
$.ajax({
type: "GET",
url: baseurl + "_pxc_api/api/variables?pathPrefix=Arp.Plc.Eclr/" + HMIReadList,
})
.done(function (data, status, jqXHR) {
viewModel.Testvar = data.variables[0].value;
console.log(viewModel.Testvar);
})
.fail(function (jqXHR, status, errorThrown) {
console.log("CreateSession Error: " + errorThrown);
console.log("Status: " + status);
console.dir(jqXHR);
alert("CreateSession $.ajax failed. Status: " + status);
});;
}
I am using a button in the html page to call this function. In the console I can see that it is reading a value from the PLC and that it is different that the initial value 50. But on the html page it is not changing. I am not sure why it isn't working I have been looking around for some solutions but have not found anything that is working.
A knockout observable is a function. In order to update the value of the observable, you need to invoke the function with the new value as follows:
viewModel.Testvar(data.variables[0].value)
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.
I made an api in java , which allows the user to get data.
there is an call : ..../api/users where i give a list back of all users avalible.
Now i got a site with a search user button, wen you press that button i want to make a call to /api/users with the help of Ajax.
i got the part that you can click on the search button, but i don't understand how to make that call with ajax
This is my code:
$.ajax({
url: ”api / resource / users ",
dataType: "json”,
}
).fail(
funcNon(jqXHR, textStatus) {
alert("APIRequestfailed: " + textStatus);
}
).done(
funcNon(data) {
alert("succes!")
}
);
Is this the way of making a good call with ajax ?
or do i have to use :
http://localhost/projectUser/api/resource/users ?
Assuming you are using JQuery to make the Ajax call then this sample code should be helpful to you. What it does is;
On search button was clicked
Do AJAX call to fetch stuff from your Java REST API
When the expected JSON object was returned, parse it and do something
O
$(document).ready(function() {
$('#demoSearchBtn').click(function () {
// Search button was clicked!
$.ajax({
type: "GET",
url: "http://localhost/projectUser/api/resource/users", // edit this URL to point into the URL of your API
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
var jsonObj = $.parseJSON(data);
// Do something with your JSON return object
},
error: function (xhr) {
alert('oops something went wrong! Error:' + JSON.stringify(xhr));
}
});
});
}
if this http://localhost/projectUser/api/resource/users is the url, it's either
$.ajax({
url: ”api/resource/users", ...
or
$.ajax({
url: ”http://localhost/projectUser/api/resource/users", ...
depending on what the browsers current URL is (relative or absoute depends on context of the browser).
but it is never ever ”api / resource / users " with spaces between words and slashes.
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.