I have a URL that I'd like to scrape a certain bit of information from and I'd preferably do that by obtaining the element. I'd also need to get it as plaintext, but I'm still pretty new to Ajax/jQuery and don't quite know what the correct syntax is..
My ajax call is:
$.ajax({
url: URL,
dataType: 'text',
success: function(data) {
var info = data; //How can I get a table from the data without loading the whole site extracting a small portion?
if(info != undefined) {
console.log(info); //Needs to be plaintext.
}
}
});
I hope my question is clear... I'm essentially loading a website and retrieving a table or class name as plaintext... How could I do that? Thanks.
Your options on the client-side are:
1.) First, optionally use a regular expression to isolate that tag contents, but this is usually considered rather costly.
2.) Create a node, then drop the text into it's innerHTML.
That's usually the standard way of rendering text responses to the DOM.
Neither one are all that lightweight.
If you just need to pick something out of the text, use Regular Expression. Also, as mentioned, be aware of XSS and cross-origin policy.
Additionally, you may want to handle this on the server-side.
Related
I'm using jQuery and an $.ajax() call to post some complex HTML via POST to my database. I'm able to get the form's structure via .html(), but the user's selections are lost in the process. I thought I could use .clone() instead but I got this error:
Uncaught InvalidStateError: Failed to read the 'selectionDirection'
property from 'HTMLInputElement': The input element's type ('hidden')
does not support selection.
// Cloning my form
var myFormHTML = $("#myForm").clone();
console.log(myFormHTML);
var inputData = {
advancedSearchHTML: myFormHTML,
otherParam: otherVar
};
console.log(inputData);
// JS ERROR is down here in the $.ajax() call:
$.ajax({
type: "POST",
url: 'serverSideScript.php',
dataType: 'html',
data: inputData,
success: function (response) {
console.log(response);
}
});
These forms are very complex and they include over 100 <input type="hidden">'s which change according to the user's selections. I can't change the way this works. So my problem is that I have complex forms with HTML generated by the user and I need to copy both the HTML AND all its values so that it can be inserted into my database and eventually reloaded back into the DOM, perhaps months later. Any ideas?
EDIT: I've tried everything I can think of but I can't seem to get user input values out of the HTML, which is frustrating because I'm used to just hitting "Copy HTML" in Chrome's Inspector, so to me it seems like it should be easy to get that same HTML out of the <form> as a string. Some of the things I've tried:
$myFormHTML.html()
$myFormHTML.innerHTML
$myFormHTML.outerHTML
$myFormHTML.get(0).innerHTML
$myFormHTML.get(0).outerHTML
JSON.stringify($myFormHTML.html())
I've got it down to the point where I've got a complete jQuery Object which, when appended to the DOM, has all the user's input included (:selected states, :checked states, input values, etc.). I need to take this jQuery Object and spit out all its HTML content into a string that can be transferred to the server. Does anyone have any idea what to do? Maybe there's a way to do the same loop that gets done during an $.append() so I could build up a string from scratch? Any other ideas?
http://api.jquery.com/serialize/
This does exactly what you want, except since your form is built by user-input you cannot verify if it's a valid form or not. If the form markup is incorrect, you cannot serialize the data.
Here is the example:
http://jsfiddle.net/jyc30nxz/1/
$('#myForm').serialize();
An important aspect of this is if your form inputs do not have the "name" attribute, then you cannot return it's value during serialization which is why you end up with an empty string.
Edit:
This also works:
console.log($(this).clone().html())
My guess is your form markup is invalid
Have you tried to .serialize the form contents?
I have a javascript array which stores seat numbers (in a cinema), which are selected by the user via clicking and added to the array each time using a function. I want the page to show the total cost of these seats, which means accessing an sql table inside some php.
So I have e.g. seatNumbers = ["a1", "d6", "e3"] and three sql query like 'select cost from seat where seat_number='a1';'. The function that adds to the array on clicking a seat and prints the seats is something like:
var seatArray = [];
function addSeat(seat) {
seatArray.push(seat);
document.getElementById("textarea").innerHTML="Seats : ";
for (x in arraytest) {
document.getElementById("textarea").innerHTML+=arraytest[x];
document.getElementById("textarea").innerHTML+=" ";
}
}
And I want to show the total cost in the HTML.
I'm wondering if what I'm trying to achieve is possible? What would be the general method and would I need to load a new page instead? And if it's not possible, what would be a better way to go about this?
Your question is very broad, and to answer it, quite some stuff needs to be known and used.
What you want is very possible though. In fact, there are technologies that in their core focus on providing solutions to problems like yours! What you need is some solid info (and possibly experience with) AJAX and maybe even REST. By using AJAX your page wont have to reload, and in your situation AJAX is probably the best choice anyway.
To point you in the right direction: AJAX javascript W3Schools Tutorial and PHP AJAX W3Schools tutorial
Then, use jQuery to make it all a LOT easier: jQuery (i'd go for 1.x)
You'll have to create an API that accepts an HTTP (preferably GET) request and returns the cost for the seat that you refer to in your URL like (more REST like, should return a whole seat object with price included): /seat/200, or (not REST like)/seat/cost/200).
Your choice if you want to follow (if you haven't read up on it, possibly confusing) REST rules. In your situation i'd just begin with some good old AJAX, it just works and is even better suited for stuff like this.
You should use AJAX. Try using jQuery library and ajax function.
Covert Your array with seats on JSON string and send it by AJAX to page which check the whole price. Then, You can update Your HTML code with total cost.
var json_data = '{...}';
$.ajax({
url: "total_cost.php",
dataType: "json",
type: 'POST',
data: { json: json_data },
success: function(response) {
// .. on success
var json_response = jQuery.parseJSON(response);
var cost = json_response.total_cost;
}
});
site.com/api/index.php is where I need the ajax request to go. From site.com/sub/ the request works perfectly but sub.site.com is sending the request to sub.site.com/api/index.php which obviously does not exist... I've Google and StackOverflowed the hell out of the question, but can't seem to find an answer that works.
Code:
var jQuery_ajax = {
url: "site.com/api/index.php",
type: "POST",
data: $.param(urlData),
dataType: "json"
}
var request = $.ajax(jQuery_ajax);
The most common answer was to set document.domain to the regular site, but that does not seem to do anything... I've also seen answers talking about iFrames, but I want to stay away from iFrames at all costs.
document.domain = "site.com";
** Note: everything is on the same server.
HACKY SOLUTION: made sub.site.com/api/index.php a file that simply reads
include_once("$path2site/api/index.php");
Once you've corrected the URL to http://site.com/api/index.php try adding the following to api/index.php:
header("Access-Control-Allow-Origin: http://sub.site.com");
e: it's possible that doing so may disallow use from site.com as well; I'm not seeing a way to provide two values, so you may need a way to tell it which site to use, like a ?sub=1 arg to index.php
I'm trying to use the API from https://developer.forecast.io and I'm getting a JSON response, this is the first time I'm using an API and all I really need to know is, how do I assign the JSON response I get back from their API to elements on my page. Thanks!
This is done with a script-tag in my header:
script(src='https://api.forecast.io/forecast/APIKEY/LAT,LON')
http://api.jquery.com/jQuery.ajax/ you need to add a success callback, at the bottom of that page are examples you can look at.
EDIT
ok i saw that you are using a script tag with the request, since the api is outside your current domain you need to make a JSONP request
$(document).ready(function(){
$.ajax({
url: 'https://api.forecast.io/forecast/APIKEY/LAT,LON',
dataType: 'jsonp',
success: function(data){
//do whatever you want with the data here
$("body").append(JSON.stringify(data));
}
});
});
off course you need to make some tweaks to that piece of block but you get the idea
What you're looking for is DOM manipulation. DOM is the HTML Document Object Model, an object representation of the HTML comprising a document. There are a lot of ways to go about this, but one of the more popular Javascript libraries for performing this task is jQuery. See their help documentation category on manipulation for more information.
OK, based on your clarification, you're not yet using AJAX. I say "not yet", because you're going to need to. Again, I'll recommend jQuery for that, and their own documentation as the best resource. For a simple "get", your easiest option is the getJSON method.
So, at a very simple level you might do something like:
$(function(){
$.getJSON('url_to_api', function(data) {
$("#SummaryBox").append("<div>" + data.hourly.summary + "</div>");
}
});
I'm having an issue I cannot resolve through trying lots of different methods!!
Works in Chrome, FF, IE9 but not IE8 or IE7
Overview
I have a page, that Ajax's in the whole HTML from a local .aspx of which reads a photobucket XML feed puts into an HTML list and returns.
http://custommodsuk.com/Gallery.aspx
I've done it this way so the page ranking isn't penilised by Google speed rankings, as the server would be going off and making the call.
The code
$.ajax({
type: "GET",
url: ajaxURL,
dataType:'html',
success: function (feedHTML) {
var galleryList = $(feedHTML).find('#galleryList').find('.listItem');
var noItems = galleryList.length;
console.log(feedHTML.type);
galleryList.each(function (index) {
...
});
}
});
What I've tried
As you can see the console.log(),
the type is undefined, the feedHTML.length shows no. of characters. And from what I gather is generally treated as a string.
It is the JQuery not being able to turn the response into a jQuery object, and I can't traverse it. Therefore the each won't cycle.
I've seen lots of people with the same/similar issue on SO, but no answers, partly due to crap code examples.
Photobuckets RSS feed is malformed.
<p>CustomModsUK posted a photo</a></p>
This tripped up IE8. If you ever have problems like this in the future, check the validity of the HTML!!!