How to limit a string character count in jquery - php

I'm trying to send this text Montréal-Pierre Elliott Trudeau International Airport, Montreal, QC, Canada through a Ajax post to a php script. I'm getting a 500 (Internal Server Error) when trying to send all the characters in the text.
When I tried 'Montréal-Pierre-Elliott-Trudeau-International' by handcoding, it worked.
Here is my ajax script
$("#nomination-name").focus(function(){
$.post(
'/getlocation/'+$("#newLatitude").val()+"/"+$("#newLongitude").val()+"/"+'ok', // location of your php script
{ place: 'Montréal-Pierre-Elliott-Trudeau-International'}, // any data you want to send to the script
function( data ){ // a function to deal with the returned information
$(".flickr-images").remove();
for(i=0;i<data.images.length;i++) {
$("#images").append(data.images[i]);
}
});
});
Here is the server script:
public function getLocationImage($latitude, $longitude, $cc){
//$place = 'Montreal, Pierre, Elliott, Trudeau, International, Airport';
//GET THE IMAGES BASED ON THE LOCATION FROM FLICKR.
$api_key = 'my_api_key';
$text = Input::get('place');
// $text = 'airport';
$lat = '&lat='.$latitude;
$lon = '&lon='.$longitude;
$perPage = 6;
$url = 'https://api.flickr.com/services/rest/?method=flickr.photos.search';
$url.= '&api_key='.$api_key;
$url.= '&text='.$text;
// $url.= $lat;
// $url.= $lon;
$url.= '&per_page='.$perPage;
$url.= '&format=json';
$url.= '&nojsoncallback=1';
$response = json_decode(file_get_contents($url));
$photo_array = $response->photos->photo;
$count=0;
foreach($photo_array as $single_photo){
$size = 's';
$size2='b';
$photo_url = 'https://farm'.$single_photo->farm.'.staticflickr.com/'.$single_photo->server.'/'.$single_photo->id.'_'.$single_photo->secret.'_'.$size.'.'.'jpg';
$photo_url_big = 'https://farm'.$single_photo->farm.'.staticflickr.com/'.$single_photo->server.'/'.$single_photo->id.'_'.$single_photo->secret.'_'.$size2.'.'.'jpg';
$img[$count] = "<a href='$photo_url_big' target='_blank'><img class='flickr-images' title='' src='$photo_url' /></a>";
$count++;
}
return Response::json(["success"=>"true", "images"=>$img]);
}
I'm trying to remove the space and commas in a string and limit it's count to 20. I tried the following method but is not right.
$('#geocomplete').val().replace(/[, ]+/g, "-").substr(20, $('#geocomplete').val().replace(/[, ]+/g, "-").length)
Is this the right way?

You need to encode the parameter:
$url.= '&text='.urlencode($text);

var data = $('#geocomplete').val().substr(0,20); //get the first 20 characters
data.replace(/\s+/g, '-'); //replace all spaces with '-'

Related

Google maps failed to open stream Error

I'm uploading a csv file and getting address field in $address variable, but when I pass $address to google maps, its showing me error,
file_get_contents(http://maps.googleapis.com/maps/api/geocode/json?address=9340+Middle+River+Street%A0%2COxford%2CMS%2C38655): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request.
I searched for its solution, I found one that to encode only address but its also not working for me...
CODE
if (!empty($address)) {
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address));
$geo = json_decode($geo, true);
if ($geo['status'] = 'OK') {
if (!empty($geo['results'][0])) {
$latitude = $geo['results'][0]['geometry']['location']['lat'];
$longitude = $geo['results'][0]['geometry']['location']['lng'];
}
$mapdata['latitude'] = $latitude;
$mapdata['longitude'] = $longitude;
return $mapdata;
} else {
$mapdata['latitude'] = "";
$mapdata['longitude'] = "";
return $mapdata;
}
}
Error is at line
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address));
Have I missed anything.!
Any help is much appreciated.. Thanks
you need to use google api key
function getLatLong($address){
if(!empty($address)){
//Formatted address
$formattedAddr = str_replace(' ','+',$address);
//Send request and receive json data by address
$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=false');
$output = json_decode($geocodeFromAddr);
//Get latitude and longitute from json data
$data['latitude'] = $output->results[0]->geometry->location->lat;
$data['longitude'] = $output->results[0]->geometry->location->lng;
//Return latitude and longitude of the given address
if(!empty($data)){
return $data;
}else{
return false;
}
}else{
return false;
}
}
Use getLatLong() function like the following.
$address = 'White House, Pennsylvania Avenue Northwest, Washington, DC, United States';
$latLong = getLatLong($address);
$latitude = $latLong['latitude']?$latLong['latitude']:'Not found';
$longitude = $latLong['longitude']?$latLong['longitude']:'Not found';
To specify a Google API key in your request, include it as the value of a key parameter.
$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=true_or_false&key=GoogleAPIKey');
i hope this will help you.
It looks like the problem is with your data set. The part of the url that is being encoded as %A0 by urlencode($address) is a special non-breaking space character, rather than a regular space.
See here for more information on the difference:
Difference between "+" and "%A0" - urlencoding?
The %A0 character isn't accepted in this context, but you can do a quick str_replace() on the result of urlencode() to replace all these special space characters with the + symbols that regular spaces would have resulted in.
$geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . str_replace('%A0', '+', urlencode($address)));

Looping through CSV and parsing a JSON query using each result

