Making an API call in Javascript - new call at each click - javascript

Here's what I want to achieve:
I have an element on a webpage, let's call is storm
Every time the user clicks on the storm link, I want the following:
perform an API call which parameters are pre-defined BUT with the storm string as one of them
store the result (the API generates a JSON file) somewhere
parse the result with one method or another.
I have no problem parsing the JSON returned, but I would like to know how to do the first two steps.
NB: I use JS more than jQuery, but I'm not nazi on this.
Thank you very much for your help.
EDIT: thanks #ema
I've got a XHR model, attached under here.
Can you help me identify where I have to add my API url (from what I've understood, what is before the first question mark), and how to add to it the pre-defined parameters and the custom parameter (a string, containing storm for example)?
Thanks again
function XHR(url, method, data, onsuccess, onfailure, onprogress, onload, onabort) {
var request = new XMLHttpRequest();
// Ten seconds is ought to be enough for anybody.
var xhrtimeout = setTimeout(onfailure, 10000);
request.addEventListener("progress", onprogress, false);
request.addEventListener("load", onprogress, false);
request.addEventListener("error", onfailure, false);
request.addEventListener("abort", onabort, false);
request.addEventListener("readystatechange", function (e) {
if (request.readyState == 4) {
if (request.status == 200) {
clearTimeout(xhrtimeout);
onsuccess(request.responseText);
} else {
onfailure(e);
}
}
});
request.open(method, url, true);
request.send(data);
}
function getJSONAndParse(url, allDone) {
XHR(url, "GET", null, function(data) {
allDone(JSON.parse(data));
}, function() {
alert("error");
});
}
getJSONAndParse("http://lalala.com/json", function(parsedJSON) {
alert(parseJSON[0].name);
console.log(parseJSON);
});

You can use XMLHttpRequest, something like this:
var r = new XMLHttpRequest();
r.open("POST", "api/url", true);
r.onreadystatechange = function () {
var json = r.responseText;
// parse your json here
};
r.send("storm=value_of_storm&another_param=value_of_whatever");
HTH

Let me see if I understood..
To call an API from JQuery is very simple, and you cand use $.ajax (most complete) or $.post (simplest)
both you call on the click event that you can bind in $(document).ready with
$(document.ready(function(){
$('.mybuttons').off('click');//to only hit once if you have Postbacks
$('.mybuttons').on('click', myapicall);
});
example with $.ajax:
function myapicall(){
$.ajax({
beforeSend: function () {
// a 'Loading'
},
type: 'POST',
url: 'URL-OF-API',
contentType: 'application/json; charset=utf-8',
data: { stormvalue: 'the sorm value you want to send to API'},
dataType: 'json',
success: function (json) {
try {
json = JSON.parse(json.d);
// now you have a json object to play with, and if its a string, then you can """save""" using eg. input hidden
} catch (ex) {
alert(ex);//show the error parsing json
}
},
error: function (xhr, ajaxOptions, thrownError) {
var r = jQuery.parseJSON(xhr.responseText);
alert(r); // show the error of callback
},
complete: function (json) {
alert('sucess!');
}
});
}
example with $.post
function myapicall(){
$.post('URL-OF-API', { stormvalue: 'the sorm value you want to send to API'},
function (json) {
try {
json = JSON.parse(json.d);
// now you have a json object to play with, and if its a string, then you can "save" using eg. input hidden
} catch (ex) {
alert(ex);//show the error parsing json
}
}
);
}
Hope I can help you, and sorry for bad english, ;-)

Related

Calling ajax request continually until a certain search request is found

I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"

I've a not working AJAX function

I'm building a time management system for the place I work for. While coding it I've created a system which the user can configure the database details (like the wordpress first run install) and once the data is saved successfully I want to show the next step.
The first part is working perfectly but I've run into some issues with the second part where the system checks the connection and start creating the database and the needed tables.
Up to now I've been using JSON to send and receive PHP response text. But now I wanted to create a AJAX function to the same as JSON. But the problem is the AJAX function is sending the data but I can't get the response text.
I went through most of the SO titles came up when I did a google search (might have missed once) but none of them worked. When I try to get the output from an alert it shows as oject[Object] on the popup.
Below is my jquery which I have the AJAX coded into.
function checkResponse(){
var res = $('#response').text();
if(res === "Saved"){
$.ajax({
url: './bin/config/createConfig.php',
type:'get',
data:{check:'check'},
dataType:'json',
complete: function (data) {
alert(data.responseText);
}
});
// $('#nextstep').show();
// $('#dbConfig-details').hide();
}
}
Above function is called by the below setTimeOut.
if(noEmpty && confirm('Are you sure all details to be true?')){
createConfig();
setTimeout('checkResponse();', 1000);
}
This is the PHP which the above AJAX send data to.
if (!empty($_REQUEST["check"])){
if(file_exists('../iConnect/node.php')){
$readFile = file_get_contents('../iConnect/node.php');
$dataTxt = unserialize($readFile);
extract($dataTxt);
try{
$dbConnect = new PDO('mysql:host='.$dbHost.';dbname='.$dbName,$dbUser,$dbPass);
$dbConnect -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected";
}catch(PDOException $ex){
echo "ERROR: ".$ex->getMessage();
exit();
}
}else{
echo "File missing";
}
}
The creatCofig() code.
function createConfig(){
var dbUser = document.getElementById("dbUser").value,
dbPass = document.getElementById("dbPass").value,
dbName = document.getElementById("dbName").value,
dbHost = document.getElementById("dbHost").value;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","./bin/config/createConfig.php?dbUser="+dbUser+"&dbPass="+dbPass+"&dbName="+dbName+"&dbHost="+dbHost,true);
xmlhttp.send();
}
I know I'm missing something with the AJAX but my knowledge is limited on AJAX can some one please show me what am I doing wrong.
The complete callback has a signature of (jqXHR jqXHR, String textStatus).
Read about it here here.
Try the following pattern :
$.ajax({
url: ...,
type: ...,
data: ...,
dataType: ...,
}).then(function (data) {
alert(data.responseText);
});
Also, don't rely on a timeout to wait for an ajax response. That's what promises are for.
In createConfig(), use jQuery.ajax() and return a promise as follows :
function createConfig() {
return $.ajax({
'type': 'post',
'url': './bin/config/createConfig.php',
'data': {
'dbUser': $("#dbUser").val(),
'dbPass': $("#dbPass").val(),
'dbName': $("#dbName").val(),
'dbHost': $("#dbHost").val()
}
}).then(function(response) {
$("#response").html(response);
return response;
});
}
Now you can write :
if (noEmpty && confirm('Are you sure all details to be true?')) {
createConfig().then(checkResponse);
}

Jquery Ajax function is not working while calling the Servlet

I am facing some problem while calling ajax. Can anyone look at my code and suggest something to solve my problem
function search(file,input){
$.ajax({url:'/Searchandhighlight?name='+input+'&file='+file,type:"post",
success:function(){
$("#bodyy").html();
}
});
}
I am using ajax to call the servlet and servlet changes some contents of database and after success I am trying to refresh my "#bodyy" div.
Thanks in advance
Firstly let us know what file variable holds.
Normally Ajax call with parameters goes like this. dataType depends on what kind of response you are expecting.
$.ajax({
type: "POST",
url: "/Searchandhighlight",
dataType: "json",
data: {"name" : input, "file" : file},
success:function(data){
if(data){
alert("success");
}
},
error:function(){
alert('failed');
}
})
I finally solved my issue by following code
function search(file,input){
if(input != "") {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Searchandhighlight?name=" + input + "&file=" + file, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location.reload();
}
}
xmlhttp.send(null);
}
}

