Jquery Ajax Request with JSON Response, How To

jQuery ajax request with json response, how to?

You need to call the

$.parseJSON();

For example:

...
success: function(data){
var json = $.parseJSON(data); // create an object with the key of the array
alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
},
error: function(data){
var json = $.parseJSON(data);
alert(json.error);
} ...

see this in
http://api.jquery.com/jQuery.parseJSON/

if you still have the problem of slashes:
search for security.magicquotes.disabling.php
or:
function.stripslashes.php

Note:

This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.

How to call ajax request with JSON response using jQuery?

  1. You might missed to add type //GET or POST, which type of REST OPEATION
  2. dataType is mispelled
  3. Missed to add contentType

 $.ajax({
type: "POST", //rest Type
dataType: 'jsonp', //mispelled
url: "http://json-cricket.appspot.com/score.json",
async: false,
contentType: "application/json; charset=utf-8",
success: function (msg) {
console.log(msg);
}
});

Updates:
While trying to figure out the reason, I think this is the best answer to understand the problem.

Say you're on domain abc.com, and you want to make a request to domain
xyz.com. To do so, you need to cross domain boundaries, a no-no in
most of browserland.

The one item that bypasses this limitation is tags. When you
use a script tag, the domain limitation is ignored, but under normal
circumstances, you can't really DO anything with the results, the
script just gets evaluated.

Enter JSONP. When you make your request to a server that is JSONP
enabled, you pass a special parameter that tells the server a little
bit about your page. That way, the server is able to nicely wrap up
its response in a way that your page can handle.

How to parse json response for ajax request?

It'll probably be a little trial and error - I get a bit confused with JSON at times and forget which sections are arrays and which are just readable.

When I've been dealing with JSON before I use

var json = JSON.parse(JSON.stringify(data));

to get the parsed object. You can then access key/value pairs with something like json.items. If there can be multiple items I think you would want something like json.items[0].$value[0].resource[0].name to read from the right section, but depending on how flexible the layout of your JSON response is you might need to specify the index (using [index]) at other points.

Jquery ajax request showing json object instead of alerting

This might not be the solution but this works for me. Due to the reason listed in the bold letters in my question, I did some changes.
I changed my MVC action as:

    [HttpPost]
public ActionResult Subscribe(Subscriber Sub)
{
KeyGenerator Validate = new KeyGenerator();
string Email = Sub.Username.Trim();
bool IsValid = Validate.ValidateEmail(Email);
ENT Ent = new ENT();
if (IsValid)
{
Subscriber SubEmail = Ent.Subscribers.Where(a => a.Username.ToLower() == Email.ToLower()).FirstOrDefault();
if (SubEmail != null)
{
//return Json(new { success = true, responseText = "Already subscribed!" }, JsonRequestBehavior.AllowGet);
return RedirectToAction("ViewSubMsg", new { id = "Already subscribed!" });
}
else
{
Ent.AddToSub(Email);
//return Json(new { success = true, responseText = "Thank you." }, JsonRequestBehavior.AllowGet);
return RedirectToAction("ViewSubMsg", new { id = "Thank you!" });
}
}
else
{
//return Json(new { success = false, responseText = "Invalid request!" }, JsonRequestBehavior.AllowGet);
return RedirectToAction("ViewSubMsg", new { id = "Invalid request!" });
}
}

Then I added a new action:

    [HttpGet]
public ActionResult ViewSubMsg(string id)
{
if (string.IsNullOrEmpty(id))
{
return Redirect("mysiteurl");
}
else
{
ViewBag.Msg = id;
return View();
}
}

And its view:

//View    
@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ViewSubMsg</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
alert("@ViewBag.Msg");
window.location.replace("mysiteurl");
});
</script>
</body>
</html>

How to get JSON response from AJAX request

You've not tagged jQuery, so I'm giving you a JavaScript only answer.

Read this on sending Forms from Mozzila

Here's an answer on sending a simple form using just Javascript. Code below is from that answer.

const form = document.querySelector("#debarcode-form");
form.addEventListener("submit", e => {
e.preventDefault();
const fd = new FormData(form);
const xhr = new XMLHttpRequest();
xhr.addEventListener("load", e => {
console.log(e.target.responseText);
});
xhr.addEventListener("error", e => {
console.log(e);
});
xhr.open("POST", form.action);
xhr.send(fd);
});

