Making a AJAX request with jquery and parsing JSON - javascript

EDIT- I have figured out that the request is working correctly but I don't know what to do with the data once it has been retrieved from the server. I don't know how to access the JSON, how do I do this?
I am trying to do a jQuery AJAX request and parse the JSON which is hopefully received. Here is my code:
search.onsubmit = function() {
$.getJSON("http://www.geocodefarm.com/api/forward/json/d4abb1b19adb13e42eac5a7beac6f4dbeb4b4ba4/" + searchBox.value, function(data) {
var rawJSON = $.parseJSON(data);
alert(rawJSON.COORDINATES.latitude);
});
alert("test");
}
I known that the getJSON function is not working because the test alert appears. Why does it not work?

You can do it like so:
sendAjax: function (url, dataObj) {
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(dataObj),
contentType: "application/json; charset=utf-8",
timeout: 30000,
success: function (result) {
//do shit..
}
,
error: function (result) {
}
});
}

Related

Ajax Request: Json Data Not Being Passed to Controller

I'm building a program that searches documents in ASP.NET Core. I'm passing the search data from a text box to the controller through an Ajax request but the controller isn't receiving the string.
I've tried changing how the ajaxData field is defined, adding quotations around 'search' and even turning the whole thing into a string but I can't get it to pass to the controller.
This is the code for the request:
ajaxData = {search: $("#textSearchBox").val()}
console.log(ajaxData);
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: ajaxData,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
And this is the top of the Controller's GetDocuments function:
[Route("GetDocuments")]
public async Task<IActionResult> GetDocuments(string search)
{
No error messages anywhere. The Console shows an Object that contains 'search: "Test"' but when I hit the breakpoint in GetDocuments 'search' is null.
I think is more elegant way to use GET in this case then you should change your code to
var ajaxData = $("#textSearchBox").val();
url: "#Url.Action("GetDocuments", "DocumentSearchApi")"?search=ajaxData
and remove data: ajaxData
Because you want to get something from the search. Using the post is when you want to modify the data from API
you need use JSON.stringify() when sending data to a web server, the data has to be a string not a object
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: JSON.stringify(ajaxData),
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});

Handing value into Success function from AJAX Call

G'day all,
I'm trying to pass a value through to a Success var from the original AJAX call.
Here's some code :
function isJobComplete(jobGUID) {
var data = { "pJobGUID": jobGUID };
var url = '/DataService.asmx/isJobComplete';
var success = function (response, jobGUID) {
if (response.d) {
//The job is complete. Update to complete
setJobComplete(jobGUID);
}
};
var error = function (response) {
jAlert('isJobComplete failed.\n' + response.d);
};
sendAjax(data, url, success, error);
}
function sendAjax(data, url, success, error) {
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: success,
error: error || function (response) {
jAlert(response.d);
}
});
}
When the isJobComplete function runs, it has the correct value for jobGUID on the first pass through, but on the return to Success after the AJAX call, jobGUID changes to the word "success", with the double quotes.
How can I pass through that jobGUID to the Success function so I can use it to do more work depending on the AJAX response?
Thanks in advance....

HTTP get requests in ajax

I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.
Javascript code:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
var jsonStr = JSON.stringify(data);
alert(jsonStr['password']);
}
});
});
})
The response JSON code looks like this:
{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn#mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}
When im running this I only get the error function. Any suggestions or solution is appreciated :)
Basically you are converting the JSON to string and trying to access the string as object. Please don't stringify the data, and for JSON why using long code, your code should be:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.getJSON( "http://website/api/user/Mikkel1337", function( data ) {
// do something on success
alert(data.password);
});
});
});
Cheers !!!
dont need to JSON.stringify of data simple use
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
alert(data.password);
}
});
});
})
You should pass two argument for error:function(jqXHR, exception) as below.
And check once your API Url using proper way, may be your API is not show you proper result and you not get any of data from that API so that may be a reason you get error message.
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function (data) {
var jsonStr = JSON.stringify(data);
//also try this way to get JSON data:
// var jsonStr =JSON.parse(data);
alert(jsonStr['password']);
},
error: function (jqXHR, exception) {
alert("An error had occurred");
},
});
});
});

Sending data from JQuery to C#, ASP.Net

I have a canvas in my .aspx form page where one can sign a signature, I would like to send the base64 data from the JQuery client side to the C# Asp.Net side. Here I want to upload this base64 data to a database.
(a couple things I tried)
Jquery:
$("#savebtn").bind("click", function () {
var base64 = $('#sketch')[0].toDataURL("image\png");
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: '{ data: "' + base64 + '"}',
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
$.post("EvaluatieForm.aspx", { data: base64 }); // another thing i tried
C#:
var d = Request.Params["data"];
The variable d is null when i put a breakpoint at it.
Does anybody see how I can tackle this hurdle, or make it easier?
(note: I do not have a lot of experience with JQuery)
Your JSON with base64 could be available as request body.
using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
string text = reader.ReadToEnd();
}
If you replace
url: 'EvaluatieForm.aspx'
by
url: 'EvaluatieForm.aspx?data=' + base64
and remove
data: '{ data: "' + base64 + '"}',
then it will work.
Try this:
Just a small change in your existing code, used JSON.stringify to post data.
$("#savebtn").bind("click", function () {
var base64 = $('#sketch')[0].toDataURL("image\png");
var objectToPasss = {data: base64};
var postData =JSON.stringify(objectToPasss );
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: postData,
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
$.post("EvaluatieForm.aspx", { data: base64 });
Try this:
$("#savebtn").bind("click", function () {
$.ajax({
url: 'EvaluatieForm.aspx', // page where i have button listenener
data: {
sketch: $('#sketch')[0].toDataURL("image\png")
},
type: 'POST',
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log("inside sucess");
console.log("result: " + result);
},
error: function (request, error) {
// This callback function will trigger on unsuccessful action
alert('Error!');
}
});
where
var d = Request.Params["sketch"];
The data argument in the jQuery ajax() function works in conjunction with the contentType. As you are setting it to application/json, then it stands to reason that data will be serialized, so setting the sketch variable seems about right.
With ajax you can try xhr.
maybe this thread helps you out! :)
How can I upload files asynchronously?

How to call json object from AJAX?

Here is my script:
$.ajax({
type: "Get",
url: "Sample.js",
datatype: 'json',
data: JSON.stringify({ key:key }),
success: function (data) {
var sample = data.name;
$("#html").html(sample);
},
error: function () {
alert("Error");
}
});
This is my Sample.js file:
{ "name": "user" }
When I run this code I get a blank screen. This is my script using getJSON():
$.getJSON("Sample.js", function (data) {
var sample = data.name;
$("#html").html(sample);
})
This produces "user" perfectly. What is the problem with $.ajax code?
In the getJSON version your don't send any data. Could this be the reason why that works? To me it looks like this could be sth. on the server side that delivers an empty JSON object when you pass the key parameter.
As the jQuery documentation states:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Try modifying the dataType param.
change your datatype to dataType. Its case sensitive. Refer http://api.jquery.com/jQuery.getJSON/
Remove JSON.Stringify and change Get to GET
$.ajax(
{ type: "GET",
url: "Sample.js",
dataType: "json",
data: {key:key },
success: function (data)
{ var sample = data.name; $("#html").html(sample); },
error: function () { alert("Error"); }}
);

Categories