ParsIng BIng Image Search using JQuery or Javascript Errors - javascript

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

Related

Sending form data with extra parameters through Ajax?

I am trying to send a post request with the form data as well as some other parameters to my Codeigniter controller. This is the code I am using.
function onSignIn(googleUser) {
console.log('onto the function');
var profile = googleUser.getBasicProfile();
var google_name = profile.getName();
var google_image = profile.getImageUrl();
var google_email = profile.getEmail();
console.log('got the details');
console.log('submitting');
var title = ('#title').val();
var message = ('#message').val();
$.ajax({
type: "POST",
url: 'http://localhost/review/submit',
data: {
title,
message,
'google_name': google_name,
'google_email': google_email,
'google_image': google_image,
},
success: function () {
alert('fuck');
}
});
}
I keep getting $ is not defined and I have no idea why that is, cause when I remove $ it gives me #title.val() is not a function.
Make sure you are giving jquery reference with correct path to your code
Include bellow CDN link in your head section of code
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js

JQuery does not fetch and parse json from url

I have been developing an app to connect with an API I recently built for testing (It is working fine) but I deem to be getting an unknown error with my code. I am a newbie trying out jQuery. This is my code:
$(document).ready(function(){
$.ajax({
url: 'api.lynmerc-enterprise.com/requests',
async: false,
type: 'GET',
//dataType: 'json',
success: function(data){
console.log(data);
var data2 = jQuery.parseJSON(data);
console.log(data2);
//assign parsed JSON to variables
var apiStatus = data2.status;
var apiMessage= data2.message;
var apiData = data2.data;
var data3 = $.parseJSON(apiData);
//Here we get Requester info and material JSON
console.log(data3);
var materials = data3.material;
var data4 = $.parseJSON(materials);
console.log(data4);
//loop through the data and assign needed info to table
$.each(data3, function(i,row){
var dateRequested = data3.date;
var projectCode = data3.p_code;
var requestNumber = data3.rq_no;
var materialName = data4.name;
var purpose = data4.purpose;
var quantity = data4.quantity;
var cost = data4.cost;
var total = data4.total;
$("table.table").append("<tr><td>"+dateRequested+"</td><td>"+projectCode+"</td><td>"+requestNumber+"</td><td>"+materialName+"</td><td>"+purpose+"</td><td>"+quantity+"</td><td>"+cost+"</td><td>"+total+"</td></tr>");
});
},
//error: function(){console.log('Error Encountered')},
beforeSend: setHeader()
});
});
//set required headers
function setHeader(xhr){
xhr.setRequestHeader('Api-Key','ZHhjZmIyMHdnazVtdWw=');
xhr.setRequestHeader('Content-Type','application/json')
}
The code is supposed to connect to the API with the Api-Key as a header then fetch Json of format
{
'status':success,
'data':'[{
"p_code":,"requester_id":,
"date":,"rq_no":,
"id":, "materials":[{
"name":,
"purpose":,
"cost":,
"quantity":,
"status":,
"rq_no":,"id":,
"total":},
...
]}
.....
]'
... The data is to be assigned to variables then appended to the main HTML table
I finally had it working perfectly:
<script type="text/javascript">
function fetchJson(){
$(document).ready(function(){
$.ajax({
url: 'http://api.lynmerc-enterprise.com/requests',
headers: {
'Api-Key':'ZHhjZmIyMHdnazVtdWw='
//'Content-Type':'application/json'
},
//async: false, //return value as variable not to make an async success callback
type: 'GET',
dataType: 'json',
success: function(data){
console.log(data);
//var data2 = JSON.parse(data.data);
var data2 = data.data;
var data2Array = [];
$.each(data2, function(idx, data2){
console.log(data2.p_code);
console.log(data2.date);
console.log(data2.rq_no);
var userfo = data2.user;
console.log(userfo.fullname);
console.log(userfo.project_site);
var material = data2.materials;
var dateRequested = data2.date;
var requestNumber = data2.rq_no;
var requester = userfo.fullname;
var projectSite = userfo.project_site;
$.each(material, function(idx, material){
console.log(material.name);
console.log(material.purpose);
console.log(material.quantity);
console.log(material.cost);
console.log(material.total);
console.log(material.status);
var materialName = material.name;
var purpose = material.purpose;
var quantity = material.quantity;
var cost = material.cost;
var total = material.total;
var requestStatus = material.status;
/*$('#dateRequested').append(dateRequested);
$('#requestNumber').append(requestNumber);
$('#requester').append(requester);
$('#projectSite').append(projectSite);
$('#materialName').append(materialName);
$('#purpose').append(purpose);
$('#quantity').append(quantity);
$('#cost').append(cost);
$('#total').append(total);
$('#requestStatus').append(requestStatus); */
var table = $("#requestsTable");
table.append("<tr><td>"+dateRequested+
"</td><td>"+requester+
"</td><td>"+projectSite+
"</td><td>"+requestNumber+
"</td><td>"+materialName+
"</td><td>"+purpose+
"</td><td>"+quantity+
"</td><td>"+cost+
"</td><td>"+total+"</td></tr>");
});
});
},
error: function(){console.log('Error Encountered')},
//beforeSend: setHeader()
});
});
/* var request;
function setHeader(request){
request.setRequestHeader('Api-Key','ZHhjZmIyMHdnazVtdWw=');
request.setRequestHeader('Content-Type','application/json')
}*/
}
</script>
When using dataType:'json' in the code, we dont parse the json again as jQuery does all that so when we try to parse again it returns an error. Then for it to be appended to html we use $(selector).append where the selector is the element id. In this case when appending to table, we append to so it will be $(#tableBodyId).append("what to append");

How to use ajax to get page title for a URL

I want to get the <title> of a page using its URL.
For example,
if the URL is (https://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=ajax%20fail),
what I want to get is (ajax fail - google search)
Here is my code and unfortunately it does not work.
This code return error code: 0, undefined, no transport.
$(document).ready(function () {
titleInfo = {
url: "http://google.co.kr",
title: "abcd"
}
$('#target').text("SS");
requestAjax('http://gorapaduk.dothome.co.kr', titleInfo);
});
var requestAjax = function (url, data) {
$.ajax({
url: url,
cache: false,
success: function (html) {
alert(html);
request(html, data);
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
}
});
}
var request = function (html, data) {
var matches = data.match(/<title>(.*?)<\/title>/);
var spUrlTitle = matches[1];
data.title = spUrlTitle;
$('#target').text("spUrlTitle");
console.log(data.title);
}
Change,
var matches = data.match(/(.*?)</title>/);
to
var matches = html.match(/(.*?)</title>/);
in your request function .
and put,
dataType: "html",
in your ajax request .

Javascript: Determine whether an array contains a position

I have a list of files, and for each file, on click event, I get the file name and parse the file name and get the extension type:
extension = $('#'+id_href).text().split('.').pop();
Now, a ajax call should be made in order to fetch data about the current file extension.
I want to prevent the ajax api call if I already have the extension data saved in my extension array.
My extension array looks like: a[extension_1] = html_data_1, a[extension_2] = html_data_2;
I want to check if the position extension_1 already exists, and if not, a ajax call should be made to retrieve the data;
with what should i replace the if(!array_extension[extension]) line?
var array_extension = new Array();
ImgAjaxLoader = "$url_img"+'ajax-loader.gif';
ImgI = "$url_img"+'info_icon.png';
$("html").live("click", function() {
$(".info_box").hide();
});
$(".info").live("click",function(e){
e.stopPropagation();
var elem = $(this);
$(".info_box").hide();
position = $(this).offset();
var id = 'container_tooltip';
var id_img = $(this).attr('id');
var id_href = $(this).attr("id").replace("image_","href_");
$('#'+id_img).attr('src',ImgAjaxLoader);
$('#'+id).toggle(100, function() {
if($(this).css('display') == 'block') {
extension = $('#'+id_href).text().split('.').pop();
//if(!array_extension[extension])
$.ajax({
url: "$url",
data: { document_id:elem.attr('document_id') },
success: function (response) {
//console.log(response);
response = JSON.parse(response);
array_extension[response.extension] = response.html;
$('#'+id).html(response.html);
$('#'+id).css({'top':(position.top-110)+'px','left':(position.left+30)+'px'});
$('#'+id_img).css({'width':'20px','height':'20px',"padding":"0px"});
$('#'+id_img).attr('src',ImgI);
}
});
}
});
});

Fetch Data by variable with 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',

Categories