Getting blank response in the javascript file while fetching the API response - javascript

I have a button. When I click that button, Login method in the js file gets executed. Inside the Login method, I am calling an API. I am trying to fetch the output returned by the API but I am getting blank response in the alert message in the below code.
I am getting the correct response when trying to hit the API through Postman.
Here is the js code where I am calling the API-
function Login() {
var url="https://localhost:44369/categories?username="+"sid"+"&password="+"123";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
alert(xhr.responseText);
}
xhr.open('GET', url, true);
xhr.send(null);
}
Here is the get API code-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace login.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
[HttpGet]
[Route("categories")]
public IHttpActionResult Get(string username,string password)
{
loginResponse response = new loginResponse();
if(username=="sid" && password== "123"){
response.Success = true;
}
else
{
response.Success = false;
}
return Ok(response);
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody] string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}

This worked for me -
var username=document.getElementById("UserName").value;
var password=document.getElementById("Password").value;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://localhost:44369/categories?username=sid&password=12', true);
xhr.send();
xhr.onreadystatechange = () => {
console.log(xhr);
if (xhr.readyState=== 4) {
console.log(xhr.response);
}
}

If you confused you can create code for JavaScript XHR in Postman, follow below steps:
I think below code works:
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://localhost:44369/categories?username=sid&password=123");
xhr.send();

Related

How can a Json return be sent from a controller to the frontend in Asp.NET Core MVC application?

So, I have a JS script that sends a request to the server and that works fine. However, I want the frontend to recieve a response containing some information and read it on the frontend and execute a function.
uploadButton.addEventListener("click", () => {
var formData = new FormData();
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
if (request.response.result == "Success") {
console.log("Result is success")
window.location = request.response.url;
}
}
My controller looks like this.
[HttpPost("/page/upload")]
public IActionResult Upload()
{
*working parts pertaining to reading the request are omitted*
var redirectUrl = Request.Host + "/" + page.PageURL;
return Json(new { result = "Success", url = redirectUrl});
}
What I want is for my JS script to access the returned Json and its contents. How would I do this?
Try using the following code. It will subscribe the readystatechange event and run when API response has been received
uploadButton.addEventListener("click", () => {
var formData = new FormData();
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
request.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
var responseData = JSON.parse(this.responseText);
if (responseData.result == "Success") {
console.log("Result is success")
window.location = responseData.url;
}
}
});
});

Having an array of javascript objects as an ajax call parameter, without jquery?

