JS to jQuery to the fullest - javascript

I have this:
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
} else {
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var nocache = 0;
function insert() {
document.getElementById('insert_response').innerHTML = "To Sek .. "
var bID= encodeURI(document.getElementById('bID').value);
var kommentar= encodeURI(document.getElementById('kommentar').value);
nocache = Math.random();
http.open('get', 'insert.php?bID='+bID+'&kommentar=' +kommentar+'&nocache = '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
function insertReply() {
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('insert_response').innerHTML = response;
if ($("#box[value=1]").length > 0) { window.parent.showMessage("Video Is OK"); }
}
}
And i want to "shorten" the code, and make it use jQuery to the fullest. eg, i have heard of serialize(); instead of using http.open etc.., but how should i use it in this case?
And do i really need all that in createobject() to make the http?

Untested, but I'm pretty sure this is what you need:
function onInsertComplete(data,textstatus){
$("#insert_response").html(data);
}
function doInsert(){
$("#insert_response").html("To Sek...");
var nocache = '0';
var data = { bID : $("#bID").val(), kommentar: $("#kommentar").val(), nocache: nocache };
$.get('insert.php', data, onInsertComplete);
if ($("#box[value=1]").length > 0) {
window.parent.showMessage("Video Is OK");
}
}

Most of this can be cleaned up with a call to the get method in jQuery.
First, it will abstract away the browser-specific details for you, so you don't have to check how get XMLHttpRequest.
You can then use jQuery to get elements through selectors. To select any element by id, you would use the following syntax:
$("#<id>")
The hashtag indicates that you want to select the elements with the id specified. From there you can use some of the general attribute functions to get the values inside of specific elements.
Finally, you can use Javascript's ability to generate closures to create and pass one as the callback to the get function, which is executed when the call completes. You would then use the same selectors general attribute functions to change the values on the client side when the call completes.

Something on this line?
http://api.jquery.com/load/
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});

Related

Check My Code. Is it a correct way to append?

function saveToDataBase(save_id,textarea_id,question_no,assg_name,testinput,testoutput)
{
document.getElementById(save_id).addEventListener('click',function(){
//alert("Hello");
var question=document.getElementById(textarea_id).value;
var question_id=assignment_name+question_no;
var request;
var url="saveQuesToDataBase.jsp?question="+question+"&question_id="+question_id+"&assg_name="+assg_name;
for(var i=0;i<testinput.length;i++)
{
var v=document.getElementById(testinput[i]).value;
url=url+"&testinput"+i+"="+v;
}
for(var i=0;i<testoutput.length;i++)
{
var v=document.getElementById(testoutput[i]).value;
url=url+"&testoutput"+i+"="+v;
}
var len=testinput.length;
url=url+"&size_of_arr="+len;
if(window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
request=new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
request.onreadystatechange=function()
{
if(request.readyState==4 && request.status == 200)
{
alert(request.responseText);
}
};
request.open("GET",url,true);
request.send();
}
catch(e){alert("Unable to connect to server");
}
})
}
The function is called on click, but not redirected to saveQuesToDataBase.jsp . Please see if I could append things to url this way ? Tell me the better way.
testinput and testoutput are the two arrays of id's of textareas.
I used loop to retrieve id and to get the value.
For your code design,I have two suggestions:
a. First I would recommend you using jQuery ajax instead of original Ajax,it will hide the implement of different browsers.With it you can make it like below:
$.ajax({
url:your_request_url,
type:"post",//or get
data:your data,
success:function(data){},
error:function(){}
});
b. since Http Get method has parameter length limit,details can be found at maximum length of HTTP GET request?. You need to use POST instead of GET,while using POST,when can using data to pass more parameters to ajax:
var params ={};//define a parameter object
for(var i=0;i<testoutput.length;i++)
{
var v=document.getElementById(testoutput[i]).value;
params["testoutput"+i]=v;
}
$.ajax({
url:your_request_url,
type:"post",//or get
data:params,//passing the parameters.
success:function(data){},
error:function(){}
});

