Fetch Data by variable with Javascript - javascript

How would I go about fetching a piece of text that has been outputted via a piece of javascript code and assigning it to the end of the link in the below script:
$(document).ready(function(){
$(document).bind('deviceready', function(){
var name = $('#name');
var logo = $('#logo');
var attacking = $('#attacking');
var midfield = $('#midfield');
var defence = $('#defence');
var rating = $('#rating');
var url = 'http://79.170.44.147/oftheday.co/fifa/team.php?name=(Piece of text needs to be inputted at the end here, so that the correct data can be fetched)';
$.ajax({
url: url,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var name1 = ''+item.name+'';
name.append(name1);
});
$.each(data, function(i,item){
var logo2 = '<img src="'+item.logo+'" />';
logo.append(logo2);
});
$.each(data, function(i,item){
var attacking2 = ''+item.attacking+'';
attacking.append(attacking2);
});
$.each(data, function(i,item){
var midfield2 = ''+item.midfield+'';
midfield.append(midfield2);
});
$.each(data, function(i,item){
var defence2 = ''+item.defence+'';
defence.append(defence2);
});
$.each(data, function(i,item){
var rating2 = ''+item.rating+'';
rating.append(rating2);
});
},
error: function(){
name.text('There was an error loading the name.');
logo.text('There was an error loading the logo.');
attacking.text('There was an error loading the attacking data.');
midfield.text('There was an error loading the midfield data.');
defence.text('There was an error loading the defence data.');
rating.text('There was an error loading the rating data.');
}
});
});
});
I understand how to do this in PHP it would be something like inserting "'.$name.'" to the end of the link where $name is equal to the outputted content. I don't quite understand how to this here though, the script used to output the previous text is in a separate javascript file too.
Any help would be greatly appreciated!

var url = '.../oftheday.co/fifa/team.php?name='+encodeURIComponent(someVar);
where does the variable part come from? A dropdown?
If so then
var url = '.../oftheday.co/fifa/team.php?name='+encodeURIComponent($("#someId").val())
UPDATE:
<div onload="onBodyLoad()" id="international"></div>
would mean
var url = '.../oftheday.co/fifa/team.php?name='+encodeURIComponent($("#international").text())
But what is
onload="onBodyLoad()"
supposed to do? - I do not believe there is such an attribute on a div

Rather than constructing the query parameters yourself with string concatenations you would be better off using the data parameter of jQuery.ajax(). See the docs at http://api.jquery.com/jQuery.ajax/.
Your ajax call would then look something like this:
// Notice that there is no name= in the url
var url = 'http://79.170.44.147/oftheday.co/fifa/team.php';
$.ajax({
url: url,
data: {
name: $("#international").text() // this will put the name=... in the query
},
dataType: 'jsonp',

Related

ParsIng BIng Image Search using JQuery or Javascript Errors

I can successfully parse Bing Search JSON API correctly. Using Version 7 of both Web Search and Images. For some reason JSONLint is correct for images but but can not parse a damn thing. My JQuery code is below Thanks in advance!
////JQUERY CODE
$(document).on("click", "#i-search", function () {
//API URL
var uri = 'bing-img.php';
//SEARCH PARAMETERS
var e = escape($('#book').val());
var pg = escape($('#pg').val());;
var limit = escape($('#limit').val());;
var market = "en-us";
$.ajax({
url: uri,
method: "GET",
data: { q:e, s:limit, p:pg, m:market },
success: function(data) {
var obj = JSON.parse(data)
//SEARCH RESULTS
var ocean = obj.value; //client prop is an array
for(var i = 0; i < ocean.length; i++){
//alert(ocean[i].thumbnail);
var ocean_format = '<p>' + ocean[i].name +'</p>';
$("#bookout").append(ocean_format);
}//END SEARCH RESULTS
$("#moreout").html(more);
},
error: function() {
// console.log(data);
}
});
}); //END IMAGE SEARCH SUBMIT
/////// VALID BING IMAGE JSON ////////////
https://0ct0p.us/bing-img.php?q=mazda&s=2&p=0&m=en-us
/////CROSS ORGIN ERROR ON FIREFOX
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowOrigin

jQuery Ajax GET request not working correctly

I'm trying to call an AJAX query and have had lots of trouble recently.
Im trying to call a api that I have custom made myself, it displays this when the url api/reverse/test - tset (is just uses a php function to reverse the text given in the slug3.
That function works fine, just wanted to give some back on what gets requested.
reverse.php - HTML File
<textarea id="input"></textarea>
<div id="output">
</div>
index.js - All of my jQuery and AJAX
$(document).ready(function(){
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function(){
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; },
error: alert('fail')
}) // End of AJAX
$output.html = output;
});
});
api.php - PHP file being called
<?php
$area = $_GET['area'];
if ($area == 'reverse') {
if (isset($_GET['text']) ) $text = $_GET['text'];
else $text = 'Hello';
echo strrev($text);
}
It's then supposed to take the output variable and display that in a div but that's not the main thing that matters.
error removed - was trying to see if it fixed it
There are several issue I found:
Jquery:
var text = $('#input').val(); // if you are getting value from any inputbox - get value using .val() function
var url = 'http://localhost/test.php?data='+text; // pass data like this ?data='+text
// AJAX START
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
async: true,
success: function(data) { var output = data; alert(output)},
error: function(data) { alert('fail') }
});
In php you ca get data like this:
echo $_GET['data'];
exit;
Try this. Scope of variable output is within the success call and you are using it outside the ajax call.
$(document).ready(function()
{
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function()
{
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; $output.html = output;},
error: alert('fail')
}) // End of AJAX
});
});