I'm trying to send an array of JavaScript objects to my ASP.Net MVC controller without using jQuery. I have a simple array of JavaScript objects like this...
var data = [];
data.push(new person(1, "David"));
data.push(new person(2, "Karine"));
data.push(new person(2, "Annie"));
...etc
function person(_id, _name) {
this.id = _id;
this.name = _name;
}
...and I would like to have it as a parameter of an ajax call like this:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var obj = JSON.parse(xmlhttp.responseText);
for (var i = 0; i < obj.length; i++) {
if (i == 1) {
alert(obj[i].name);}
}
}
else {
alert('There is an error');
}
}
};
xmlhttp.open("GET", "/Home/AjaxTester?id=15&name=dave", true);
xmlhttp.send();
The way I found so far to pass parameters to an ajax call, which is ...Home/AjaxTester?id=15&name=dave, works fine for basic types, but I can't find a way to do the same with more "complex" types. I'm open to new ways to parameterize my ajax call if anything better, or even a new way to make an ajax call, as long as it is pure JavaScript, no library, no framework, or whatever.
Here's my MVC controller...
public JsonResult AjaxTester(List<Person> _person)
{
//Whatever Logic...
return Json(_someObjects);
}
...and the class of the received parameter
public class Person
{
public int id { get; set; } = 0;
public string name { get; set; } = "";
public Person(int _id, string _name)
{
this.id = _id;
this.name = _name;
}
}
You need to have FromUri command before parameters, like this:
public JsonResult AjaxTester(FromUri List<Person> _person)
You need to change your http method from GET to POST.
xmlhttp.open("POST", "/Home/AjaxTester?id=15&name=dave", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(JSON.stringify(data));
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
Make sure you add the setRequestHeader. If you are sending a json object then change the request header to the following:
xhr.setRequestHeader("Content-type", "application/json");
I would also recommend removing the query parameter and updating the controller to accept this type of object. You may also need to add the [FromBody] in next to that parameter.
And your controller should be updated similar to
public JsonResult AjaxTester([FromBody] List<Person> _person)

How to pass parameters to controller using ajax and javascript?

I am trying to delete an item from shopping cart using Ajax with javascript, but I have trouble passing parameters to the controller. The parameters are null in controller.
My javascript code shows as below:
function removeRow(itemId, rowID){
if (xmlHttp == null)
{
alert("Your browser does not support AJAX!");
return;
}
var query = "action=remove&item=" + itemId;
/* alert(query); */
xmlHttp.onreadystatechange = function stateChanged()
{
if (xmlHttp.readyState == 4)
{
var row = document.getElementById(rowID);
row.parentNode.removeChild(row);
}
};
xmlHttp.open("GET", "addTo.htm", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send(query);
return false;
/* var row = document.getElementById(rowID);
row.parentNode.removeChild(row); */
}
My controller code shows as below:
#Controller
#RequestMapping("/addTo.htm")
public class AddToController{
#RequestMapping(method=RequestMethod.GET)
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
String action = request.getParameter("action");
System.out.println(action);
ModelAndView mv = new ModelAndView();
ArrayList<Item> cart;
if(action.equals("remove")){
System.out.println("cart size is" + cart.size());
Long itemId = Long.parseLong(request.getParameter("item"));
ItemDAO itemDao= new ItemDAO();
Item item = itemDao.get(itemId);
cart.remove(item);
System.out.println(cart.size());
}
return mv;
}
}
The action and item are null in the controller.
Can anyone help with this problem?
You're sending a GET request, so add the parameters as a query after your URL:
xmlHttp.open("GET", "addTo.htm?" + query, true);
and pass in null (rather than your query string) when calling the .send method:
xmlHttp.send(null);
Also, the "application/x-www-form-urlencoded" header is only used when you're sending serialised parameters but using POST, so remove the xmlHttp.setRequestHeader line.
More info: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

Redirect to new page as response to XHR post request

I have no way to fix the javascript. The page uses a XHR
function openPOST(url, params, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-Type', "application/x-www-form-rlencoded");
xmlhttp.send(params);
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if (xmlhttp.status === 200) {
if (callback) callback(this.responseText);
}
}
}
return xmlhttp;
};
At the time of page load, use the following query
document.addEventListener('DOMContentLoaded', function () {
...
function go() {
openPOST("/home/someaction", "query=123", function (count) {
document.querySelector("h1").textContent = count;
});
}
...
go();
...
});
Is it possible to implement such a code to ASP.NET MVC so he moved on to another page, but did not put the result in another page ?
I need to POST requests are redirected to the page to a different address.
the following code inserts the result in document.querySelector("h1").textContent
public void someaction() {
Response.Status = "307 Temporary Redirect";
Response.AddHeader("Location", "http://example.com");
}
EDIT:
User opened an old version of our webpage in his browser. This webpage makes an ajax call to our webserver and inserts response as a string (no eval(), js code won't work). Is there are any way to reload this web page from our server?
On your action method, you can call a Javascript code by returning a Javascript result
[HttpPost]
public ActionResult someaction() {
if (Request.IsAjaxRequest()) {
return JavaScript("document.location.href=\"http://www.google.com\"");
} else {
return Redirect("http://wwww.google.com");
}
}

Unable to get data at first click in android webview with server communication

I am calling this method from JavaScript.
For the first time, it is giving null. But from the second time onwards, the data is coming.
Please help me.
#SuppressLint("JavascriptInterface")
public String loadClickedData() {
pDialog = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new HttpAsyncTaskClickedData()
.execute("http://192.168.0.9/btrepo/btrepo/android_api.php");
return bdb.getmPosIdData();
}
Here we are getting data through AsyncTask in Android:
private class HttpAsyncTaskClickedData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("tag", "get_pos_details"));
nameValuePairs.add(new BasicNameValuePair("pos_id", posId));
return GET(urls[0], nameValuePairs);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getApplicationContext(), result+" in post ",
// Toast.LENGTH_LONG).show();
pDialog.dismiss();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
bdb.setmPosIdData(result);
}
}
This method is for getting data from the server:
public static String GET(String url, List<NameValuePair> pair) {
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse httpResponse = httpClient.execute(httpPost);
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
is = inputStream;
// convert inputstream to string
if (inputStream != null) {
// jObj = convertIsToJson(inputStream);
result = convertIsToJson(inputStream) + " ";
// jSonStr = result;
} else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
I am getting data from the server in json string format.
It is displaying attributes with null value like {pos["posid":null, "storeName":null]} etc..
In the following function
public String loadClickedData() {
pDialog = ProgressDialog.show(this, "dialog title",
"dialog message", true);
new HttpAsyncTaskClickedData()
.execute("http://192.168.0.9/btrepo/btrepo/android_api.php");
return bdb.getmPosIdData();
}
You execute your HttpAsyncTaskClickedData(), and return bdb.getmPosIdData() immediately. (Which will always be an issue for the 1st time)
The result of the AsyncTask is only available in onPostExecute, where you call bdb.setmPosIdData(result);.
#Override
protected void onPostExecute(String result) {
// ...
bdb.setmPosIdData(result); // result is only stored in bdb here!
}
The HttpAsyncTaskClickedData runs in the background, and possibly takes some time.
That is why your first call is always unable to get data, as you returned bdb.getmPosIdData() immediately after executing your AsyncTask.
private class HttpAsyncTaskClickedData extends
AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs
.add(new BasicNameValuePair("tag", "get_pos_details"));
nameValuePairs.add(new BasicNameValuePair("pos_id", posId));
return GET(urls[0], nameValuePairs);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getApplicationContext(), result+" in post ",
// Toast.LENGTH_LONG).show();
data = result;
pDialog.dismiss();
bdb.setmPosIdData(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(MainActivity.this, "dialog title",
"dialog message", true);
}
#SuppressLint("JavascriptInterface")
public String loadData() {
Toast.makeText(getApplicationContext(), data+ " hi ",
Toast.LENGTH_LONG).show();
return data;
}
}
and calling loadData() method from javascript.
This function is for get data by using post url in javascript
function jsonPost(){
var http = new XMLHttpRequest();
var url = "http://192.168.0.9/btrepo/btrepo/android_api.php";
var params = "tag=fav_stores&mobile=984989874";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
alert("hello "+http.send(params));
}

Categories