Accessing JSON data from a url

I'm fairly new to web programming, so I'm sorry in advance if this is a dumb question. I've looked around and wasn't able to find anything very concrete on this so I figured I'd ask here.
I'm trying to make a script which reads a JSON file and returns some data. More specifically here's a link.
I want to search through and find where an world_id is equal to xxxx, and return the match_id. In another thread it one of the solutions was something similar to
var obj = JSON.parse(//JSON info here)
var a = obj.world_id
Can anyone point me in the right direction as to achieve this?
There are many reasons to add jQuery to a project. BUT. Please don't add jQuery just to get some json data. Javascript is perfectly capable of handling this one on its own, thank you:
// simple cross-browser ajax helper
var ajaxGet = function (url, callback) {
var callback = (typeof callback == 'function' ? callback : false), xhr = null;
try {
xhr = new XMLHttpRequest();
} catch (e) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (!xhr)
return null;
xhr.open("GET", url,true);
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && callback) {
callback(xhr.responseText)
}
}
xhr.send(null);
return xhr;
}
// example usage, grab the json data, loop it and log red_world_id to console
ajaxGet(
'https://api.guildwars2.com/v1/wvw/matches.json',
function (response) {
response = JSON.parse(response);
if (!response)
return;
var i, list = response.wvw_matches;
for (i in list) {
console.log(list[i].red_world_id); // outputs an id
}
});
Try it here: http://jsfiddle.net/7WrmL/
So basically, for your specific usage, instead of simply logging the ID to console, you can check each object's id properties against the desired matching id and, for example, return i for the index of the match (not sure I understand exactly what you're after there).
And keep in mind: use jQuery when you need it, not for everything and anything.
Documentation
XMLHttpRequest on MDN - https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
XMLHttpRequest ON MSDN (IE) - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
JSON on MDN - https://developer.mozilla.org/en-US/docs/JSON
for... on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
An easy way of getting the JSON data is by using jQuery, like this:
<div id="reply"></div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$.getJSON(
"https://api.guildwars2.com/v1/wvw/matches.json",
function (data) {
$("#reply").html(JSON.stringify(data));
// or work with the data here, already in object format
});
});
</script>
See here: http://jsfiddle.net/mynetx/LwNKC/
Look at my code below. I used jquery to get content
var result;
$.get(
"https://api.guildwars2.com/v1/wvw/matches.json",
{},
function(data) {
var result = data;
}
);
var arr = JSON.parse(result);
var length = arr.length;
for (var i = 0; i < length; i++)
{
if(arr[i].red_world_id == 'xxx')
{
console.log('Got it');
}
if(arr[i].blue_world_id== 'xxx')
{
console.log('Got it');
}
if(arr[i].green_world_id== 'xxx')
{
console.log('Got it');
}
}
Look out for slip of the pen :).

Help me properly make an AJAX call

