Jump to content

Drongo_III

Members
  • Posts

    579
  • Joined

  • Last visited

Posts posted by Drongo_III

  1. Hi Guys

     

    Quick question. I am trying to write a sort of multi purpose validation function (just for simple forms).

     

    I want to pass a dynamic value to the length part of the regular expression patterns below. I can get this to work for the 'tstring' case in the switch statement (i.e. where i pre-concatenate the values). But if i use complex syntax and then try to pass the values separately ( as in 'tint'  case below) i can't seem to get it to work. Is it possible to do? Or do i need to pre-concatenate first?

     

    Thanks chaps!

     

    function call looks like:

    $validate->multiVal($_POST['name'], 1, 6, 'tstring');
    

     

    Actual function:

    public function multiVal($subject, $lenMin, $lenMax, $type){
    
    	$length = $lenMin . "," . $lenMax;
    	switch($type){
    
    		case 'tstring':
    		$pattern = "/^[a-zA-Z\s\b]{{$length}}$/";
    		break;
    
    		case 'tint':
    		$pattern = "/^[0-9]{{$lenMin}, {$lenMax}}$/";
    		break;
    
    
    	}
    
    
    	preg_match($pattern, $subject, $matches);
                     // check results and return true or false
    	}
    

  2. Don't know if the case of your query makes any difference but as a long shot you could could change the WHERE clause so that it actually says "AND password=' " instead of "and password=' "

     

    Maybe...

     

    Edit: scratch that...they aren;t case senstive :)

  3. Are you quite sure your connection is working?

     

    or

     

    Are you sure there isn't  more than one row in your table that matches your criteria? Therefore your $result actually contains 2+? Because you're specifically looking for 1 in your if statement.

     

    To test that you could just do:

     

    if($count >0){
    
    }
    

     

    or

     

    Are you quite sure your password is actually stored as an MD5?

     

    Just a thought.

  4. Out of interest... Why do you suggest loading the xml using curl first? Is there some advantage to just straight loading it using simplexml_load_file?

     

     

     

    on another tack, using the RSS

     

    
    $output = curl_get_contents('http://www.weatheroffice.gc.ca/rss/city/on-94_e.xml');
    $xml = simplexml_load_string($output);
    
    echo $xml->channel->item[0]->title. '<br /><br />';    //=> No watches or warnings in effect, Windsor
    echo $xml->channel->item[1]->title. '<br /><br />';    //=> Current Conditions: Cloudy, 15.1°C
    
    

  5. Ok, been doing some practice on JS regular expressions and I'm getting stuck :/

     

    Why do the patterns below return false?

     

    
                                      var str = 'first sentence';
    			//var pattern = new RegExp('^[a-zA-Z]{5,6}\s'); //FALSE
    			//var pattern = new RegExp('^[a-zA-Z]{5,6}\b'); //FALSE
    			//var pattern = new RegExp('^[a-zA-Z]{5,6} '); //TRUE
    			   var pattern = new RegExp('^[a-zA-Z]{5,6} s'); //TRUE
    
    			var result = pattern.test(str);
    			 //alert(1);
    			document.getElementById('para').innerHTML = result;
    
    

     

    I don't understand why the first two return false. To my (increasingly shakey) understanding of regex the patterns that return false should be true. For instance i interpret the following pattern as follows:

     

    var pattern = new RegExp('^[a-zA-Z]{5,6}\b');                    
    

    Start the beginning of string (^), match any a-z characters of any case - specifically matching 5-6, then match a word boundary. Which to me should match 'first ' in var str above.

     

    So is it simply a case that you should always match spaces as literals or am i reading the regex incorrectly?

     

     

  6. Woah! Both very helpful but esepcially big thanks to josh for taking the time to go into such detail.

     

    I did realise my ignorance in using square brackets shortly after posting - mostly because i was a bit brain fried from working on something all day and i only really use regex once in a blue moon.

     

    But I had no idea javascript  regex object didn't  use a pattern delimeter and i definitely didn't realise the distinction between explicitly creating a regex object and an object literal - so i am very, very glad i asked guys.

     

    I think i'll spend some time  on regex this evening!

     

    PS don't make this a sticky! not sure i want my noob question immortalised lol  ;D

  7. Hi Guys

     

    I am not quite sure what I'm doing wrong here as when I run this match in php using preg_match I get the expected result returned - but in JS it's just giving me 'false'.

     

    I want to match the end of the string below for the suffix .html - but everytime i test it i get 'false' returned.

     

    
            var str = 'http://localhost/TESTJS.html';
    var pattern = new RegExp('/[\.html]+$/');
    
    var result = pattern.test(str);
    alert(result);
    
    

     

    Any enlightenment on where i am going wrong would be hugely appreciated :)

  8. Hi Guys

     

    I am having my first trip into the worlds of google maps api v3.

     

    This far I can generate a map based off a location lookup. This is all just rough to test things out (see code below).

     

    What I am really stuck with is how to get the geocoding to work.

     

    All I want to do is geocode an address and display the new marker on my map. But i can't even get google's example to work :/ Can anyone propose a way to make this work with my little bit of code below?

     

    I've been at this for about four hours so any help would be appreciated  :'(

     

    Google's example code

    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': 'london' }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
    

     

     

    My Code

    <!DOCTYPE html>
    <html>
      <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <style type="text/css">
          html { height: 100% }
          body { height: 100%; margin: 0; padding: 0 }
          #map_canvas { height: 100% }
        </style>
        <script type="text/javascript"
          src="http://maps.googleapis.com/maps/api/js?key=XXXXXX&sensor=true">
        </script>
        <script type="text/javascript">
    
    // Innitiate call to get coords
    
    	function getLoc(){
    
    		navigator.geolocation.getCurrentPosition(getCord, errorFunc, {enableHighAccuracy: true});
    
    	}
    
    	// Position check was successful - therefore set vars and call map
    	function getCord(position){
    
    		var lat = position.coords.latitude;
    		var longe = position.coords.longitude;
    
    		initialize(lat, longe);
    
    	}
    
    	// Report error when finding coords
    	function errorFunc(error){
    
    	var error = error.code;
    
    	alert(error);
    	}
    
    
    
    // Initialise the Google Map
          function initialize(lat, longe) {
           
    
    	var lat = lat;
    	var longe = longe;
    
    	var mapOptions = {
    
              center: new google.maps.LatLng(lat, longe),
              zoom: 8,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
    
            var map = new google.maps.Map(document.getElementById("map_canvas"),
                mapOptions);
    
    	var marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat, longe),
            map: map,
    	title: 'tester'
    
          });
      
    
          }
      
       
      
    	  
        </script>
      </head>
      <body onload="getLoc()">
        <div id="map_canvas" style="width:100%; height:100%"></div>
      </body>
    </html>

  9. Hmm well after much messing around with this I've found that if I set the accuracy arg to 'true' (default being false) then it finds my coords. The only problem is that using high accuracy initialises the gps on the phone, which takes around 30-40 seconds.

     

    Anyway posting this in case it helps someone.

     

    navigator.geolocation.getCurrentPosition(successFunction, errorFunction, {
            enableHighAccuracy: true});
    

  10. Hi Guys

     

    I've been playing around with navigator.geolocation.getCurrentPosition etc.

     

    I've written a very basic test script (below). At the moment I am just playing around to get familiar with it before i try something more sophisticated.

     

    But I've hit an issue with it and I'm unsure of how to proceed.  Basically I've tested the script/page below on two mobiles - both running android.

     

    On the more modern phone the browser throws up a prompt asking "do you want to give www.XXXXX.com  permission to access to your location?" - hitting the "accept" button then renders out the coords as expected. Great!

     

    However, on the other android phone (which is a little older but has google navigator and maps on it so is enabled), I get no prompt for permission and instead an error message is thrown with code 2 - which according to w3c spec. corresponds to:

     

    "POSITION_UNAVAILABLE (numeric value 2)

        The position of the device could not be determined. For instance, one or more of the location providers used in the location acquisition process reported an internal error that caused the process to fail entirely. "

     

    So I was wondering if anyone had encountered this type of issue and how they fixed it?

     

    It seems to me the reason why it's going to code 2 is because the script doesn't have permission to share location data. But i don't know if, or how, you can specifically seek permission.

     

    Any help would be much appreciated!

     

    Drongo

     

     

     

     

    <script src="jquery1.8.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    
    $(document).ready(function(){
    
    	if(navigator.geolocation){
    
    		navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
    	}
    
    else{	
    	$('#location').html("Geolocation not supported ");
    }
    
    	   
    // Success Function to obtain coords	
    function successFunction(position) {
    
    
    		var lat      = position.coords.latitude;
    		var longe = position.coords.longitude;
    		$('#location').html("This is your lat " +  lat + " and this is your long " + longe);
    
    	}
    
    // Fail function - outputs error code
    	function errorFunction(error){
    
    		var error = error.code;
    		$('#location').html("The error code is " + error);
    
    	}
    
    });
    
    </script>
    

  11. Yeah I know what you mean. That's one thing I've learned - programming is very much a mindset. And very often you solve problems by stepping back and trying to logically think "what's actually going on as this executes..." and then suddenly you have an 'AHA!' moment and realise the issue.

     

    Definitely something i can relate to as i have a long way to go on my web development journey hehe...

  12. As far as my logic extends (which on most days isn't that far haha) i believe that snippet of code checks to see if your currency is set in the post array, if not, it will check to see if the currency is session variable is set. If it's not set it will apply the default value of gbp - otherwise it assumes the currency session is set and therefore does nothing.

     

    If you think your forms aren't posting try doing:

     

    print_r($_POST);
    

     

    at the top of your page. This will display everyting in the post array (again, sorry if i am telling you anything you know). I just tested your form though and it worked perfectly for me.

  13. Sorry dipping into this thread so excuse me if the answer is wrong.

     

    But it sounds like you're assuming the form for currency is posting directly to a session variable, which doesn't happen.

     

    So it sounds like you need a middle step:

     

    
    //Check is the user has submitted a new currency
    
    if(isset($_POST['currency'])){
    $_session['currency'] = $_POST['currency'];  
    }
    
    //If the user hasn't changed the currency check if the currency isset, if not, use default value of gbp
    else if(!isset($_session['currency'])){
    $_session['currency'] = "GBP";
    }
    
    

     

    Typing this directly into the browser so apologies if anything is typoed!

     

    Also, and you probably know this, make sure you have session start at the top of each subsequent page to preserve and make accessible the session across pages.

     

  14. Thanks ChristianF - looks like i've invented resonseJson then  :D

     

    The reason I thought a library might be preferable was because then you wouldn't rely on the browser to decode - instead the library would ensure that the decoding would work. But I could be wrong on this. Does that make sense as an approach to ensure legacy browsers still work?

     

     

     

     

    1. [*]As far as I'm aware there is no
    http.responceJSON attribute, only http.responseText, when working outside of any frameworks.

    So decoding the string with a JSON parser is indeed the correct approach.

    [*]A browser either supports JSON parsing, or it doesn't. If it doesn't then you get a catchable exception, in which case you can use a failsafe method. Libraries doesn't really enter into the equation ant this point, except for the fact that they tend to handle the error caused by a missing JSON parser.

     

    Relying on a library, or not, is a decision which requires considerations of a lot more points that just JSON parsing. That said, it is generally recommended to use one (like jQuery) if you need to do a lot of DOM manipulation and AJAX calling. Simply because it lessens the workload on you, mostly due to the fact that most/all of the browser incompatibilities are handled automatically.

    If you need only a few simple AJAX calls, or some other trivial functionality, then it can be advisable to forgo the library. It's all a judgement call, really.

  15. HI Guys

     

     

    Couple of questions:

     

    1) When working with ajax in 'raw' javaScript (i.e. not jquery), if the response from the server is going to be in Json format do you need to make the onreadystate response:

     

    http.responseJson
    

     

    Or since the json is essentially a string do you just do get request 'responseText' and then decode the string using json parser.

     

    Which brings me to question two!

     

    2) Is it ok to rely on native browser support to decode jason - i.e. using:

     

    var myObject = JSON.parse(myJSONtext);
    

     

    Or is this a bad idea if someone is using an older browser? And is it therefore better to rely on a library instead?

     

    Many thanks

     

    Drongo!

     

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.