Sending JSON request with parameters from obj-c - javascript

I've been trying out lots of tutorials and SO question to find a way to make the below code work in obj-c. Its a json response from the server, but nothing i've tried works. How should I make the below code in obj-c?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$.ajax({
url: "http://myjsonurl.com",
data: { employerID: "1", startDate: "2013-09-13", endDate: "2013-09-15" },
success: function(data) { console.log(data); }
});
</script>
</head>
</html>

Change this response page to be purely JSON like so,
{ "employerID": 1, "startDate": "2013-09-13", "endDate": "2013-09-15" }
Make sure to put quotes around those keys unless they are variables.
You can use a third-party tool (linked to one below) to call this url and get the response as data, then convert the data to a NSJSONSerialization object in the completion block.
https://github.com/andrewapperley/AFFNetworking

This is not only json response HTML script also came ,
Inform to your web-service person clear the HTML script give as array , dictionary format result

Related

Loading API with jQuery and Ajax, its returning Object Object, can't figure out how to get it to display JSON data in the console or anywhere

I'm calling an API with the following code and if all I get back is Object Object. I've tried a few different things, with no luck. I am getting jquery-3.4.1.min.js:2 XHR finished loading: GET "url.to.api" in console. Here's my code.
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="./jquery-3.4.1.min.js"></script>
<title></title>
</head>
<body>
<script>
$.ajax({
type: "GET",
url: "to API", // note, this doesn't end in JSON, but if I type the URL into my browser, I can view the JSON data
// Request headers
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Cache-Control", "no-cache");
xhrObj.setRequestHeader("Subscription-Key", my key");
},
})
.done(function (data) {
alert(data); // I changed this from a 'success' pop up to tell me it was working, but I can't display the data anywhere, so I tried in the box, and got object object
})
.fail(function () {
alert("error");
});
</script>
</body>
</html>
I'm new to API's, there is no documentation on this one at all. Thanks!
API URLs do not necessary need to end in JSON. If you view the API response through your browser and it is indeed in the JSON syntax, the API is likely to be outputting the result in JSON.
In that case, the ajax request will automatically parse the response from the API call to a javascript object, which is why it will show [object Object] when you do alert(data).
To print out the contents of the javascript object as a string, you will simply need to stringify the object before alerting using the JSON.stringify() syntax as follows:
alert(JSON.stringify(data)); // I changed this from a 'success' pop up to tell me it was working, but I can't display the data anywhere, so I tried in the box, and got object object

How to display a json data from a existing url using ajax call

I Am new in working with json and jquery. I am trying to study the basics of json and jquery by working on some example. So I use existing json data in http://api.androidhive.info/contacts for my example. I want to display this data in my HTML page. My code is:
<html>
<head>
<title>jQuery Ajax Example with JSON Response</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked.");
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php
type: "GET",
dataType: 'json', // Choosing a JSON datatype
success: function (msg) {
alert("ajax worked.");
JsonpCallback(msg);
},
})
function JsonpCallback(json)
{
for (var i in json.contacts) {
$('#wines').append('contacts: ' + json.contacts[i] + '<br/>');
}
}
return false; // keeps the page from not refreshing
});
});
</script>
</head>
<body>
<form method="post" action="">
<button value="all" type="submit">Get!</button>
</form>
<div id="wines">
<!-- Javascript will print data in here when we have finished the page -->
</div>
</body>
</html>
can any one please give me some brief introduction to JSON and how it's working ?
Thanks in advance.
You are iterating the JSON wrong, in your case since you are using jQuery (as mentioned) you can use the $.each(json, callback); helper fron jQuery, you can see the documentation here Jquery $.each documentation
For an example implementation I've created this JSFIDDLE LINK
for you. Have a great day ahead. Don't forget that JSON means
Javascript Object Notation
It's an object.
$.each(jsonData.contacts, function(k, v)
{
console.log(v.name);
$('#name').append('<li>'+v.name+'</li>');
});
jQuery
Am try to study the basics of json and jquery
Is a Javascript library with lots of very usefull methods. If you want to create a dynamic website it is very recommended to look into jQuery. There are many site with great explanation on what jQuery can do. As far as your example is concerned: There is an issue when passing variables/data from one framework to another or even when simply storing data. Here comes JSON.
JSON
Or JavaScript Object Notation (JSON) is used to solve exactly that problem. What is basically does is take all the desired data (array, variable, object, string etc.) and writes it in a human readable and for other frameworks readable fashion. I use JSON to store data in files when no database is available or when passing data from one framework to another (like JS <-> PHP).
Your example code
What happens here:
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked."); // not yet
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php --> this I don't know
type: "GET", // communication type
dataType: 'json', // Choosing a JSON datatype
success: function (msg) { // here, the whole content of the url is read, idealy it is in JSON format ofc
alert("ajax worked."); // hoorray
JsonpCallback(msg);
},
})
There is the serverside.php file that receives a GET command and returns HTML. All the HTML content is in JSON type (so no <stuff>, i.e. no actual HTML) and your success function returns that content in the msg variable. Typically you use something like
var obj = JSON.parse(text);
to convert the JSON data to Javascript variables. Read this here JSON in Javascript
JSONP
Now what if you want to do some domain crossing (as you suggested), then I strongly recommend to read this here What is JSONP all about? . It explains what JSONP is all about