I have a JavaScript function that is being called. I need to have it call a PHP function and return a true/false.
The script with the function is in the file /db/cancel_hike.php
My current JS looks like this:
function uncancelHike( hike_id )
{
//var url = "/db/cancel_hike.php;
var success = null;
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.open("GET", url , true);
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
var xmlDoc = request.responseXML;
// obtain the array of markers and loop through it
markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++)
{
// obtain the attribues of each marker
success = markers[i].getAttribute("success");
if ( success == "true" )
{
document.getElementById("success").style.display = 'block';
document.getElementById("warning").style.display = 'none';
document.getElementById("error").style.display = 'error';
}
if ( success == "false" )
{
document.getElementById("success").style.display = 'none';
document.getElementById("warning").style.display = 'none';
document.getElementById("error").style.display = 'block';
}
}
}
}
request.send(null);
return false;
}
What I am having trouble with is:
How to call an actual function in the PHP script?
Do I absolutely need to have some XML returned? Or is there a way to just get back the returned value?
I am using YUI JS library. Do I need to make some calls to it, or is it not necessary in this case?
How to call an actual function in the PHP script?
You can't. You request URIs.
Write a PHP script that calls the function you want and place it at the URI you call.
(You can use query strings and the like as the input to an if statement that you use to conditionally call different functions)
Do I absolutely need to have some XML returned? Or is there a way to just get back the returned value?
You can return any kind of data you like.
I am using YUI JS library. Do I need to make some calls to it, or is it not necessary in this case?
It's a library. You never need to make calls to it. It often simplifies the code you have to write.
How to call an actual function in the PHP script?
Do I absolutely need to have some XML returned? Or is there a way to just get back the returned value?
Well, you don't call the actual function. What you want to do is pass variables using GET, that is, by appending them to the URL like file_name.php?var1=this&var2=that to pass var1 of "this" and var2 equaling "that." You retrieve them in the PHP file with $_GET['this'] and $_GET['that']. Whatever PHP outputs to the page via echo, print_r, etc. is then sent back in a request object as part of its responseText property.
You just set url in request.open to a URL on your site. For example, in your .js file:
request.open("GET", "answer_me.php?hike_id=" + hike_id, true);
And in your .php file:
<?php
$hike_id = $_GET['hike_id'];
if ($hike_id < 5) {
echo "true"; // echo true would return "1", BTW
} else {
echo "false"; // echo false would return nothing
}
Note that that will just return a string value to request.responseText of false, thus you could do this:
var result = request.responseText;
if (result === "true") {
...
document.getElementById("success").style.display = "block";
...
} else {
...
document.getElementById("success").style.display = "none";
...
}
You do not need it to be XML, especially as it looks like you're not really using the loop (the same three DOM elements are being assigned values each time).
And honestly, for AJAX I'd recommend using a framework like jQuery (or YUI, although I don't find its AJAX stuff as intuitive). Your entire code would look like this:
var $success = $("#success");
var $error = $("#error");
function cancelHikeCallback(data) {
var is_success = (data === "true");
$success.toggle(is_success);
$error.toggle(!is_success);
}
function cancelHike(hikeIdToSend) {
$.get("/db/cancel_hike.php", {hike_id: hikeIdToSend}, cancelHikeCallback);
}
IMO things like jQuery's $.ajax ($.get is a specialized form of $.ajax) make this stuff much easier to read and debug.
jsFiddle Example

Why does this function not return JSON string?