Make sure that the form you've rendered in the PHTML partial via ZF2 contains the correct action URL (so you've used the URL ViewHelper like so: <?= $this->url('name/of/path') ?>). This is to make sure that the JavaScript sends the data to the correct spot of your Zend Framework application.

Next, handle the data like so in your Controller:

public function handleFormAction()
{
/** @var \Zend\Http\Request $request */
$request = $this->getRequest();

/** @var \Some\Namespace\Of\CustomForm $form */
$form = $this->getCustomForm(); // You've created this using a Factory of course
if ($request->isPost()) {
$form->setData(\Zend\Json\Json::decode($request->getContent(), Json::TYPE_ARRAY));

if ($form->isValid()) {
$object = $form->getObject();

// object handling, such as saving

// Success response
// Redirect to success page or something
$this->redirect()->toRoute('success/route/name', ['id' => $object->getId()]);
}

// Fail response, validation failed, let default below handle it ;-)
}

if ($request->isXmlHttpRequest()) {
return new \Zend\View\Model\JsonModel([
'form' => $form,
'validationMessages' => $form->getMessages() ?: '',
]);
}

// Default response (GET request / initial page load (not async) )
return [
'form' => $form,
'validationMessages' => $form->getMessages() ?: '',
];
}

This answer obviously misses stuff, such as creating the Form for the Controller using a Factory, routing configurations and object hydration and handling.

This is because these things are out of scope of the question.


P.S. - I've used FQCN's (Fully Qualified Class Name), you should include them at the top of the file.

How to handle Ajax JSON response?

Since the response of the AJAX GET Request is an array, you have to access the key using index as suggested by @tymeJV.

$.ajax({
type: "GET",
url: window.apiURL,
data: data,
success: function(data) {
var myObj = $.parseJSON(data);
console.log(myObj[0]["result_code"]);
}
});

If the response is an array of objects:

Something like: [{"id":10858362988,"http_code":"200","result_code":"1"}, {"id":20858362988,"http_code":"404","result_code":"1"}], do something like below

$.ajax({
type: "GET",
url: window.apiURL,
data: data,
success: function(data) {
var myObj = $.parseJSON(data);
for (var i=0; i<myObj.length; i++) {
console.log(myObj[i]["result_code"]);
}
}
});

Jquery .ajax get request for a json response

You need to change the dataType to jsonp to avoid the CORS restriction.

JSONP is a technique used in JavaScript programs running in web browsers to request data from a server in a different domain. Typically this is prohibited by web browsers because of the same-origin policy. Wikipedia provides a far better description than I possibly could. See here.
When it comes to making GET requests to APIs, this is something you will encounter regularly, so it's worth knowing.

The jquery code allows you to view the JSON object in the console, which you can then manipulate as you please. The way I have currently included will change the div to the timestamp as returned by the JSON object. This jsfiddle should demo what you are looking for http://jsfiddle.net/zmxv2j7q/

        $(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url:"http://bustime.mta.info/api/siri/vehicle-monitoring.json",
data: {key: '##################',
OperatorRef:'MTA%20NYCT',
LineRef:'B54',
VehicleRef:'9531' },
dataType: 'jsonp',
async: false,
success: function(result){
console.log(result.Siri)
$("#div1").html(result);
$("#div1").html(result.Siri.ServiceDelivery.ResponseTimestamp)
}});
});
});

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Create a model


public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}

Controllers Like Below


    public ActionResult PersonTest()
{
return View();
}

[HttpPost]
public ActionResult PersonSubmit(Vh.Web.Models.Person person)
{
System.Threading.Thread.Sleep(2000); /*simulating slow connection*/

/*Do something with object person*/

return Json(new {msg="Successfully added "+person.Name });
}

Javascript


<script type="text/javascript">
function send() {
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}

$('#target').html('sending..');

$.ajax({
url: '/test/PersonSubmit',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#target').html(data.msg);
},
data: JSON.stringify(person)
});
}
</script>

JSON response at ajax request to JS variables

Since you're encoding you response in server side you should parse it in the js side, you could use $.parsejson() :

success: function(response) 
{
var response = $.parseJson(response);
//if $.parseJson dont work, use JSON.parse

var jsDlpath=response.DLpath;
var jsPhotoIDPath=response.PhotoIDPath;

alert(jsDlpath+" - "+jsPhotoIDPath)
}

NOTE : Use success/done callback instead of complete.

Hope this helps.



Related Topics



Leave a reply



Submit