Javascript Variable passing to PHP with Ajax

I've started working with ajax a little lately, but I'm having trouble with something I feel is incredibly simple: storing a JS variable in PHP.
Say I want to store a zip code (assigned with Javascript) and pass that to a PHP variable via AJAX: Why doesn't this work?
Keeping it simple for demonstration purposes, but this is the functionality I desire..
zipCode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});
});
zip.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
<?php
echo $_POST['zip_code'];
?>
</body>
</html>
An error: "Notice: Undefined index: zip_code" is all that is returned. Shouldn't "123456" be echo'd out?
You are supposed to put this:
<?php
// query database before echoing an associative array of `json_encode()`ed data if a response is needed
echo json_encode(array('zip_code' => $_POST['zip_code']);
?>
on a separate page, that is not an HTML page. AJAX just sends to that page, so you can use it and echo it out, making database queries before that, or what have you. Upon success you will see the result of your echo as the argument passed to the success method in this case if you used data as the argument the result for zip_code would be held in data.zip_code. Also, set your dataType:'JSON' in $.ajax({/*here*/}).
Here:
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST',
dataType: 'JSON',
success: function(data){
// in here is where you do stuff to your page
console.log(data.zip_code);
}
});
When you load the page, a call is being made to the server for zip.php, however that request is in no way linked to the page you're currently viewing.
If you look at the response to your ajax request - you'll see a copy of the page with the correct zip code echo'd
The actual answer then depends on what exactly you're trying to do (and a less simplified version of the code) to give you the best option.
The current setup you have doesn't make sense in practice
That is not how AJAX works. Thake a look at the example below. It will make an AJAX post to handle_zip.php and alert the results (Received ZIP code 123456)
start_page.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
This is just a static page.
</body>
</html>
zipcode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'handle_post.php',
data: {zip_code:zip},
type: 'POST',
success: handleData
});
});
}
function handleData(data) {
alert(data);
}
handle_post.php:
<?php
die ('Received ZIP code ' . $_POST['zip_code']);
As others have mentioned, it sounds like you're expecting the two bits of code to run at the same time. The reality is that:
zip.php will be parsed on the server (and resulting in the error)
Server will then serve up the HTML to the browser (which will have a blank body due to the $_POST not existing when the PHP was parsed)
browser will see the javascript .ready() and run that code
server will handle the POST request to zip.php, and generate the HTML you're expecting. It'll be returned in the AJAX response, but as you're not handling the response, nothing is shown in the current session. (you can see the POST response using any of the common web developer tools)
Remember, PHP runs on the server, then any javascript runs on the client. You're also missing the step of handling the response from the request you made in your javascript.
try this to give you better idea of what's happening.
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});.done(function(data ) {
console.log(data)
});
In your code, the server is creating the page first, so no javascript is run yet, therefore it creates an error because $_POST['zip_code'] doesn't exist. Then it sends this page to your browser and you can see that. At this point is when your browser executes the javascript, it sends the request again, now with POST data, the server should return the response of the request and you should be able to see it in the console.
You could make this 2 separate pages, one for viewing the page, and anotherone for processing the ajax request, or if for your application you want to do it in the same page, you would need an if statement to get rid of that error, something like
if(isset($_POST['zip_code'])){
echo $_POST['zip_code];
}

Using JavaScript to get JSON response and display on the webpage, testing JavaScript

I'm trying to create a JS app with the following functionality: A button that gets a JSON document and displays that text. I'm going through an Elasticsearch tutorial, and there is indeed valid JSON at the url I provide:
{"_index":"planet","_type":"hacker","_id":"xfSJlRT7RtWwdQDPwkIMWg","_version":1,"exists":true, "_source" : {"handle":"mark","hobbies":["rollerblading","hacking","coding"]}}
When using the code below...I get an alert of
[object Object]
instead of an alert with the full JSON. I'm planning to take the steps next of actually selecting part of the JSON, but I'd like to at least see the full document first...
Any ideas? Thank you in advance!
<!DOCTYPE html>
<html lang="en">
<head><title>Demo</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /></head>
<body>
<input id="testbutton" type="button" value="Test" />
<p id="results">results appended here: </p>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#testbutton").click(function() {
$.ajax({
url: 'http://localhost:9200/planet/hacker/xfSJlRT7RtWwdQDPwkIMWg',
dataType: 'json',
success: function(data) {
$("#results").append('all good');
alert(data);
},
error: function() {
$("#results").append("error");
alert('error');
}
});
});
});
</script>
</body>
</html>
Use alert(JSON.stringify(data));
jQuery tries to "best guess" the data format it receives, and parse it for you.
That's exactly what you're seeing. jQuery has already parsed the JSON into an object for you. To see the JSON representation, you can stringify the data again;
alert(JSON.stringify(data));
... or, you can tell jQuery not to parse the response in the first place, passing dataType: "string" as one of the options. data will then be the JSON representation, and you'll have to JSON.parse(data) to turn it into an object.
You are getting the JSON converted to a javascript object from which you can access the individual properties using the . operator like
alert(data._type);
Simple!
alert() calls .toString() on the object which returns "[object Object]".
Use console.log(data), right-click and goto the console (or hit F12).
Or just do as the others: alert(JSON.stringify(data));