function addphoto()
{
var ajaxRequest = initAjax();
if (ajaxRequest == false)
{
return false;
}
// Return Ajax result when the state changes later
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
alert(ajaxRequest.responseText);
return ajaxRequest.responseText;
}
}
// Capture form elements
var values = {
"category" : encodeURIComponent(document.addphoto.category.options[document.addphoto.category.selectedIndex].value),
"photo_title" : encodeURIComponent(document.addphoto.photo_title.value),
"photo_descrip" : encodeURIComponent(document.addphoto.photo_descrip.value)
}
var queryString = '?', i = 0;
for (var key in values)
{
if (i != 0)
{
queryString += '&'
}
queryString += key + '=' + values[key];
i++;
}
// Execute Ajax
ajaxRequest.open("POST", "ajaxcheckform.php" + queryString, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", queryString.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(null);
}
function ajaxCheckform(formname)
{
var response = addphoto(); // <--This is undefined and not sure why
var responseObj = JSON.parse(response);
if (responseObj.success == 1)
{
// Successful form!
alert(responseObj.success_text);
}
else
{
// Error!
alert(responseObj.error);
}
}
I'm sure I must be making some basic error somewhere, but I'm having trouble locating it. In this script, ajaxCheckform() is a function that executes one of several similar functions. Above, I included addphoto(), which is one of several functions I'll need that look like this.
On a side note, I'd love to know I can call upon a function dynamically. The addphoto() function will be only one such function being called up at that moment and I'm trying to find a way to pass formname as the function I need. I've searched Stackoverflow and Google. I've found nothing that works.
Note, I'm aware of jQuery, but I'm not there yet. I need this function to work first.
It is not addphoto() thats undefined but response is undefined. ajaxRequest is asynchronous and the addphoto() function will return before the request completes.
try this
function addphoto() {...
// Return Ajax result when the state changes later
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
alert(ajaxRequest.responseText);
var responseObj = JSON.parse(ajaxRequest.responseText);
if (responseObj.success == 1) {
// Successful form!
alert(responseObj.success_text);
}
else {
// Error!
alert(responseObj.error);
}
}
}
....
}
function ajaxCheckform(formname) {
addphoto();
}
That's because response is set to the return of addphoto(), which is nothing. What you want to do is have ajaxCheckForm get called when the AJAX call is completed:
// Return Ajax result when the state changes later
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
ajaxCheckform(ajaxRequest.responseText);
}
}
Then your ajaxCheckform will work with that data:
function ajaxCheckform(responseText)
{
var responseObj = JSON.parse(responseText);
if (responseObj.success == 1)
{
// Successful form!
alert(responseObj.success_text);
}
else
{
// Error!
alert(responseObj.error);
}
}
You can't return from an event handler (which onreadystatechange is).
You have to do the work inside that event handler.
addphoto() does not return anything (or rather, returns inconsistently) ... the onreadystatechange event's handler is returning the value, but there is no caller that will receive that json string.
I'd highly suggest that you abstract these details away with something like jquery ... just follow the docs for suggested usage and this code will be much simpler
You're sending a GET style parameter list to a POST method.
You need to send that string in the body of your HTTP request.
var response = addphoto(); // <--This is undefined and not sure why
The addphoto() function never has a return statement in it, so it returns undefined. And the ajaxRequest is asynchrous and wont return immediately.

Lose response from the server in AJAX

I have this code that make 3 requests to a server, the code works fine with the request but when I receive the response the code fails, take avoid the first response and give me the third.
phone.open("POST", '/', true);
phone.setRequestHeader("Content-type", elmnt.getAttribute('ctype'));
phone.send(reqStr);
This is the code that catch the response.
phone = new ConstructorXMLHttpRequest();
onreadystatechange = function(){
if(phone.readyState == 4){
if(phone.status == 200){
var val = phone.responseText;
alert(phone.responseText)
dataInsert(val);
break;
}else{
alert("Problemas status:"+phone.status+" state:"+phone.readyState);
break;
}
}
};
#Hemlock here is the code of the constructor:
function ConstructorXMLHttpRequest()
{
if(window.XMLHttpRequest) /*XMLHttpRequest(Browsers Mozilla, Safari and Opera). */
{
return new XMLHttpRequest();
}
else if(window.ActiveXObject) /*IE*/
{
/*There a several difference between versions of IE, so
* if the kids of MS release a new please put in this Array.*/
var versionesObj = new Array(
'Msxml2.XMLHTTP.5.0',
'Msxml2.XMLHTTP.4.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP');
for (var i = 0; i < versionesObj.length; i++)
{
try
{
return new ActiveXObject(versionesObj[i]);
}
catch (errorControlado)
{
}
}
}
throw new Error("Couldn't make a XMLHttpRequest");
}
The reason people think this is funny is because your case statement is A) useless because you don't actually want to take different actions depending on the state of the object, you actually only want to act on its status under one condition and B) your case is used in conjunction with an if statement, which is redundant - not to mention syntactically erroneous.
I think you're trying to do
if(phone.readyState == 4){
var val = phone.responseText;
alert(val);
dataInsert(val);
}else{
alert("Problemas status:"+phone.status+" state:"+phone.readyState);
}
I also think you should look into using a 3rd party library like jQuery to do your ajax.
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: 'getData.html',
success: function(val) {
alert(val);
dataInsert(val);
}
});

Categories