converting javascript code to jquery - javascript

I have following code of javascript for search function. It works well when written inside html/php file it self, however, when I try to add this in my jQuery file, it doesn't work anymore.
<script type="text/javascript">
function findmatch(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
document.getElementById('search_result').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'php/search.php?search_text='+document.search.search_text.value , true);
xmlhttp.send();
}
</script>
I tried replacing 'getElementById' with $('#') and few some ways. But didn't work. I want to convert in jQuery so I can manage/animate 'search_result' div according to size of result returned. I don't know how will I do that. But, if you can guide me fir that extra, It would be great/

If i understand correctly, it's Ajax call:
<html>
<head>
<script src="jqueryLibrary.js"></script>
<script type="text/javascript">
function findmatch() {
$.ajax({
url: 'php/search.php?search_text=' + document.search.search_text.value,
type: 'get',
success: function(responseText){
$('#search_result').text(responseText);
}
})
}
</script>
</head>
</html>

try this one
function findmatch(){
$.ajax({
type : "GET",
url : 'php/search.php?search_text='+document.search.search_text.value,
cache : false,
async : false,
success : function(data) {
$('#search_result').text(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}

So this should work:
function findmatch() {
$.post('php/search.php?search_text='+document.search.search_text.value,function(response){
$('#search_result').html(response);
});
}
//EDIT: Made a mistake, semikolon after function findmatch() { }; <<
Greetings

Related

Convert AJAX implementation into jQuery AJAX implementation

I have an implementation of AJAX, How to exactly replicate this with jQuery AJAX
var request;
function sendInfo()
{
var id = document.form.bid.value;
var url="retrieve.jsp?bid="+id;
if(window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
request=new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
request.onreadystatechange=getInfo;
request.open("GET",url,true);
request.send();
} catch (e)
{
alert("Unable to connect to server");
}
}
I need to send a data bid onkeyup, display some data into the 'dispArea'
function getInfo()
{
if(request.readyState==4)
{
var val = request.responseText;
document.getElementById('dispArea').innerHTML=val;
}
}
Implement the same using jQuery AJAX
What I have tried ::
$(document).ready(function(){
$('#bookid').keyup(function(){
$.ajax({
url : 'retrieve.jsp',
data : {
bid : $('bookid').val()
},
success : function(responseText){
$('#dispArea').text(responseText);
}
});
});
});
bid is not available in the retrieve jsp file.
I didnt use # symbol in referring to the id "#bookid".
and to receive the text as html.
$(document).ready(function(){
$('#bookid').keyup(function(){
$.ajax({
url : 'retrieve.jsp',
type : 'POST',
async : 'false',
data : {
bid : $('#bookid').val()
},
success : function(responseText){
$('#dispArea').html(responseText);
}
});
});
});

Request JSON by AJAX in two ways

I don't know why but when I do request JSON in this way console log prints nothing:
var xhr = new XMLHttpRequest();
function elenco_studenti() {
var url = "/controller?action=student_list";
xhr.responseType = 'text';
xhr.open("GET", url, true);
xhr.onreadystatechange = print();
xhr.send(null);
}
function print(){
console.log(xhr.responseText);
}
Instead when I do request JSON in this way, it works:
$(document).ready(function(){
$.ajax({
url: '/controller?action=student_list',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
});
Can you help me? Thank you very much.
Assign the function reference instead of invoking the function
xhr.onreadystatechange = print();
to
xhr.onreadystatechange = print;
and wait for the actual response to be ready
function print() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
link to docs

Using AJAX GET request to pass the value of <option> tags to the URL

I want to pass options' values to the URL whenever the users select an option. For example these are the options:
Option 1
Option 2
Option 3
And this is the URL: http://example.com/products
When he selects an option among those 3, the URL changes into this: http://example.com/products?option=option1
I tried vanilla Javascript XMLHttpRequest for this, and this is my code:
function ajaxFormValidate(_method, _url, _callback, _fallback, _sendItem) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState < 4) {
return;
}
if(xmlHttp.status !== 200) {
_fallback(xmlHttp.response);
return;
}
if(xmlHttp.readyState === 4) {
_callback(xmlHttp.response);
}
};
xmlHttp.open(_method, _url, true);
xmlHttp.send(_sendItem);
} //Set a function for AJAX Request
//Actual performance
window.addEventListener('load', function(){
var _sort = document.getElementById('sort'), _filter = document.getElementById('filter'); //Get the elements
_sort.addEventListener('change', function(){ //If the value of the field changes
var _frmData = new FormData(); //Create a new FormData object
_frmData.append('sort', _sort.value); //Append the value to this object
ajaxFormValidate('GET', location.href, function(response){
//Perform the redirection here (without reloading the page)
}, function(response){
alert("Request cannot be sent!");
}, _frmData);
}, false);
});
Recently, I don't have any ideas for this. Any help is appreciated. Thanks
This is a good way of using GET in pure Javascript:
var ajax = new XMLHttpRequest();
ajax.open("GET", "example.com/products.php?option=YOUR OPTION VALUE GOES HERE", true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
console.log(data);
}
}
And this is the jQuery way (my preferred method):
var myOption = $('.your-elenet-calss-name').val();
var myurl = "http://example.com/products.php";
var dataString="&option="+myOption+"&check=";
$.ajax({
type: "GET",
url: myurl,
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function(){//Do some stuff here. Example: you can show a preloader///},
success: function(data){
if(data =='success'){
alert('done deal...');
}
}
});

How to Call a Web Service in a Cross-Browser way

I want to call a Web Service from Mozilla, Internet Explorer and Chrome.
Bellow is my LaboratoryService.js file which calls the Web Service:
function StringBuffer() {
this.__strings__ = new Array;
}
StringBuffer.prototype.append = function (str) {
this.__strings__.push(str);
};
StringBuffer.prototype.toString = function () {
return this.__strings__.join("");
};
function LaboratoryService() {
this.url = "http://25.48.190.93:8082/labratory?wsdl";
}
LaboratoryService.prototype.buildRequest = function () {
var oBuffer = new StringBuffer();
oBuffer.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" ");
oBuffer.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
oBuffer.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
oBuffer.append("<soap:Body>");
oBuffer.append("<getLabratory xmlns=\"http://nano.ito.ir/\" />");
oBuffer.append("</soap:Body>");
oBuffer.append("</soap:Envelope>");
return oBuffer.toString();
};
LaboratoryService.prototype.send = function () {
var oRequest = new XMLHttpRequest;
oRequest.open("post", this.url, false);
oRequest.setRequestHeader("Content-Type", "text/xml");
oRequest.setRequestHeader("SOAPAction", this.action);
oRequest.send(this.buildRequest());
if (oRequest.status == 200) {
return this.handleResponse(oRequest.responseText);
} else {
throw new Error("Request did not complete, code " + oRequest.status);
}
};
LaboratoryService.prototype.handleResponse = function (sResponse) {
var start = sResponse.indexOf('div') - 4;
var end = sResponse.lastIndexOf('div') + 7;
return sResponse.substring(start, end);
};
Bellow is my HTML code which uses LaboratoryService.js to show data:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Labratories</title>
<script language="JavaScript" src="LaboratoryService.js"></script>
<script language="JavaScript" src="jquery-1.8.0.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function () {
$("#btnGetLaboratories").click(function () {
var oService = new LaboratoryService();
var fResult = oService.send();
var newData = $('<div/>').html(fResult).text();
$("#divResult").html(newData);
});
});
</script>
</head>
<body>
<input id="btnGetLaboratories" type="button" value="Get Laboratories" />
<div id="divResult">
</div>
</body>
</html>
This approach works fine in Internet Explorer.
The problem is that this approach does not work in FireFox and Chrome.
I think that the oRequest.send(this.buildRequest()); does not work in FireFox and Chrome.
Edited Web Service Call Using JQuery
I changed LaboratoryService.prototype.send to use JQuery to call Web Service as bellow:
LaboratoryService.prototype.send = function () {
$.ajax({
type: "POST",
url: this.URL,
contentType: "text/xml",
headers: { "SOAPAction": this.action },
success: function (msg) {
return this.handleResponse(msg);
},
error: function (e) {
alert('error');
}
});
};
But it alerts error. How do I call Web Service using JQuery?
Again Edited Code
I changed my JQuery AJAX call as bellow. It works fine in Internet Explorer but returns error in Chrome and Firefox.
LaboratoryService.prototype.send = function () {
$.ajax({
type: "POST",
url: this.URL,
contentType: "text/xml; charset=\"utf-8\"",
dataType: "xml",
data: this.buildRequest(),
processData: false,
success: function processSuccess(data, status, req) {
if (status == "success") {
var sResponse = req.responseText;
var start = sResponse.indexOf('div') - 4;
var end = sResponse.lastIndexOf('div') + 7;
var newData = $('<div/>').html(sResponse.substring(start, end)).text();
$("#divResult").html(newData);
}
},
error: function () {
alert('error');
}
});
};
Just change :
LaboratoryService.prototype.send = function () {
var oRequest = new XMLHttpRequest;
oRequest.open("post", this.url, true);
oRequest.setRequestHeader('User-Agent','XMLHTTP/1.0');
oRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oRequest.setRequestHeader("SOAPAction", this.action);
oRequest.send(this.buildRequest());
if (oRequest.status == 200) {
return this.handleResponse(oRequest.responseText);
} else {
throw new Error("Request did not complete, code " + oRequest.status);
}
};
Please, refer this link.

