Jquery Ajax function is not working while calling the Servlet - javascript

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

Related

Show java servlet process in web

I'm developing a small web app that queries a few databases to do data predictions, then returns an object with the predicted result.
That's somewhat working already, but data processing in the servlet can go over half an hour depending on query filters, I usually set up a javascript "loading" div on submit, but its a bit sad.
So the question is, can I somehow send messages to the web client while the servlet is processing so it doesn't look like the page died? (improving the loading div with actual info on how the process is going)
Just add the preloader before sending the request and remove that preloader on success.
var isBool = false;
function communicateWithServer(){
$("#preloader").show();
var isBool = false;
$.ajax({
url : 'url',
data : {
},
type : 'POST',
dataType : 'text',
success : function(response) {
isBool=true;
$("#preloader").hide();
//Show success
},
error : function(request, textStatus, errorThrown) {
$("#preloader").hide();
//show error
}
});
secondComm();
}
function secondComm(){
$.ajax({
url : 'url2',//send the response from your second servlet to this
data : {
},
type : 'POST',
dataType : 'text',
success : function(response) {
$("#preloader").text(response.value);
if(!isBool){secondComm();}
//
},
error : function(request, textStatus, errorThrown) {
if(!isBool){secondComm();}
//show error
}
});
}
Please do not get confused with the jquery you can do this without jquery too.
function communicateWithServer() {
document.getElementById("preloader").style.display = 'block';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//show success
} else {
//show error
}
document.getElementById("preloader").style.display = 'none';
};
xhttp.open("GET", url, true);
xhttp.send();
}

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

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

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!

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