How to implement asynchronous service call in javascript? - javascript

I want to call my server asynchronously.
My code is as below:-
function GetSynchronousJSONResponse(url, postData) {
var xmlhttp = null;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject) {
if (new ActiveXObject("Microsoft.XMLHTTP"))
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
else
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open("POST", url, false);
xmlhttp.send(postData);
var responseText = xmlhttp.responseText;
return responseText;
}
But service call gives "Bad Request" error.
Please help

You forgot to add content type in your request.
please add below line and try again
xmlhttp.setRequestHeader("Content-Type","application/json;charset=utf-8");

function GetSynchronousJSONResponse(URL,postData)
{
$.ajax({
url : URL,
type : "POST",
data : JSON.stringify(postData),//if required
contentType : 'application/json',
success : function(data) {}
})
}
you can Try this .....................

Related

How to send AJAX post request and receive back JSON data in Vanilla JS?

I have used JQuery example to send form data and receive back JSON data. Now I would like to do the same thing in plain/vanilla Javascript. Here is example of my JQuery code:
$('.frmSubmitData').on('submit', function(e){
e.preventDefault();
var formData = $('#myForm').serialize();
console.log(formData);
$.ajax({
type: 'POST',
encoding:"UTF-8",
url: 'Components/myTest.cfc?method=testForm',
data: formData,
dataType: 'json'
}).done(function(obj){
if(obj.STATUS === 200){
console.log(obj.FORMDATA);
}else{
alert('Error');
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
});
And here is what I have so far in plain JS:
function sendForm(){
var formData = new FormData(document.getElementById('myForm')),
xhr = new XMLHttpRequest();
xhr.open('POST', 'Components/myTest.cfc?method=testForm');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(formData);
}
I think that something is wrong in way how I handle response with JSON data. If anyone can help me with problem please let me know. Thank you.
Optimally, for Firefox/Chrome/IE and legacy IE support, first determine the request type:
function ajaxReq() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Browser does not support XMLHTTP.");
return false;
}
}
Then, send the request:
var xmlhttp = ajaxReq();
var url = "http://random.url.com";
var params = "your post body parameters";
xmlhttp.open("POST", url, true); // set true for async, false for sync request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params); // or null, if no parameters are passed
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
try {
var obj = JSON.parse(xmlhttp.responseText);
// do your work here
} catch (error) {
throw Error;
}
}
}

Javascript data input Json