Request data from server using AJAX and Jquery

I need to create a script that takes data from a form, send it to a server (there's some diabolical C# procedure on it, that's not my job...), the server resolves the string and reply me with 4 strings (yup, they are in spanish): 'pendiente', 'verificada', 'rechazada', and finally 'error'
Now, I have to get that response and properly show the correct message (hidden-inline html).
All this procedure shouldn't "refresh" the actual page, so I'm using AJAX for this.
Have in mind I'm a newbie :) I've learned Jquery just for this task,
and I have to say I'm quite happy with this.
The problem
I don't really know how to handle or "manipulate" that request using Jquery... I figured how to send the data to the server, but I think I'm handling incorrectly the response.
The code:
In this case I've adapted the script, every different response should get its own border color, I'm using conditionals (they are wrong for sure) to add CSS clases to an #ajax div.
So, it might have silly errors...
$(document).ready(function () {
$('#enviar').click(function (event) {
event.preventDefault(); //avoid page refresh
var consulta = $('#string').val();
$("#normal").text(consulta);
//Start AJAX!
$.ajax({
async: true,
cache: false,
type: 'post',
url: 'http://184.22.97.218:8081/chequeostatusdonation', //la del servr
data: {
html: consulta
},
dataType: 'html',
beforeSend: function () {
console.log('Sending...');
},
success: function (data) {
console.log('Just sent -'+data+'- with success dooh');
$('#ajax').html(data);
//start conditional
if (data == pendiente) {
$("#ajax").addClass(pendiente);
} else if (data == verificada) {
$("#ajax").addClass(verificada);
} else if (data == rechazada) {
$("#ajax").addClass(rechazada);
} else {
$("#ajax").html('<h1>error</h1>');
}
//end condicional
},
complete: function () {
console.log('Listo el pollo');
}
});
});
});
Here is the JSFiddle
Edit: Now, I just found these two links
learn.jquery.com/code-organization/concepts/
learn.jquery.com/code-organization/beware-anonymous-functions/
Screw my code! :D
Async is by default "true", so you don't need to mention that one in your code.
You included a link to the server (in the URL-field), but what is the file you are trying to open? You will need to include the path to where you will get the data from (file / script). To make Ajax work, you will need to respect the "same origin policy", so you can insert a relative path to the file / script.
Is the response of your call always a short string with one of those key words ('pendiente', 'verificada', 'rechazada' or 'error)? In that case I would recomment using "text" instead of "html" as dataType, as jQuery will try to parse it to a DOM-structure, which is not what you want here.
Your if-statements (and class-assignments as well) aren't working because you try to compare it to a non-excisting variable instead of the string with that value. You should use " or ' around your string to solve that.
This code should be working. If not, let me know. Include the error given in the console of the browser.
$(document).ready(function () {
$('#enviar').click(function (event) {
event.preventDefault(); //avoid page refresh
var consulta = $('#string').val();
$("#normal").text(consulta);
//Start AJAX!
$.ajax({
type: 'POST',
cache: false,
url: 'RELATIVE_PATH_HERE', //la del servr
data: {
html: consulta
},
dataType: 'text',
beforeSend: function () {
console.log('Sending...');
},
success: function (data) {
console.log('Just sent -'+data+'- with success dooh');
$('#ajax').html(data);
//start conditional
if (data === 'pendiente') {
$("#ajax").addClass('pendiente');
} else if (data === 'verificada') {
$("#ajax").addClass('verificada');
} else if (data === 'rechazada') {
$("#ajax").addClass('rechazada');
} else {
$("#ajax").html('<h1>error</h1>');
}
//end condicional
},
complete: function () {
console.log('Listo el pollo');
},
error: function() {
console.log('Problem with XHR-request');
});
});
});
Be careful with .addClass if you process multiple Ajax-calls as they will add on each other.

Javascript AJAX call to Jquery Call

In order to have my code written almost fully written in Jquery, I want to rewrite an AJAX call in Jquery.
It's a call from a webpage to a Tomcat servlet.
Similar code of my present situation:
var http = new XMLhttpRequest();
var url = "http://example.com/MessageController?action=send";
http.onreadystatechange = function ()
if (http.readyState == 4)
{
if (http.status == 200){ var response = http.responseText;}
else {/*code2*/}
};
http.async = false;
http.open("POST", url, true);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(string);
Which would be the best way to do this? .ajax or .post? Could you help me with some pseudo code to start this?
Use .ajax or (as you are using POST) .post:
$.ajax({
url: "http://example.com/MessageController",
type: "POST",
data: { action: "send", yourStringName: "something" },
async: false, // make sure you really need it
contentType:'application/x-www-form-urlencoded'
}).done(function(response) {
console.log(response);
});
It doesn't matter which one you use, because .post is shorthand for .ajax.
You can use jQuery post.
var url="MessageController"
$.post(url, { action : "send"} ,function(data){
//response from MessageController is in data variable
//code 1
alert(data)
}).error(function(){
alert("error"); //code 2
})
Assuming MessageController is some url in your domain and you are aware of the same origin policy

Categories

Resources