This might not be a well formulated question, what I need is the metadata from the document where the script is begin executed not from where the data is extracted...
We have foo.com/some_title_article.html
inside of it, we have an script
<script>
(function($) {
$(document).ready(function(){
var id = data.qids;
var theTime = new Date().getTime();
$.ajax({
url: "http://foo.com/apis/shares/api.php?ids="+id+"&time="+theTime
}).done(function(data) {
$('#showData').html(data); // This will show a basic html form...
});
});
})(jQuery);
</script>
inside the file api.php I call a few other java scripts that are related to where that file is stored, as it is right now is working fine, but what I need is to get metadata from some_title_article.html into my other java scripts that is loaded via ajax... sortof like var currentURL = window.location.href; which is declared inside and a java script inside the api.php file, it load the full url as foo.com/some_title_article.html and not foo.com/apis/shares/api.php ...get it?., So, how can get information from the url where the ajax is executed and pass it to the other scripts that are called after the ajax script...
Does this help:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<div id="showData"></div>
<script type="text/javascript">
$.ajax({
url: "http://foo.com/apis/shares/api.php?ids="+id+"&time="+theTime
}).done(function(data) {
var content = data.content;
var metadata = data.metadata;
$('#showData').html(content); // This will show a basic html form...
//Then, do whatever you want to with metadata
});
</script>
You make api.php return an object where the first key is the content and the second key is the meta data.
Otherwise, if api.php returns a string that already contains meta tags in it, you would need to parse them or add them to the dom and access them that way.
Can you share a sample of what is returned by api.php?
Related
I have a dropdown box which whenever I change its values, a js script forwards its responses to another dropdown. This script works when is inside the .html file, but once I move it to a seprate .js file it does not work. this is the code:
$("#id_subtag-tags").change(function () {
var tagId = $(this).val(); // get the selected tag ID from the HTML input
console.log(tagId);
$("#displaytags").html('');
$.ajax({ // initialize an AJAX request
url: '{% url "ajax_load_subtags" %}', // set the url of the request (= localhost:8000/app/ajax/load_subtags/)
data: {
'tags': tagId // add the tag id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_subtags` view function
$("#id_subtag-subtags").html(data); // replace the contents of the subtags input with the data that came from the server
}
});
});
There is another function in the same file which is properly is being loaded to that html file, so I think problem is not in loading. I don't know what is causing this bug.
The error I receive is:
GET failed, ajax_load_subtags 404 (Not Found),
url.py:
path('myapp/post/ajax/ajax_load_subtags', load_subtags, name='ajax_load_subtags'),
My guess is that the problem is in loading the url, as in html I had {% load static %} but I don't know what is the equivalent in .js files!!
In the AJAX url, you are trying to use Django template syntax inside JS with {% url "ajax_load_subtags" %}. This means you will be doing a request to an empty url and therefore receive a 404.
I would recommend adding the url to a data attribute like below:
HTML
<div id="someElement" data-subtags-url="{% url 'ajax_load_subtags' %}">
JS
$.ajax({
url: $('#someElement').data('subtags-url'),
...,
});
For those working with django and have the same issue. I just used directly the url rather than the name of url and it works:
$("#id_subtag-tags").change(function () {
var tagId = $(this).val(); // get the selected tag ID from the HTML input
console.log(tagId);
$("#displaytags").html('');
$.ajax({ // initialize an AJAX request
url: "/myapp/post/ajax/ajax_load_subtags", // set the url of the request (= localhost:8000/app/ajax/load_subtags/)
data: {
'tags': tagId // add the tag id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_subtags` view function
$("#id_subtag-subtags").html(data); // replace the contents of the subtags input with the data that came from the server
}
});
});
The best way is putting a static folder on the main directory. Then on your .html file on the top you could just add {% load static %}. Then go to your settings.py and on the bottom paste this
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
Now on your .html file since the <script> work properly at the bottom then just do this
{% static 'filename.js' %}
This should work
I'm having an issue with sending some HTML code using AJAX please see my code below
<iframe src="http://www.w3schools.com" width="10" height="10" id="awc_frame"></iframe>
<script>var iframe = document.getElementById("awc_frame");</script>
Here is the AJAX code below
<script>
$.ajax({
type: "POST",
url: "mobileView.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
})
</script>
The code isn't sending the variable to the PHP file. Looking into the Network side of things it sends text ie if I put "" around iframe it sends this code
"val = iframe" but not the actual code within the iframe. The "var iframe"does work and pulls back the HTML code of the iframe
Please tell me what I'm doing wrongly.
Thanks in advance.
EDIT: I'm sorry. It's not the HTML code within the iFrame I need to send, It's the entire iFrame code I need to send.
Another Edit: What I'm trying to accomplish when a visitor from my company goes to my website I would like Javascript or Jquery to load an internal website from the visitors computer and then have all of the code from that website that's on the client's end to be sent to a Server which will store the entire iFrame code in a database.
This would send the entire html inside the iframe.
var iframe = $('#awc_frame').html();
First of all, var iframe does not contain HTML of the iframe element - it contains a DOM Node, which is kind of a wrapper around the iframe element (it contains various properties of that element, including the HTML).
Next thing, you probably want to wait for the iframe to completely load all the contents, so you'll have to bind to the load event of it.
Something like this should work:
var $iframe = $("#awc_frame");
$iframe.on("load", function () {
var iframeHTML = $iframe[0].contentWindow.document.body.innerHTML;
// jQuery alternative
var iframeHTML = $iframe.contents().find("body").html();
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: iframeHTML
},
success: function(data){
console.log(data);
}
});
});
Super important thing in this example
Just one more thing - please note that for websites outside of your own domain, this code won't work (due to Same Origin Policy). Any other code won't work too.
Since javascript has problems with getting the HTML from a cross-domain iframe, you can't do this across domains. However, why not just send the iframe's src attribute to the PHP page, and then just use file_get_contents to get the HTML, and then store that? Problem solved:
Javascript:
var iframe = $('#awc_frame').prop('src');
$.ajax({
type: "POST",
url: "posttest.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
});
PHP:
$html = file_get_contents($_POST['val']);
what are you trying to do?
var iframe = document.getElementById("awc_frame");
above code is an javascript object of your iframe which contains a lot of properties.. since you are using jQuery, you could get that with:
var iframe = $('#awc_frame');
keep in mind that above code is the element it self in jquery object format you could get element object like this:
var iframe = $('#awc_frame')[0];
** you're doing something wrong.
if you're trying to get iframe HTML content:
var iframe_contents = $("#awc_frame").contents();
if you explain more about what you are trying to do, i can update my answer to suit you.
* UPDATE *
considering what you are trying to do..
Method #1: (Easy Way)
you could use php to fetch content of the website you need:
<?php
$contents = file_get_contents('http://www.w3schools.com');
// Saving $contents to database...
?>
Method #2: (Hard Way)
as #mdziekon said, you first should wait until your iframe gets loaded then:
var iframe = $("#awc_frame");
iframe.on("load", function () {
var contents = $(this)[0].innerHTML;
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: contents
},
success: function(data){
console.log(data);
}
});
});
hope it solves your problem
I need to find a way to pass the correct input to this javascript function to have it search an XML document and return the requested node value(s). The parsing of the XML node values actually does work properly when hard-coded as seen below and I can successfully load content using the following:
function parse(document){
Lyrics2 = $(document).find('elementRef[id="2"] content').text()
Ref2 = $(document).find('elementRef[id="2"] bibleRefs').text()
$("#content").text(Lyrics2);
$("#scripture").text(Ref2);
};
$.ajax({
url: 'songlyrics.xml',
dataType: "xml",
success: parse
});
The problem is I want to pass an additional parameter to the parse function that searches for somnething else in the XML. The ultimate goal is to have a div updated on the page with modified content from the XML document once a link is clicked, for example, something like this (where 'reference' is the search string passed in):
function parse(document,reference){
Lyrics2 = $(document).find(reference).text()
$("#content").text(Lyrics2);
};
...
<div id="content"></div>
Title
What is happening is the text that is present on page load is replaced with nothing after clicking a link that has onClick specified to run the 'parse' function--no errors are generated in the debug window.
XML:
<?xml version="1.0" encoding="UTF-8"?>
<elements>
<elementRef id="1">
<name>John</name>
<artist>Smith</artist>
<content>Active</content>
<supportImg>test1</supportImg>
<bibleRefs>Mark 2:13</bibleRefs>
<other>Mark 2:11</other>
</elementRef>
<elementRef id="2">
<name>Jane</name>
<artist>Smith</artist>
<content>Active</content>
<supportImg>test2</supportImg>
<bibleRefs>John 3:17 Mark 12:3</bibleRefs>
<other>October, 2011</other>
</elementRef>
</elements>
Please let me know if you need more information in order to help. Any help is GREATLY appreciated.
I think what you are looking for is
function parse(reference) {
if (!xml) { //the ajax request is not yet loaded so there is nothing to do
return;
}
var content = $(xml).find(reference).text()
$("#content").text(content);
};
var xml;
$.ajax({
url: '
songlyrics.xml ',
dataType: "xml",
success: function (doc) {
//assign the loaded xml content to a gloabl variable so that it can be used later
xml = doc;
}
});
then
Title
I'm trying to get JSON array from my php-script. Following is my Jquery code written in my jsp file-
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://example.com/root_dir/test_json.php', function(data)
{
alert(data);
});
});
but, above code showing only outer alert (i.e. alert("Inside Ready");) and not showing inner alert (i.e. alert(data); ). I'm getting expected json when I hit URL in browser. So definitly there is no problem in URL and php-script.
following is test_json.php
<?php
//Create an array
$json_response = array();
$row_array['label'] = 'A';
$row_array['value'] = $row['0 to 2'];
$row_array['color'] = '#FA2020';
array_push($json_response,$row_array);
$row_array['label'] = 'B';
$row_array['value'] = $row['2 to 3'];
$row_array['color'] = '#2BD95A';
array_push($json_response,$row_array);
$row_array['label'] = 'C';
$row_array['value'] = $row['above 3'];
$row_array['color'] = '#F7F739';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
Getting following json when I hit URL in browser-
[{"label":"A","value":"19","color":"#FA2020"},{"label":"B","value":"1","color":"#2BD95A"},{"label":"C","value":"2","color":"#F7F739"}]
I'm using jquery-1.10.2.js. Thank You..!
Try This one...Hope so it is useful to you
$(document).ready(function()
{
$.ajax({
type:'POST',
url:'http://example.com/root_dir/test_json.php',
dataType:'JSON',
data:{
},
success:function(data1){
alert(data)
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("error");
}
});
});
Your code seems to be working fine -
I just created a test page with your code and it works -
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://<<CHANGE SERVER NAME>>/zz-test/get_json.php', function(data)
{
alert(data);
});
});
</script>
</head>
<body>
</body>
</html>
Your jQuery and PHP code looks fine so, in my experience, it is usually an error caused by calling your PHP script from a different domain (i.e.: file:///). If you can access your browser's console, you should be able to see if this is in fact the error causing the data not to be displayed.
One solution for this is to add at the top of your PHP code:header('Access-Control-Allow-Origin: *');. There are however some security concerns with this, so it should not be used permanently.
Alternatively, you could upload all your HTML, CSS, JS, jQuery, etc. code to the web server hosting the PHP file, which is a far better option.
Finally, if the option above is not possible you could use JSON-P (although this does not work with POST requests), there is a question about this at Simple jQuery, PHP and JSONP example?
Sometimes you see code like this.
<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
{lang:'en', parsetags:'explicit'}
</script>
I'd like to know how it's possible to parse the object literal inside this script tag from the loaded script.
var scripts = document.getElementsByTagName('script');
var thisScriptTag = scripts[scripts.length - 1];
var data = thisScriptTag.textContent || thisScriptTag.innerText;
alert(data);
If you have JSON data you'd use JSON.parse() to convert the data to a JavaScript object.
Note that the code must not be wrapped in a DOMready/onload event - it needs to run right when that <script> tag is processed.
The code to get the current script tag was taken from How may I reference the script tag that loaded the currently-executing script?