Javascript - XMLHttpRequest failing in Internet Explorer

* SOLVED * Answer is in separate post below
This code runs fine in FireFox but it will not run in Internet Explorer 8. It gives me the error of "access denied. Is there something I am missing?
function loadXMLDoc(dname){
if (window.XMLHttpRequest){
var xhttp=new XMLHttpRequest();
}
else{
var xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname,false);
xhttp.send();
return xhttp.responseXML;
}
var xmlDoc=loadXMLDoc("notSchema.xml");
var x=xmlDoc.getElementsByTagName('ROOT_NODE_ID');
It specifically doesn't like the .open() and the .send()
Edited...
var x;
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(http){
xmlDoc = http;
alert(http);
x=http.getElementsByTagName("ROOT_NODE_ID");
},
error: function(html){
alert('failure: ' + html);
}
});
}
loadXMLDoc("notSchema.xml");
for (var i=0;i<x.length;i++)
{
if(x[i].childNodes[0] == undefined) {
treeArray[count]="null";
count++;
}else{
//return ROOT_NODE_ID
treeArray[count]=x[i].childNodes[0].nodeValue;
count++;
}
}
Edited the Code once again. What I'm trying to do is load the XML, parse for the tag "ROOT_NODE_ID" and then get that value and store it into an array
When I run that code in firefox, it returns 51, which is the number of ROOT_NODE_ID tags and fills the tree that I am making.
When I run the same exact code in IE8, it does not even alert.
I'm Stumped.
I figured it out. Like I said before, if you run the code above in Firefox, it returns the 'object' and if you run it in IE8, it returns the contents of the object. I solved this problem by loading the content of the object again in IE8, thus turning the content of the object back into an object that will be ready to be parsed. If that makes any sense.
Just to clarify to people that are just visiting this thread. When I called 'alert(http);' in firefox, it would return '[object XMLDocument]', but in IE8 it would return the actual contents of '[object XMLDocument]'.
var treeArray=new Array();
var count = 0;
var x;
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(http){
var xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
//Loading the contents of the object 'http' a second time, which turns it into an object again.
xmlDocument.loadXML(http);
x = xmlDocument.getElementsByTagName("ROOT_NODE_ID");
alert(x.length);
},
error: function(html){
alert('failure: ' + html);
}
});
}
loadXMLDoc("notSchema.xml");
for (var i=0;i<x.length;i++)
{
if(x[i].childNodes[0] == undefined) {
treeArray[count]="null";
count++;
}else{
//return ROOT_NODE_ID
treeArray[count]=x[i].childNodes[0].nodeValue;
count++;
}
}
Zack,
You can use jquery to do the ajax call - jquery will do everything properly behind the curtains.
In your case here:
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(html){
var x=xmlDoc.getElementsByTagName('ROOT_NODE_ID');
},
error: function(html){
alert('failure: ' + html);
}
});
}

Categories

Resources