So despite hours of fiddling I cannot understand why my JSON query only returns a result for the last line in the CSV/TXT files I am trying to parse.
Here is the code:
//Enter API Key Here
$api_key = 'AIzaSyB9Dq3w1HCxkS5qyELI_pZuTmdK8itOBHo';
$origin = 'RG12 1AA';
$output_type = 'json'; //xml or json
$csv_location = 'http://www.naturedock.co.uk/postcodes.csv';
//Do not edit
$base_url = 'https://maps.googleapis.com/maps/api/directions/';
$origin_url = '?origin=';
$destination_url = '&destination=';
$end_url = '&sensor=false&key=';
$page = join("",file("$csv_location"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$destination = $kw[$i];
echo $destination;
$raw_url = $base_url . $output_type . $origin_url . $origin . $destination_url . $destination . $end_url . $api_key;
$request_url = str_replace(' ', '', $raw_url);
$getJson = file_get_contents($request_url);
$routes = json_decode($getJson);
$result = $routes->routes[0]->legs[0]->distance->value;
echo $result . '<br>';
}
The result I get looks like this:
Distance by Post Code Generator v0.1 by Phil Hughes
RG12 0GA
RG12 0GB
RG12 0GC
RG12 0GD4066
Where the '4066' is the correct variable for RG12 0GD postcode but none of the others return results as you can see.
Please help.
Your
join("",file("$csv_location"));
concatenated all lines feom the file to a single line without separator. The following explode() sees no newlines any more. So you are working on one line only. count($kw) always evaluates to 1 and your loop runs only one time.

Remove "http://" from URL string

I am using a bit.ly shortener for my custom domain. It outputs http://shrt.dmn/abc123; however, I'd like it to just output shrt.dmn/abc123.
Here is my code.
//automatically create bit.ly url for wordpress widgets
function bitly()
{
//login information
$url = get_permalink(); //for wordpress permalink
$login = 'UserName'; //your bit.ly login
$apikey = 'API_KEY'; //add your bit.ly APIkey
$format = 'json'; //choose between json or xml
$version = '2.0.1';
//generate the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
//fetch url
$response = file_get_contents($bitly);
//for json formating
if(strtolower($format) == 'json')
{
$json = #json_decode($response,true);
echo $json['results'][$url]['shortUrl'];
}
else //for xml formatting
{
$xml = simplexml_load_string($response);
echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}
As long as it is supposed to be url and if there is http:// - then this solution is the simplest possible:
$url = str_replace('http://', '', $url);
Change your following line:
echo $json['results'][$url]['shortUrl'];
for this one:
echo substr( $json['results'][$url]['shortUrl'], 7);
You want to do a preg_replace.
$variable = preg_replace( '/http:\/\//', '', $variable ); (this is untested, so you might also need to escape the : character ).
you can also achieve the same effect with $variable = str_replace('http://', '', $variable )

Amazon API page number not working

I'm trying to fetch a list of results for a search through Amazon API to list products on my website. Everything works except for specifying the page number that I want to retrieve. It always fetches page 1 for some reason.
$SecretAccessKey = "xxx";
$request['AWSAccessKeyId'] = "xxx";
$request['AssociateTag'] = "xxx";
$request['Timestamp'] = gmdate("Y-m-d\TH:i:s\Z");
$request['ResponseGroup'] = "ItemAttributes,Offers,Images";
$request['ItemPage'] = 1;
$request['Service'] = 'AWSECommerceService';
$request['Version'] = '2011-08-01';
$request['Operation'] = 'ItemSearch';
$request['SearchIndex'] = $search['category_name'];
$request['Keywords'] = $search['text'];
$request['Page'] = 5;
ksort($request); // Sorts in order of key
$Prepend = "GET\nwebservices.amazon.com\n/onca/xml\n";
$String = http_build_query($request);
$PrependString = str_replace('+', '%20', $Prepend . $String);
$Signature = base64_encode(hash_hmac("sha256", $PrependString, $SecretAccessKey, True));
$Signature = urlencode($Signature);
$BaseUrl = "http://webservices.amazon.com/onca/xml?";
$SignedRequest = $BaseUrl . $String . "&Signature=" . $Signature;
// Fetch the generated URL
$xml = simplexml_load_file($SignedRequest);
I've tried with $request['Page'], $request['page'], $request['Pages'] and $request['pages']. None seem to work to pull the correct page. Does anyone know what this parameter is supposed to be named?
Turns out it was ItemPage.
$request['ItemPage'] = 5;

How to get user's profile pic url using graph api

Hi i m trying to get url of user's profile pic so I use following code
$userinfo = $facebook->api("/me/picture?type=large");
var_dump($userinfo);
but instead of returning url it returns NULL. Please help me why this is happening.
Thank you.
This is how we can get actual picture url
$URL='FB GRAPH API URL';
$headers = get_headers($URL, 1); // make link request and wait for redirection
if(isset($headers['Location'])) {
$URL = $headers['Location']; // this gets the new url
}
$url_arr = explode ('/',$URL);
$ct = count($url_arr);
$name = $url_arr[$ct-1];
$name_div = explode('.', $name);
$ct_dot = count($name_div);
$img_type = $name_div[$ct_dot -1];
$pos = strrpos($img_type, "&");
if($pos)
{
$pieces = explode("&", $img_type);
$img_type = $pieces[0];
}
$imagename = imgnameyouwant'.'.$img_type;
$content = file_get_contents($URL);
file_put_contents("fbscrapedimages/$imagename", $content);
If you know the [uid], you can simply use the following code
<img src="http://graph.facebook.com/[UID]/picture" />
You can also crop/resize the profile picture by providing height/width parameters.
Eg: https://graph.facebook.com/[UID]/picture?width=140&height=140
If you want to use standard sizes, try
<img src="http://graph.facebook.com/[UID]/picture?type=large" />
where type is one of {square,small,large}

Categories