Pinterest pins through HTML/JavaScript - javascript

I Have been using pins to get the information of a pin from pinterest.
The following is the script being used:
<script type="text/javascript">
function getresponse1()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids="+{Pin ID});
alert(xmlHttp.status);
var data=xmlHttp.responseText;
var jsonResponse = JSON.parse(data);
var pin_url="www.pinterest.com/pin/"+pin_id+"/";
var page_name=(jsonResponse["data"][0].pinner.full_name);
alert(page_name);
}
</script>
Whenever XMLHttpRequest() method is being invoked the status returned is always 0 and the xmlHttp.responseText is empty.
But when the link is opened in a browser the response is correct and has all the information of the pin.
EDIT:
Tried implementing cross domain too. But yet the status returns 0.
New Script:
<script type="text/javascript">
function getresponse1()
{
var xhr = new XMLHttpRequest();
var url="https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids=308074430730714588";
if ("withCredentials" in xhr) {
xhr.open("GET", url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
alert(xhr.status);
var data=xhr.responseText;
}
</script>
Please let me know where i'm making mistake. Thanks in advance
Note: I'm using Chrome browser

This is an general issue, as you try to do an ajax request to a different site (cross domain).
This isn't an new issue at all, I think here it is well explained and this posts provide also some thoughts about possible solutions.

AJAX is asynchronous, so your data will only be available from some kind of callback.
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
var data = JSON.parse(request.responseText);
}
};

Related

Send PHP Variable with Ajax Call

I wrote a PHP application that makes an AJAX call (XMLHttpRequest) and is called every 5 seconds. The page called makes a database query. However, I need a variable from the main page and am unable to find a solution to attach it to the Ajax call.
Using $_GET seems a bit too insecure to me. Is there another way here?
This is my first expierence with ajax so please dont be to hard with me :)
Here is my Ajax Call
const interval = setInterval(function() {
loadText() }, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.'&name='.$_SESSION['name'].'&org='.$_SESSION['org'];?>', true);
xhr.onload = function() {
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText; }
})
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
// console.log(xhr);
}
Ill hope i provided enough Information
WIsh u all a great weekend
You do not need sending session variables at all: those are already known to the called page, because it can share the session information of the calling page.
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?= $role ?>'
is enough, provided that "table_view.php" issues a session_start() command.
I have fixed your code; It's here:
(Note: \' means that the character ' doesn't closing the string.)
const myInterval = setInterval(function(){loadText();}, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.\'&name=\'.$_SESSION[\'name\'].\'&org=\'.$_SESSION[\'org\']; ?>', true);
xhr.onload = function(){
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText;
}
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
}

ReferenceError: CSV is not defined

I am using the jquery.csv-0.71.min.js lib to load a csv file and convert it to an array. However, when loading my webpage:
<script src="assets/lib/jquery/dist/jquery.min.js"></script>
<script src="assets/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Jquery-csv -->
<script src="assets/js/jquery.csv-0.71.min.js"></script>
<script>
(function() {
var data;
var url = 'data/data.csv';
function makeRequest(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.readyState === 4 && xhr.status === 200) {/*run code*/}
};
xhr.send(null);
}
})();
data = CSV.toArrays(xhr.responseText);
console.log(data);
</script>
I get in the console:
ReferenceError: CSV is not defined at 'data = CSV.toArrays(xhr.responseText);'
Any recommendations what I am doing wrong?
I appreciate your replies!
UPDATE
I put my code into the document read funciton, however, I still get the same error as above.
$(document).ready(function() {
(function() {
var data;
var url = 'data/data.csv';
function makeRequest(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.readyState === 4 && xhr.status === 200) {/*run code*/
}
};
xhr.send(null);
}
})();
data = CSV.toArrays(xhr.responseText);
console.log(data);
});
You code is executed before browser loads the CSV script.
Wrap you JavaScript code with
$( document ).ready(function() {
// PUT YOUR JavaScript CODE HERE
});
This will make browser to wait, until all your scripts are loaded, and only after to execute the code.
You can check the documentation of the jquery csv here. It says that you should invoke methods like this:
$.csv.toArrays(csv);

XMLHttpRequest does not send file