Update data from a new JSON after delay of 5 seconds and again from a new JSon after another 5 delays sec

my updated full script:
$(document).ready(function() {
$.getJSON('table.json',function(data){
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i=0, size=data.length; i<size;i++) {
html += '<tr class="tablecontent"><td>'+ data[i].name+ '</td><td>'+ data[i].code+ '</td><td>'
+ data[i].value+ '</td><td>'
+data[i].bid+'</td><td>'+data[i].offer+'</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll,5000);
});
});
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "dummy.json",
success: function(data){
//HANDLE DATA
setTimeout(poll,5000);
}
});
},5000);
Please help me in this. i have 3 JSONs. 1st Json will load initially. That is done.
2nd json needs to be parsed (which has 2 field changes) and show the initial json + changed fields and then again from 3rd JSON.
I have written below script:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "dummy.json",
success: function(data){
//HANDLE DATA
JSON.parse(data);
}
});
},5000)
dummy.json is my second changed JSON. Is this the correct way?how should i call this function function in my $(document).ready?
Set it as a regular function and then call it from itself within the success handler so then you are never getting ahead of yourself. Then you can also just call it once from your $(document).ready.
var poll = function(){
$.ajax({
type:"GET",
url: "dummy.json",
success: function(data){
//HANDLE DATA
setTimeout(poll,5000);
}
});
}

Return a set from ajax to JavaScript

