Trigger cross domain YQL ajax request with input onBlur - javascript

I have a form to collect information about a product (i.e. from Amazon). I am attempting to trigger a YQL ajax request on blur of the URL input. Currently, no errors in console, but no results either. Here is my form input:
<div class="uk-form-row">
<div class="uk-form-label"><?php echo $this->form->getLabel('item_url'); ?></div>
<div class="uk-form-controls "><input type="text" name="jform[item_url]" id="jform[item_url]" value="<?php if (!empty($this->item->id)) { echo $this->item->item_url;}; ?>" class="uk-form-large uk-width-medium-1-1" placeholder="http://" aria-required="required" required="required"/></div>
</div>
<script type="text/javascript">
jQuery( "#jform[item_url]" ).blur(function() {
var path = jQuery('#jform[item_url]').val();
requestCrossDomain(path, function(results) {
jQuery('#url_results').html(results);
});
});
</script>
<div id="url_results">
</div>
My function:
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {
// If no url was passed, exit.
if ( !site ) {
alert('No site was passed.');
return false;
}
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
jQuery.getJSON( yql, cbFunc );
function cbFunc(data) {
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
Here's the fiddle: http://jsfiddle.net/FLY66/2/

This issue is more related to your server. You can simply set the Access-Control-Allow-Origin header on your server. Look for your server language to see how to set Access-Control-Allow-Origin
Setting it to * will accept cross-domain AJAX requests from any domain.
Another alternative is use 'JSONP' data type for returned data.
References
http://en.wikipedia.org/wiki/Same_origin_policy
https://developer.mozilla.org/en/http_access_control

Related

Send Cookie via JS to PHP

I am trying to send a String within Javascript to my Server. I made it create a cookie and right now I would like it to do stuff (for now: a simple echo). This is my button-function (I am using Bokeh):
const d = s.data;
var clustOut = "Nevermind the real input";
if (numberOfColors.length >= 2) {
localStorage.setItem("input", clustOut);
document.cookie = ('clustOut=' + clustOut + ';max-age=10368000;' + ';path=/');
window.location.href = "/php-scripts/post_cluster.php";
//alert(numberOfColors.length + "\\n" + clustOut);
//alert(d["x"] + d["y"] + d["color"]);
} else {
alert ("You have to assign the points to at least two clusters!");
}
My PHP-Files should simply echo:
<?php
$clustOut = $_COOKIE['clustOut'];
echo $clustOut;
?>
I am pretty sure that window.location.href = "/php-scripts/post_cluster.php"; might be the wrong command for a submit. What can I do to make my PHP-Script get the Cookie that I just set?
Sending data with the Fetch API.
The client and server can communicate with each other with the HTTP protocol. Whenever you load a webpage a HTTP request is send to the server and a response is send back to the client. You can make your own requests and talk to the server through the same protocol with the Fetch API.
You send the data to the server and wait for a response to come back. This way you can check what the server received and maybe do something with the response you got back.
let data = {
clustOut: "Nevermind the real input"
};
fetch('/php-scripts/post_cluster.php', {
method: 'POST',
body: JSON.stringify(data)
}).then(response => {
if (response.status === 200 && response.ok) {
return response.text();
}
}).then(message => {
console.log(message);
});
Sending data with XMLHttpRequest (IE10+)
For browsers that don't support the Fetch API fall back to the older XMLHttpRequest. It does the same thing, but is written differently.
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (this.status === 200) {
console.log(this.responseText);
}
}
xhr.open('POST', '/php-scripts/post_cluster.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(JSON.stringify(data));
Sending data with the a form.
A more analogue approach would be to use a <form> element with the action attribute pointing towards your PHP script. This will also send a request to the PHP file while reloading the page. However, reading out the response works differently as you need to display the response on the page during rendering to see the outcome.
<form method="POST" action="/php-scripts/post_cluster.php">
<input type="hidden" name="clustOut" value="Nevermind the real input">
<button type="submit">Send</button>
</form>
Receiving data on server
Because in the examples above we've used the POST method to send our data, we'll need to access the global $_POST variable in PHP to read out the data that has been send. The value that is being returned or echoed will be send back in the response to the client.
<?php
$clust_out = isset( $_POST[ 'clustOut' ] ) ? $_POST[ 'clustOut' ] : '';
return $clust_out . ' has been received';
?>

passing data using post array in java-script

i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>

How to load a php file correctly using jquery

So allow me to first say I have looked at previous questions, and none of them have helped me out. My problem is as follows, I have an html file with a form which calls a javascript function to load a php file.
The form looks as following:
<form method="GET" id="submission" >
<div class="form-group">
<label for="q">Search Term:</label>
<input type="text" class="form-control" id="q" name="q" placeholder="enter a keyword">
</div>
<div class="form-group">
<label for="location">location</label>
<input type="text" class="form-control" id="location" name="location" placeholder="lat,long">
</div>
<div class="form-group">
<label for="locationRadius">Location Radius:</label>
<input type="text" class="form-control" id="locationRadius" name="locationRadius" placeholder="25km">
</div>
<div class="form-group">
<label for="maxResults">Max Results:</label>
<input type="number" class="form-control" id="maxResults" name="maxResults" placeholder="0 to 50">
</div>
<button type="submit" id="submitButton" >Submit</button>
</form>
The JS function responsible for sending is the following:
function sendData() {
var keyword = document.getElementById("q").value;
var location = $('#location').value;
var locationRadius = $('#locationRadius').value;
var maxResult = $('#maxResults').value;
alert("keyword is: " + locationRadius);
$.get(
{
type: 'GET',
url: '../php/geolocation.php',
data : {q: keyword, location: location, locationRadius: locationRadius, maxResults: maxResult}
},
function (data) {
//alert("Data loaded " + data);
document.getElementById("geolocation-results").innerHTML = data;
}
);
}
$(document).ready(function() {
$("#submission").submit(function() {
sendData();
return false;
});
});
SO my problem is two fold, how to call it in an ajax like manner as the above format worked for my old code, but for some reason refuses to function correctly for this one. And how should I fetch the php data? The php code is below:
It is a modified version of youtube's geolocation example code.
<?php
/**
* This sample lists videos that are associated with a particular keyword and are in the radius of
* particular geographic coordinates by:
*
* 1. Searching videos with "youtube.search.list" method and setting "type", "q", "location" and
* "locationRadius" parameters.
* 2. Retrieving location details for each video with "youtube.videos.list" method and setting
* "id" parameter to comma separated list of video IDs in search result.
*
* #author Ibrahim Ulukaya
*/
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
$htmlBody = null;
// This code executes if the user enters a search query in the form
// and submits the form. Otherwise, the page displays the form above.
if (isset($_GET['q'])
&& isset($_GET['maxResults'])
&& isset($_GET['locationRadius'])
&& isset($_GET['location'])) {
/*
* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$DEVELOPER_KEY = 'AIzaSyC6q-84bJv9HWCUDT4_SQ5Bp9WFJW2Z-e4';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
try {
// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'type' => 'video',
'q' => $_GET['q'],
'location' => $_GET['location'],
'locationRadius' => $_GET['locationRadius'],
'maxResults' => $_GET['maxResults'],
));
$videoResults = array();
# Merge video ids
foreach ($searchResponse['items'] as $searchResult) {
array_push($videoResults, $searchResult['id']['videoId']);
}
$videoIds = join(',', $videoResults);
# Call the videos.list method to retrieve location details for each video.
$videosResponse = $youtube->videos->listVideos('snippet, recordingDetails', array(
'id' => $videoIds,
));
$videos = '';
// Display the list of matching videos.
foreach ($videosResponse['items'] as $videoResult) {
$videos .= sprintf('<li>%s,%s (%s,%s)</li>',
$videoResult['id'],
$videoResult['snippet']['title'],
$videoResult['recordingDetails']['location']['latitude'],
$videoResult['recordingDetails']['location']['longitude']);
echo $videos;
}
//$htmlBody = <<<END
// <h3>Videos</h3>
// <ul>$videos</ul>
//END;
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
}
?>
It appears that the problem is your attempt to specify an non asynchronous request. I believe these are blocked by current/modern browsers. If you check your javascript console, you will probably see an error like this:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
If you remove that, I believe it will work as before (if it worked earlier, as you indicated). jQuery ajax requests are asynchronous by default, so if you remove that line, it will operate asynchronously.
(This wasn't part of your question, but you might consider leaving your input field's value="" blank, and put your helper text in placeholder="" attributes instead. These will provide the clue to your users without the risk of having that information passed in your request.)
As for displaying the result of the call, having your call return HTML and simply displaying that HTML on your calling page should work. Since you're using jQuery you could simplify your code like so: $('#geolocation-results').html(data); You may need/want to specify dataType: 'html' in your call as well. (https://api.jquery.com/jquery.get/)
Oh my. So obvious now. I believe your structure of the .get call is wrong. Should be like this:
$.get(
"../php/geolocation.php",
{
q: keyword,
location: location,
locationRadius: r,
maxResults: maxResult
},
function (data) {
$('#geolocation-results').html(data);
}
);
Checking that now... Okay, after rushing a bit too much I can confirm that the $.get() call was just structured wrong. Correct it as shown above and it will call the PHP file correctly and display the output in the geolocation-results element.
I think there are some mistakes in your code. You don't need to put async (and not asynch) as false because it's blocking the client browser for nothing. Be also careful to your url parameter which should not contains any quotes. Finally, you should put your trigger on the submit event more than on the onclick event because you can submit the form just by pressing Enter without clicking on your button.
You can try with this javascript :
function sendData() {
var keyword = document.getElementById("q").value;
var location = $('#location').value;
var locationRadius = $('#locationRadius').value;
var maxResult = $('#maxResults').value;
alert("keyword is: " + keyword);
$.get(
'../php/geolocation.php',
{q: keyword, location: location, locationRadius: locationRadius, maxResults: maxResult},
function (data) {
alert("Data loaded " + data);
document.getElementById("geolocation-results").innerHTML = data;
}
);
}
$(document).ready(function() {
$("#submission").submit(function() {
sendData();
return false;
}
});

AJAX and YQL doesn´t work using dreamweaver (cross-domain-request)

I use a js to display some content on my app (I use Dreamweaver and PhoneGap). When i preview the html separately works, but when i load the html from other page dont.
I receive this msg on the Firefox Security: ReferenceError: requestCrossDomain is not defined
This is my HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Mobile Web App</title>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/cross-domain-request.js"></script>
</head>
<body>
<div id="container">
<p id="sitename"> http://catedralaltapatagonia.com/invierno/partediario.php? default_tab=0
</p>
function codeAddress(){
var elem = document.getElementById("sitename");
elem.value = "http://catedralaltapatagonia.com/invierno/partediario.php? default_tab=0";
var path =$('#sitename').val();
requestCrossDomain(path, function(results){
$('#container').html(results);
});
return false;
};
</script>
</body>
</html>
And my cross-domain-request.js:
/ JavaScript Document
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + 'http://catedralaltapatagonia.com/invierno/partediario.php?default_tab=0' + '"'+' AND xpath="//*[#id=\'meteo_recuadro\']"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, function(data){
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
});
}
Some clue to resolve it?
You appear to have an error in your external JS file, and it's not running. The final else statement is not correct. Try this:
/ JavaScript Document
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + 'http://catedralaltapatagonia.com/invierno/partediario.php?default_tab=0' + '"'+' AND xpath="//*[#id=\'meteo_recuadro\']"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, function(data){
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else {
throw new Error('Nothing returned from getJSON.');
}
});
}
I add the line
<script src="js/cross-domain-request.js"></script>
and the js is loaded

Get data (json format) from another domain without jsonp

How can i get data (json format) from another domain?
My problem is: I want to get data from: http://pin-codes.in/api/pincode/400001/
I have tried to use CORS but it didn't work.
My console is:
GET http://pin-codes.in/api/pincode/400001 [HTTP/1.1 200 OK 780ms]
Error Error
My code by client-script:
$(document).ready(function() {
$("#get_data_btn").click(function() {
var data_path = "http://pin-codes.in/api/pincode/400001";
$.getJSON(data_path, null)
.done(function(data) {
console.log("Success: " + data.status);
})
.fail(function(jqxhr, textStatus, error) {
console.log("Error Error");
});
});
});
You probably don't own the other domain right?
No problem at all. Never mind nay-sayers, in computing everything is a yay!
Just use a simple proxy on your server or look into YQL.
this simple query will work:
select * from json where url="http://pin-codes.in/api/pincode/400001/ "
Just test this link (bypassing cross-domain security bull$#!7).
It will get the data you requested as normal plain json (no jsonp) data wrapped in callback-function cbfunc.
Have a look at this question for further info (I did quite a lot of yql scrape answers on SO).
Update:
Here is a crude fiddle demonstrating the whole process: so you enter a url, click fetch and watch the magic happen: http://jsfiddle.net/NbLYE/
function getJSON(url) { //quick and dirty
var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(script);
}
function cbfunc(json){ //the callback function
if(json.query.count){
var data=json.query.results.json;
// do your work here, like for example:
//document.getElementById('output').innerHTML=data.toSource();
} else {
alert('Error: nothing found'); return false;
}
}
function fetch(url){ //scrape the url you'd want
var yql="select * " +
" from json" +
" where url='" + url + "';";
yql="http://query.yahooapis.com/v1/public/yql?q=" +
encodeURIComponent(yql) +
"&format=json" +
"&callback=cbfunc";
getJSON(yql);
}
That should get you started (and motivated that it is easy).
Hope this helps!
You don't have the correct CORS headers on your server.
You need to add
Access-Control-Allow-Origin: *
(or something similar) server-side to the response.
Edit: From the HTTP response, it appears you are using PHP. Use the header function in your response.
<?php header('Access-Control-Allow-Origin: *'); ?>
You can't do it using jquery only, you can use any server side script like PHP
Try using php,
<?php
echo file_get_contents('http://pin-codes.in/api/pincode/400001');
?>
Save above code in pincode.php and use jquery like,
$(document).ready(function() {
$("#get_data_btn").click(function() {
var data_path = "pincode.php";
$.getJSON(data_path, null)
.done(function(data) {
console.log("Success: " + data.status);
})
.fail(function(jqxhr, textStatus, error) {
console.log("Error Error");
});
});
});
Also read this

Categories

Resources