I want to upload a file trough a XMLHttpRequest. i have looked everywhere for examples and found quite a few. But i cant figer out what it is i am doing wrong. This is my code. The function is triggerd when a button is pressed. It not wrapped in from tags
function upl_kost() {
var url = "proces_data.php?ref=upload_kost";
var hr;
var file = document.getElementById("file_kost");
var formData = new FormData();
formData.append("upload", file.files[0]);
if (window.XMLHttpRequest) {
hr=new XMLHttpRequest();
} else {
hr=new ActiveXObject("Microsoft.XMLHTTP");
}
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "multipart/form-data");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
alert(return_data);
}
}
hr.send(formData);
}
and this function catches it.
if($_GET['ref'] == 'upload_kost') {
var_dump($_FILES);
}
My problem is that the $_FILES stays empty. When i look at the file.files variable in the js its loaded with the data from the file that i am trying to upload.
Thanks!
Reduce your JavaScript down to minimum required for this, then add in some helpful messages you can look in your console for
function upl_kost() {
var xhr = new XMLHttpRequest(),
url = 'proces_data.php?ref=upload_kost',
fd = new FormData(),
elm = document.getElementById('file_kost');
// debug <input>
if (!elm)
console.warn('Element not found');
else if (!(elm instanceof HTMLInputElement))
console.warn('Element not an <input>');
else if (!elm.files || elm.files.length === 0)
console.warn('<input> has no files');
else
console.info('<input> looks okay');
// end debug <input>
fd.append('upload', elm.files[0]);
xhr.addEventListener('load', function () {
console.log('Response:', this.responseText);
});
xhr.open('POST', url);
xhr.send(fd);
}
If you're still having a problem, it may be server-side, e.g. are you performing a redirect before trying to access $_FILES?
Your problem is that you're setting the content type of the request
hr.setRequestHeader("Content-type", "multipart/form-data");
If you ever saw a multipart/formdata post you'll notice the content type header has a boundary
Content-Type: multipart/form-data; boundary=----webko2354645675756
which is missing from your code.
If you do not set the content type header the browser will correctly set it and the required boundary. This will allow the server to properly parse the request body.

get full html source code of page through ajax request through javascript

The javascript code will be launched from www.example.com through the url bar in google chrome so i cannot make use of jquery. My goal is to pass the full html source code of www.example.com/page.html to a variable in javascript when i launch the code in www.example.com. Is this possible? If so how? I know to get the current page source it's just document.documentElement.outerHTML but i'm not sure how i'd do this. I think it's possible by using responseText somewhere in the following code:
http.send(params);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://www.example.com/page.html",true);
xmlhttp.send();
data = ""
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
data = xhr.responseText
}
}
xhr.send();
function process(){
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
alert(xhr.responseText)
}
}
xhr.send();
}
this is how i run script from the address bar.. I do it all the time..
i create a bookmark like this
javascript:script=document.createElement('script');script.src='http://10.0.0.11/clear.js';document.getElementsByTagName('head')[0].appendChild(script); void(sss=1);
then i host the js file on my computer.. i use analogx simpleserver... then you can use a full page for your script

Trying to use javascript with REST

There's quite nothing that makes me as frustrated as web development, which luckily I don't get to do often, and here's an example why. Is there any reason why the following code works perfectly fine in DreamWeaver Live View, stops after alert("2") (alert 3 never appears, neither does anything in output) on Chrome and doesn't work at all in Internet Explorer?
<script type="text/javascript">
function getStuff() {
var url = "http://url/to/restful/api";
alert("1");
var client = new XMLHttpRequest();
client.open("GET", url, false);
client.setRequestHeader("Content-Type", "application/json");
alert("2")
client.send();
alert("3")
document.getElementById("output").value = client.responseText;
}
</script>
This is called like this:
<button onClick="getStuff()">GET</button>
Try the following code:
Please go through this link http://en.wikipedia.org/wiki/XMLHttpRequest
<script type="text/javascript">
function getStuff() {
var url = "http://url/to/restful/api";
alert("1");
var client = getXMLHttpRequestObject();
client.open("GET", url, false);
client.onreadystatechange = function() {
if(client.readyState == 4){
document.getElementById("output").value = client.responseText;
}
};
client.setRequestHeader("Content-Type", "application/json");
alert("2")
client.send();
alert("3")
}
function getXMLHttpRequestObject() {
var ref = null;
if (window.XMLHttpRequest) {
ref = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Older IE.
ref = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
return ref;
}
</script>
On a side note
client.open("GET", url, false);
Using sync connection using ajax is a bad idea. It will freeze your UI code.
This is the reason why alert(3) is never called. When you do xhr.send() the thread stops and waits for the response from the server.
The ideal way to do this would be client.open("GET", url, true);

Categories