I have an ajax call which will return a set<E>. I need to process this set from the JavaScript function from which I call this ajax.
<script type="text/javascript">
function mySr(id){
$.ajax({
type: 'POST',
url: '../controller/action',
data: 'id=' + id,
success: function(data) {
var length= data.length
var size = data.size
alert(data[0]+'----'+length+'--'+size+'----'+data)
},
error: function () {
alert('error')
}
});
</script>
This is the way i used,
The alert will display like this
["37",
"40","80","90"]----22--undefined----[
I understood the data is clearly reached in the script but i don't know how to iterate through it.
How to iterate here?
How to get the length?
How to get each elements?
You need to parse the data. Try putting data = $.parseJSON(data); after the line success: function(data) {
See http://api.jquery.com/jQuery.parseJSON/ for more details.

jQuery nested XML question

I am using jQuery to insert an HTML shell into a page, and populate the shell with XML. Here is the XML in question
<minorPropCategory title="Test Title 1">
<minorProp>FLV</minorProp>
<minorProp>BLV</minorProp>
<minorProp>RLV</minorProp>
</minorPropCategory>
<minorPropCategory title="Test Title 2">
<minorProp>LAS</minorProp>
<minorProp>ILV</minorProp>
<minorProp>BIL</minorProp>
</minorPropCategory>
So first, what I do is import an HTML snippet for each minorPropCategory, and add the title using this code
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
}
);
$("#minorModuleContainer").append(minorDiv);
Then, what I want to do is add another HTML snippet, and then populate it. This is where I am having a problem. I can try it like this
//Create the actual minor modules
$(this).find('minorProp').each(function(){
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
});
But it never shows up on the page, because I don't think it is firing at the proper time. Alternatively, I tried moving the creation of the minor modules into the .load function of it's parent, but I run into another problem. The code looks like this.
//MINOR MODULE CODE
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
$(this).find('minorProp').each(function(){
alert("minorPropFired");
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
alert("test");
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
The problem is, that the line with "$(this).find('minorProp').each(function(){" doesn't fire because "this" has changed. I guess, by now, my noob is showing. I feel like I am doing this in the wrong way. Any help would be appreciated. Thanks.
Posted below is the full .js file of what I am trying to do.
// JavaScript Document<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
//gets the code for the ad from the URL. Using URL jQuery add-on to make this super-easy
var adCode = $.url.param("adCode");
if (adCode != null){
//gets the ad code's XML file
$.ajax({
type: "GET", url: adCode+".xml", dataType: "xml",
success: function(xml) {
//Set the header image
$("#headerImg").attr(
{
src:$(xml).find('headerImage').text(),
alt:$(xml).find('headerImageAlt').text()
}
);
//set the header text
$("#headerText").html($(xml).find('adText').text());
//set the top image
$("#topImg").attr(
{
src:$(xml).find('topImage').text(),
alt:$(xml).find('topImageAlt').text()
}
);
//MAJOR MODULE CODE - This code reads all of the major modules, then adds a majorModule div, and populates it
//Gets all majorProps from ad XML
$(xml).find('majorProp').each(function(){
var propCode=$(this).text();
var majorModuleCode = "majorModule.html";
//names the div with a unique ID
div = $("<div id='"+propCode+"majorModule' class='majorModule'>");
//Sets loading message in case it takes longer than usual to load
div.html("Loading......");
//After majorModule.html code loads, starts populating module
div.load(majorModuleCode,"t",
function(){
//Get the XML for the prop, which contains prop specific stuff
$.ajax({
type: "GET",
url: propCode+".xml",
dataType: "xml",
success: function(xml2) {
$("#"+propCode+"majorModule").find(".propImg").attr(
{
src:$(xml2).find('smallImage').text(),
alt:$(xml2).find('smallImageAlt').text()
}
);
$("#"+propCode+"majorModule").find(".propLogoImg").attr(
{
src:$(xml2).find('smallLogo').text(),
alt:$(xml2).find('name').text()
}
);
$("#"+propCode+"majorModule").find(".viewCalendarLinkA").attr(
{
href:"https://www.harrahs.com/AvailabilityCalendar.do?propCode="+propCode+"&showHotDeal=Y"
}
);
$("#"+propCode+"majorModule").find(".learnMoreLinkA").attr(
{
href:$(xml2).find('homeLink').text()
}
);
$("#"+propCode+"majorModule").find(".propText").html(
$(xml2).find('bodyText').text()
);
}
});
//Get the lowest rate for the prop
$.ajax({
type: "GET",
url: "lowest_rate\\"+propCode+".xml",
dataType: "xml",
success: function(xml3) {
$("#"+propCode+"majorModule").find(".roomRate").html(
"$"+($(xml3).find('roomtype').filter(
function (index) {
return $(this).attr("lowest") == "Y";
}).text()).slice(0, -3)
)
}
});
}
);
$("#mainModuleContainer").append(div);
});
//MINOR MODULE CODE
$(xml).find('minorPropCategory').each(function(){
var minorHeader=$(this).attr("title");
var minorId=$(this).attr("title").replace(/ /g,'');
var minorModuleContainerCode = "minorModuleContainer.html";
//names the div with a unique ID
minorDiv = $("<div id='"+minorId+"minorModuleContainer' class='minorModuleGroupContainer'>");
//Sets loading message in case it takes longer than usual to load
minorDiv.html("Loading......");
//After minorModuleContainerCode.html code loads, starts populating module
minorDiv.load(minorModuleContainerCode,"t",
function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").html(minorHeader);
}
);
$("#minorModuleContainer").append(minorDiv);
//Create the actual minor modules
$(this).find('minorProp').each(function(){
var minorPropCode = $(this).text();
var minorModuleCode = "minorModule.html";
minorModuleDiv = $("<div id='"+minorPropCode+"minorModule' class='minorModule'>");
minorModuleDiv.html("Loading......");
minorModuleDiv.load(minorModuleCode,"b",
function(){
$.ajax({
type: "GET", url: minorPropCode+".xml", dataType: "xml",
success: function(xml3) {
$("#"+minorPropCode+"minorModule").find(".minorPropLogo").attr(
{
src:$(xml3).find('smallImage').text(),
alt:$(xml3).find('smallImageAlt').text()
}
);
}
});
});
$("#"+minorId+"minorModuleContainer").append(minorModuleDiv);
});
});
}
});
}
});
To fix this problem just before running minorDiv.load do something like this
var elem = $(this);
minorDiv.load(minorModuleContainerCode,"t", function(){
$("#"+minorId+"minorModuleContainer").find(".minorModuleHeader").
html(minorHeader);
// replace $(this) with elem here
elem.find('minorProp').each(function(){
...
}
...
}
This will keep the reference to correct object in your nested functions.

Categories