I have data on a website which looks like this
[{"id":213877,"pic":"https://graph.facebook.com/ariel.barack/picture?type=square","url":"https://angel.co/ariel-barack","name":"Ariel Barack","type":"User"},{"id":109396,"pic":"https://d1qb2nb5cznatu.cloudfront.net/users/109396-medium_jpg?1405528556","url":"https://angel.co/mattbarackman","name":"Matt Barackman","type":"User"},{"id":881384,"pic":null,"url":"https://angel.co/austin-barack","name":"Austin Barack","type":"User"},{"id":245752,"pic":null,"url":"https://angel.co/drgoddess","name":"Dr. Goddess","type":"User"}]
I have a html file with javascript code as follows:
function httpGet(url) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
var data = xmlHttp.responseText;
data = (JSON.parse(data));
I need to access the "name" attribute from the URL database and form a string concat of all the name attributes. Could you please help me out what to be done next?
Below is my test data
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name);
For Example if you want to acces the name you can access as like above.
To concatenate the vales do like below
var Output = json.map(function(result) {
return result.name;
}).join('');
alert(Output);
Have a look on it https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var result = data.map(function(user) {
return user.name;
}).join('');
<html>
<head>
<script type="text/javascript">
function fun(){
var str='[{"id":213877,"pic":"https://graph.facebook.com/ariel.barack/picture?type=square","url":"https://angel.co/ariel-barack","name":"Ariel Barack","type":"User"},{"id":109396,"pic":"https://d1qb2nb5cznatu.cloudfront.net/users/109396-medium_jpg?1405528556","url":"https://angel.co/mattbarackman","name":"Matt Barackman","type":"User"},{"id":881384,"pic":null,"url":"https://angel.co/austin-barack","name":"Austin Barack","type":"User"},{"id":245752,"pic":null,"url":"https://angel.co/drgoddess","name":"Dr. Goddess","type":"User"}]';
var obj=eval(str);
var names='';
for(var item in obj){
names+=obj[item].name;
}
alert(names);
}
</script>
</head>
<body>
<input type="button" onclick="fun()" value="click me"/>
</body>
</html>
I got what you mean.It is the Ajax problem.If you really use the code that you provided,it should not work.Here is the Ajax code to get response from a certain url:
var ajaxRequest;
//create ajax object
function createAjaxRequest() {
var xmlhttp = null;
if (window.XMLHttpRequest) {// code for all new browsers
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {// code for IE5 and IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
//send request and identify callbak handler
function send(url) {
ajaxRequest = createAjaxRequest();
ajaxRequest.onreadystatechange = callback;
ajaxRequest.open("POST", url, true);
ajaxRequest.send(null);
}
// the callback handler
function callback() {
if (ajaxRequest.readyState == 4) {// 4 = "loaded"
if (ajaxRequest.status == 200) {// 200 = OK
var data = ajaxRequest.responseText;
}
else {
alert("Problem retrieving data");
}
}
}

ajax unexpected token *

I have ajax script but it returns unexpected token *. I use ajax example from w3school.com and it different from usually. This is my script:
<script>
$("#conform").click(function ()
{
var a= $(this).closest(".col").prev().find("#prod_qty").val();
var b= $(this).prev().val();
var c= $(this).closest("#highlight_product").find("#name").val();
var d= b * c;
var e= "<?php echo $_SESSION['name'] ?>";
var f= "<?php echo $_SESSION['email'] ?>";
}
)
function buy()
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ('Browser does not support HTTP Request');
return;
}
var url='buy.php?user='+e+'&email='+f+'&product='+c+'&count='+a+'&total='+d;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open('GET',url,true);
xmlHttp.send(null);*/
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=='complete')
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e)
{
xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');
}
}
return xmlHttp;
}
I try find it in google, It says problem with dataType, It must HTML. But i dont know how to change it, anyone know?
The line
xmlHttp.send(null);*/
has unexpected "*/" which needs to be removed
xmlHttp.send(null);
Can I suggest using Jquery AJAX wrapper? It's cross browser compliant, much neater and lets gives you a handy callback function on completion(really important) since the result is ASYNC which allows you to retrieve data before execution.
$.ajax({
type: "POST",
url: '',
data : '',
dataType: 'JSON',
}).done(function(data) {
// this will be run when the AJAX request completes
var ParsedData= jQuery.parseJSON(data);
// this will be run when the AJAX request succeeds
}).fail(function() {
// this will be run when the AJAX request fails
}).always(function() {
// this will be run when the AJAX request is complete, whether it fails or succeeds
});
}

want to create a js plugin that sends a lot of data async to another server

is there a way i can send a lot of data to another server asynchronously via javascript without running into cross domain problems?
how is google analytics able to send their encoded data to their servers?
you can use Ajax to send a lot of data.
Native Javascript:
function NewAjax(){
var xmlhttp=false;
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp = false;
}
}
if(!xmlhttp && typeof XMLHttpRequest!='undefined'){
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function load_page (url, container){
ajax=NewAjax();
ajax.open("GET", url,true);
ajax.onreadystatechange=function(){
if(ajax.readyState==1){
container.innerHTML = "loading";//<-- Preload
}else if(ajax.readyState==4){
//Page loaded
if(ajax.status==200){
//OK
container.innerHTML = ajax.responseText;
add_action();
}else if(ajax.status==404){
//Page doesn't exist
container.innerHTML = "Erro loading page";
}else{
//Show error
container.innerHTML = "Error:".ajax.status;
}
}
}
ajax.send(null); }
Or
JQuery Ajax:
$.ajax({url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');}});

How can I convert this working JS code to JQUERY

var xmlHttp;
function RefreshORP(eventTarget, eventArgument)
{
xmlHttp = GetXmlHttpObject();
if(xmlHttp == null)
{
return true;
}
xmlHttp.onreadystatechange = StateChanged;
var params = GetFormParam(eventTarget,eventArgument);
xmlHttp.open("POST","/contact.jsp",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("ajaxcall", "true");
xmlHttp.send(params);
}
In jQuery you have it all done...
$.post("/contact.jsp", $("formID").serialize(), function(data){
// process callback
});
jQuery will also set all appropriate (and somehow standardized) request headers.

Categories

Resources