I want to create a HTML page which offers a button (link, some other clickable element, etc.) which, when pressed, sends a specific constant POST request to a specific constant server. The value I need to post is a specific constant JSON-encoded value ({"key":"value"}), so for HTTP it is just a very short constant string.
The value and the URL I have to use are constant. In order to make something happen, I have to send exactly this constant POST request. There is no need to parameterize this request or to "set a value" or similar. Also, I have no parameter name or similar. I must not send a parameter list with a parameter whose value is the JSON-encoded value, but I must send the JSON-encoded value by itself. The complete POST request can look like this:
POST /post/path/to/action HTTP/1.1
Host: the.specific.server
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
{"key":"value"}
(NOT parameter={"key":"value"} or similar as body!)
The server is not under my authority but a service I want to use.
With pure shell means I can do this very simply using curl:
curl http://the.specific.server/post/path/to/action -d '{"key":"value"}'
I imagined something like
<button url="http://the.specific.server/post/path/to/action"
value="{%22key%22:%22value%22}">visible text</button>
but I found nothing appropriate.
Based on questions like this or this or this I tried various approaches like this one:
<form method="POST" action="http://the.specific.server/post/path/to/action">
<input type="text" id="key" key="value">value</input>
<button type="submit" value="{%22key%22:%22value%22}">visible text</button>
</form>
With or without the input field, the button, with other arguments, other values, etc. but nothing finally sent anything useful to the server when pressed. At best I got something which was also transmitting a parameter name (thus the payload was not just the Json-encoded value).
I guess I'm just missing something basic in this :-}
There is no way in HTML to generate JSON from forms. You need here to implement this using an AJAX request.
Using jQuery it could be something like that:
$.ajax({
type: 'POST',
url: 'http://the.specific.server/post/path/to/action',
data: '{"key":"value"}',
success: function() {
// Successful response received here
},
dataType: 'json',
contentType : 'application/json'
});
This will be trigger when clicking on a button or a link, as described below:
$('#myButtonId').click(function() {
$.ajax({
(...)
});
});
This can be put for example in a script in your page after including jQuery library, as described below:
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
// Waiting for the DOM to be loaded
$(document).ready(function() {
$('#myButtonId').click(function() {
// When button is clicked
$.ajax({
(...)
});
});
});
</script>
<body>
<button id="myButtonId">CLICK ME</button>
</body>
</head>
Edited
Here is the way to send an HTTP request using raw JavaScript API: http://www.quirksmode.org/js/xmlhttp.html.
I adapted this code to work for your use case:
function sendRequest(url, callback, postData, contentType) {
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
req.setRequestHeader('User-Agent','XMLHTTP/1.0');
if (postData) {
if (contentType) {
req.setRequestHeader('Content-type', contentType);
} else {
req.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
}
}
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
} catch (e) {
continue;
}
break;
}
return xmlhttp;
}
To execute your request, simply use the function sendRequest:
sendRequest(
'http://the.specific.server/post/path/to/action',
function() {
// called when the response is received from server
},
'{"key":"value"}',
'application/json');
Hope it helps you,
Thierry
A simple, customisable an no dependencies solution based on : https://gist.github.com/Xeoncross/7663273
May works on IE 5.5+, Firefox, Opera, Chrome, Safari.
<html>
<body>
<button id="myButtonId" onclick='post("http://the.specific.server/post/path/to/action", "{\"key\":\"value\"}");'>CLICK ME</button>
</body>
<script>
function post(url, data, callback) {
try {
var req = new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
req.open('POST', url, 1);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.send(data)
} catch (e) {
window.console && console.log(e);
}
}
</script>
</html>
You are looking for FORM encoding algorithm which enables form data to be transmitted as json.
Have a look at W3C HTML JSON form submission. It is not active and not likely to be maintained.
So, you are better off using the above JS or Jquery solution or use a server side forwarding. My suggestion is to use jquery as most websites point to google cdn these days and jquery is mostly browser cached. With below code, you neatly fire a POST request without worrying about underlying browser variants.
$.ajax({
type: 'POST',
url: 'http://the.specific.server/post/path/to/action',
data: '{"key":"value"}',
success: function() {
// Successful response received here
},
dataType: 'json',
contentType : 'application/json'
});
Try this suggestion using JQuery methods and Ajax:
$(document).ready(function(){
$("#myForm").submit(function(){
$.ajax({type:"POST",
data: $(this).serializeObject(),
url:"http://the.specific.server/post/path/to/action",
contentType: "application/json; charset=UTF-8",
success: function(data){
// ... OK
},
error: function(){
// ... An error occured
}
});
return false;
});
});
Note : serializeObject method converts form elements to a JSON string.
I now went for a simplistic solution (because that's what I wanted) I found myself by searching for more answers. It seems there is no way around using JS for this task.
<button onClick="postCommand('mypath', 'mykey', 'myvalue')">Click</button>
<script>
function postCommand(path, key, value) {
var client = new XMLHttpRequest();
var url = "http://the.specific.server/" + path;
client.open("POST", url, true);
client.send("{\"" + key + "\":\"" + value + "\"}");
}
</script>
This is in general #aprovent's answer, so I accepted his and granted him the bounty.
Related
I am trying to create a website in where I can get a particular json object from a url and then display it on the website. The field that I am trying to display is UV_INDEX out of three fields. Nothing is being printed out. I don't even know if it is getting the json object.
<!DOCTYPE html>
<html>
<body>
<h2>EPA </h2>
<p id="demo"></p>
<script>
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/92507/JSON').then(function(data) {
document.getElementById('UV_INDEX').innerHtml=json.result;
alert('Your Json result is: ' + json.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
</script>
</body>
</html>
I added a third-party chrome extenstion for CORS issue. But I get this error
Uncaught (in promise) ReferenceError: json is not definedmessage: "json is not defined"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: Error
You can try using a Ajax plugin to make CORS request where the CORS headers are not being served from service.
Add Jquery library and add your installed CORS ajax scripts after that:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/jquery.ajax-cross-origin.min.js"></script>
Now you can make cross origin request by just adding crossOrigin: true in your Ajax:
E.g.
$.ajax({
crossOrigin: true,
url: "http://iaspub.epa.gov/enviro/efservice/getEnvirofactsUVDAILY/ZIP/92507/JSON/",
success: function(data) {
console.log(data);
}
});
You can try putting the same URL in the below demo page to receive the Json data.
See live demo.
I have two html files called index.html & video.html
video.html holds coding like:
<div id="video">
<iframe src="http://www.youtube.com/embed/tJFUqjsBGU4?html5=1" width=500 height=500></iframe>
</div>
I want the above mentioned code to be crawled from video.html page from index.html
I can't use any back-end coding like php or .net
Is there any way to do using Ajax?
Try this...
$.ajax({
url: 'video.html',
success: function(data) {
mitem=$(data).filter('#video');
$(selector).html(mitem); //then put the video element into an html selector that is on your page.
}
});
For sure,send an ajax call.
$.ajax({
url: 'video.html',
success: function(data) {
data=$(data).find('div#video');
//do something
}
});
Yep, this is a perfect use case for ajax. When you make the $.ajax() request to your video.html page, you can then treat the response similar to the way you'd treat the existing DOM.
For example, you'd start the request by specifying the URI in the the following way:
$.ajax({
url: 'video.html'
})
You want to make sure that request succeeds. Luckily jQuery will handle this for you with the .done callback:
$.ajax({
url: "video.html",
}).done(function ( data ) {});
Now it's just a matter of using your data object in a way similar to the way you'd use any other jQuery object. I'd recommend the .find() method.
$.ajax({
url: "video.html",
}).done(function ( data ) {
$(data).find('#video'));
}
});
Since you mentioned crawl, I assume there is the possibility of multiple pages. The following loads pages from an array of urls, and stores the successful loads into results. It decrements remainingUrls (which could be useful for updating a progressbar) on each load (complete is called after success or error), and can call a method after all pages have been processed (!remainingUrls).
If this is overkill, just use the $.ajax part and replace myUrls[i] with video.html. I sepecify the type only because I ran into a case where another script changed the default type of ajax to POST. If you're loading dynamic pages like php or aspx, then the cache property might also be helpful if you're going to call this multiple times per session.
var myUrls = ['video1.html', 'video2.html', 'fail.html'],
results = [],
remainingUrls;
$(document).ready(function () {
remainingUrls = myUrls.length;
for (var i = 0, il = myUrls.length; i < il; i++) {
$.ajax({
url: myUrls[i],
type: 'get', // somebody might override ajax defaults
cache: 'false', // only if you're getting dynamic pages
success: function (data) {
console.log('success');
results.push(data);
},
error: function () {
console.log('fail');
},
complete: function() {
remainingUrls--;
if (!remainingUrls) {
// handle completed crawl
console.log('done');
}
}
});
}
});
not tested, but should be something similair to this: https://stackoverflow.com/a/3535356/1059828
var xhr= new XMLHttpRequest();
xhr.open('GET', 'index.html', true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementsByTagName('html').innerHTML= this.responseText;
};
xhr.send();
In prototype you can use the following code.
var form = control.form;
new Ajax.Updater('result', form.action,
{ method: 'post',
parameters: form.serialize({submit: control.name})
}
);
return false;
Is there something like this in mootools? Simple but elegant ?
Yes, there is Form.Request
i.e.
(function($){
new Form.Request($('formID'), $('responseID'), {
onSuccess : function() {
//form submitted correctly
}
});
})(document.id);
where $('formID') is your form, and $('responseID') is the element that will hold the response (i.e. a response message)
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am having the bellow function .
Here i want to return ajax success from user defined function . How to do this
alert(Ajaxcall(id_array,"del"));
function Ajaxcall(id_array,type){
$.ajax({
type: "POST",
url: "serverpage.php",
cache:false,
data: ({id:id_array,type:type}),
success: function(msg){
return msg; //this returns nothing
}
});
alert(msg); // this one undefined
}
thanks
The "a" in "ajax" stands for "asynchronous" ("Asynchronous JavaScript And XML", although these days most people use it with JSON rather than XML).
So your Ajaxcall function returns before the ajax call completes, which is why you can't return the message as a return value.
The usual thing to do is to pass in a callback instead:
Ajaxcall(id_array,"del", functon(msg) {
alert(msg);
});
function Ajaxcall(id_array,type, callback){
$.ajax({
type: "POST",
url: "serverpage.php",
cache:false,
data: ({id:id_array,type:type}),
success: function(msg){
callback(msg);
}
});
}
It's surprisingly easy with JavaScript, because JavaScript's functions are closures and can be defined inline. So for instance, suppose you wanted to do this:
function foo() {
var ajaxStuff, localData;
localData = doSomething();
ajaxStuff = getAjaxStuff();
doSomethingElse(ajaxStuff);
doAnotherThing(localData);
}
you can literally rewrite that asynchronously like this:
function foo() {
var localData;
localData = doSomething();
getAjaxStuff(function(ajaxStuff) {
doSomethingElse(ajaxStuff);
doAnotherThing(localData);
});
}
I should note that it's possible to make an ajax call synchronous. In jQuery, you do that by passing the async option in (setting it false). But it's a very bad idea. Synchronous ajax calls lock up the UI of most browsers in a very user-unfriendly fashion. Instead, restructure your code slightly as above.
But just for completeness:
alert(Ajaxcall(id_array,"del"));
function Ajaxcall(id_array,type){
var returnValue;
$.ajax({
type: "POST",
url: "serverpage.php",
cache:false,
async: false, // <== Synchronous request, very bad idea
data: ({id:id_array,type:type}),
success: function(msg){
returnValue = msg;
}
});
return returnValue;
}
JQuery has a number of global Ajax event handlers, including $.ajaxComplete() and $.ajaxSuccess() (ref: http://api.jquery.com/ajaxSuccess/).
The code can be attached to any DOM element and looks like this:
/* Gets called when all request completes successfully */
$("#myElement").ajaxSuccess(function(event,request,settings){
$(this).html("<h4>Successful ajax request</h4>");
});
This code will execute whenever any successful Ajax call is completed.
I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:
$('#Search').click(function () {
var query = $('#query').valueOf();
$.ajax({
url: '/Products/Search',
type: "POST",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
for (var x = 0; x < data.length; x++) {
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
$(content).appendTo("#ProductList");
// updateListing(data[x]);
}
}
});
});
It seems that the JSON object is being returned correctly because "alert(data)" displays the following
[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]
but when I try displaying the Id or Name to the page using:
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
it returns "undefined" to the page. What am I doing wrong?
Thanks for the help.
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
It works fine,
Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "تهران",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do
alert(data)
if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert
[object Object]
If this the response then you can be sure that you can use this as an object (json in this case).
Thus, you need to convert your string into json first, before using it by doing this:
JSON.parse(data)
Well... you are about 3/4 of the way there... you already have your JSON as text.
The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.
It isn't... its just a string.
Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.
You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.
myResult = JSON.parse(request.responseText);
Now myResult is a javascript object containing the properties that were transmitted through AJAX.
That should allow you to handle it the way you appear to be trying to.
Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.
For the record, this was already answered by Andy E for someone else HERE.
edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.
Try the jquery each function to walk through your json object:
$.each(data,function(i,j){
content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
$('#ProductList').append(content);
});
you can use the jQuery parseJSON method:
var Data = $.parseJSON(response);
input type Button
<input type="button" Id="update" value="Update">
I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below
$(function() {
$('#Search').click(function() {
var query = $('#query').val();
var update = $('#update').val();
$.ajax({
type: 'POST',
url: '/Products/Search/',
data: {
'insert': update,
'query': address,
},
success: function(res) {
$('#ProductList').empty('');
console.log(res);
json = JSON.parse(res);
for (var i in json) {
var row = $('<tr>');
row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
$('</tr>');
$('#ProductList').append(row);
}
},
error: function() {
alert("did not work");
location.reload(true);
}
});
});
});
I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this
$.ajax({
url : url,
dataType : 'json'
})
.done(function(data, statusText, resObject) {
var jsonData = resObject.responseJSON
})
From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).
Or you can set the dataType to json to convert it automatically.
parse and convert it to js object that's it.
success: function(response) {
var content = "";
var jsondata = JSON.parse(response);
for (var x = 0; x < jsonData.length; x++) {
content += jsondata[x].Id;
content += "<br>";
content += jsondata[x].Name;
content += "<br>";
}
$("#ProductList").append(content);
}
Use
dataType: 'json'
In .NET you could also return Json(yourModel) in your action method/API controller.
And parse the returned JSON as follows in the Jquery .ajax:
if you've a complex object: navigate to it directly.
success: function (res) {
$.each(res.YourObject, function (index, element) {
console.log(element.text);
console.log(element.value);
});
});