How can I make a Ajax request & response with firefox OS? - javascript

I'm having a php function which returns a Json data from db.
I want get all the json from the function and display that into my Firefox App. I tried Jquery Ajax. But its not working.
Any other library or Ajax coding?
var a=1;
$.ajax({
url:"http://localhost/shop/home/home/demo",
type:"POST",
data:{b:a},
success: function(msg){
alert(msg);
}
});
It's not working with firefox app. Help me.

You must use the mozSystem property. Here's an example using native XMLHttpRequest.
var xhr = new XMLHttpRequest({
mozSystem: true
});
xhr.open("POST", "http://localhost/shop/home/home/demo");
xhr.onload = function() {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send("b=" + a); //serialized data
Hope it helps!

Related

API Call in Cordova App Returns 404 Error

I've been using XMLHTTPRequest first, but I have tried using jQuery Ajax. Keeps the same error. Used chrome://inspect to inspect my phone and in the console shows this:
GET https://freecurrencyapi.net/api/v2/latest?apikey=my-key&base_currency=EUR 404 (Not Found)
The code for XMLHTTPRequest:
function getJSON(url) {
var http = new XMLHttpRequest();
http.open("GET", url, false);
http.send(null);
return JSON.parse(http.responseText);
}
The code for jQuery Ajax:
`
$.ajax({
type: "GET",
url: "https://freecurrencyapi.net/api/v2/latest?apikey=my-key&base_currency=" + from_val
}).done((data) => {
to_box.value = data.data[to_val] * parseFloat(from_box.value);
});
`
Please tell me what to do. thank you.

Converting native JS Ajax snippet to JQuery alternative?

I am updating historic JS code from another author but having problems converting the below to the JQuery alternative:
var xhr = new XMLHttpRequest();
xhr.open('GET', songurl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
document.getElementById('songdiv').innerHTML = '';
song.src = (window.webkitURL ? webkitURL : URL).createObjectURL(this.response);
}
}
xhr.send();
This is more so to aide consistency, Chrome - developer tools is also suggesting the code to be re-factored.
Here is what I have started with (appreciate it's not much!), the issue I'm having is checking the status code and returning the response if the status code is 200.
$.ajax({
url: songurl,
method: 'GET'
);
You want to attach a function for success.
$.ajax({
url: songurl,
method: 'GET',
success: function(response){
//do stuff with response
}
})
ajax(), or the shorthand get(), will do all that for you. There's a success() function that's only called on a successfull, 200-status request:
$.get( songurl,
function(data) {
document.getElementById('songdiv').innerHTML = '';
song.src = (window.webkitURL ? webkitURL : URL).createObjectURL(data);
},
'blob'
);

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);
}
}

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

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, ;-)

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