Make cross-domain ajax JSONP request with jQuery

I would like to parse JSON array data with jquery ajax with the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function jsonparser1() {
$.ajax({
type: "GET",
url: "http://10.211.2.219:8080/SampleWebService/sample.do",
dataType: "jsonp",
success: function (xml) {
alert(xml.data[0].city);
result = xml.code;
document.myform.result1.value = result;
},
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the first name" onclick=jsonparser1() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
My JSON data is:
{"Data": [{"Address":"chetpet","FirstName":"arulmani","Id":1,"LastName":"sathish","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"ramaraj","Id":3,"LastName":"rajesh","City":"chennai"},{"Address":"ramapuram","FirstName":"yendran","Id":3,"LastName":"sathi","City":"chennai"}],"Code":true}
But i am not getting any output...anybody please help out...
Concept explained
Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Summary
Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.
If you have reqested with query string
?callback=my_callback_method
then, your server must response data wrapped like this:
my_callback_method({your json serialized data});
You need to use the ajax-cross-origin plugin:
http://www.ajax-cross-origin.com/
Just add the option crossOrigin: true
$.ajax({
crossOrigin: true,
url: url,
success: function(data) {
console.log(data);
}
});
Your JSON-data contains the property Data, but you're accessing data. It's case sensitive
function jsonparser1() {
$.ajax({
type: "GET",
url: "http://10.211.2.219:8080/SampleWebService/sample.do",
dataType: "json",
success: function (xml) {
alert(xml.Data[0].City);
result = xml.Code;
document.myform.result1.value = result;
},
});
}
EDIT Also City and Code is in the wrong case. (Thanks #Christopher Kenney)
EDIT2 It should also be json, and not jsonp (at least in this case)
UPDATE According to your latest comment, you should read this answer: https://stackoverflow.com/a/11736771/325836 by Abdul Munim
Try
alert(xml.Data[0].City)
Case sensitivly!
you need to parse your xml with jquery json parse...i.e
var parsed_json = $.parseJSON(xml);
alert(xml.data[0].city);
use xml.data["Data"][0].city instead
use open public proxy YQL, hosted by Yahoo. Handles XML and HTML
https://gist.github.com/rickdog/d66a03d1e1e5959aa9b68869807791d5

Categories

Resources