Jump to content

Spunky

Members
  • Posts

    344
  • Joined

  • Last visited

Posts posted by Spunky

  1. One more question though, in regards to this process.

    $stored_houses = fopen("stored_houses.json","a");$store_data = array("location" => $latlng, "address" => $address);fwrite($stored_houses,json_encode($store_data));fclose($stored_houses);

    This is the PHP used to save the data to the JSON file to begin with. It doesn't include the beginning or end tag stuff I had to add to make the retrieving work (including the comma between the two sets but I know that is easy enough). Would I need to retrieve the data and rewrite all of it to the file every time a new entry is added in order to include the stuff the code above does not include? Does this tedius process make using a JSON file not ideal for the purpose I am using it?

     

    For example, now when I add a new entry, this is what the file looks like:

    {"houses":[{"location":"41.5200305, -88.20172930000001","address":"Shorewood, IL"},{"location":"41.617222, -88.20277799999997","address":"Plainfield, Il"}]}{"location":"41.5894752, -88.057837","address":"Lockport, IL"}
  2. There must be more code that you're not showing. If you put that code right between <script> tags it will work.

     

    If it's inside a function, you have to make sure that the function is being called at some point.

     

    Must have been something wrong with the cache, it is working today. Thank you for your help.

  3. Contents of JSON file:

    {"houses":[{"location":"41.5200305, -88.20172930000001","address":"Shorewood, IL"},{"location":"41.617222, -88.20277799999997","address":"Plainfield, Il"}]}

    Code to retrieve:

    $.getJSON("stored_houses.json", function(data){   alert(data.houses[0].address);});

    Nothing happens when the code runs. No errors.

  4. Also, the request is made asynchronously. This alert

    alert(stored_houses[0].address)

    will fail as it will get executed immediately (and at best introduce as race condition), so you have to do all your work with the response data within the callback function instead (like you are already doing)

     

    That is good to know, thank you. I will need to make sure I set the variables within the function.

     

    In your case, data is just a string. To convert it to a Javascript object you can use JSON.parse().

    stored_houses = JSON.parse(data);

    jQuery has a method that automatically parses JSON received from a request. http://api.jquery.com/jQuery.getJSON/

     

    So I ultimately got this to work sort of with the following code:

    $.getJSON("stored_houses.json", function(data){  alert(data.address);});

    The alert alerts the address data from the first entry of the JSON, but how do I alert data from the 2nd? data[0].address doesn't alert the same thing, instead gives an error that it is undefined.

  5.  

    Perhaps using + as both the addition operator and concatenation operator was a bad design choice.

     

    AngularJS doesn't allow functions inside expressions, but I did a bit of research and you can use a multiplication to cast the values to a number

    <div id="price">{{size*1 + cheese*1 + sausage*1}}     </div>

    I tried this, but I found that if the checkboxes weren't selected their values were being interpreted as NaN, so I added a small expression to make sure that if it wasn't a number it would evaluate to zero.

     

    Here's the end result which appears to work for all cases. I added the "currency" filter so that the number would always have two decimal digits.

    <div id="price">{{(size*1 || 0) + (cheese*1 || 0) + (sausage*1 || 0) | currency}}</div>

    Thank you, this works, yes perhaps it was a bad choice. Javascript has always used + for both addition as well as concatenation depending on it is a number or a string, I can't imagine why it isn't registering the values as numbers. Also thank you for the filter tip.

  6. http://plnkr.co/edit/yAf74IGjzullthF1F5oJ?p=preview

     

    That code in Plunker works exactly how I want it to, it adds the 2 values (.25 + .25) together to make .5.

     

    Can anyone tell me what the difference is between that code and this code?:

    <div id="form" data-ng-app="pizzaOrdersApp" ng-controller="priceCtrl">   <div class="selectionBox">      <h2>-Select Size-</h2>      <div id="optionsAreaTop">         <label class="labelSize" for="Small"><input type="radio" ng-model="size" value="3.95" />Small $3.95</label>	 <label class="labelSize" for="Medium"><input type="radio" ng-model="size" value="5.95" />Medium $5.95</label>	 <label class="labelSize" for="Large"><input type="radio" ng-model="size" value="7.95" />Large $7.95</label>      </div>   </div>   <div class="selectionBox">      <h2>-Toppings-</h2>      <div id="optionsArea">         +$.25 each<br />         <label for="Cheese"><input type="checkbox" ng-model="cheese" ng-true-value=".25" ng-false-value="0" />Cheese</label>	 <label for="Sausage"><input type="checkbox" ng-model="sausage" ng-true-value=".25" ng-false-value="0" />Sausage</label>	 <label for="Pepperoni"><input type="checkbox" ng-model="pepperoni" ng-true-value=".25" ng-false-value="0" />Pepperoni</label>	 <label for="GreenPepper"><input type="checkbox" ng-model="greenPepper" ng-true-value=".25" ng-false-value="0" />Green Peppers</label>	 <label for="Onion"><input type="checkbox" ng-model="onions" ng-true-value=".25" ng-false-value="0" />Onions</label>      </div>   </div>   <div id="redFiller"></div>   <div id="display">      <h3>Your Pizza:</h3>      <div id="topArea">         <div id="currentOrder">            <div id="orders">               <span id="defaultText">Your Order</span>            </div>            <hr />                	            <div id="price">               {{size + cheese + sausage}}  	            </div>

    Clicking each radio/checkbox makes the values appear but they are not added together, instead they appear one after another (3.95.25.25).

  7. Hi, I am attempting to get data from a .json file located on the server. Below is the code a that is not working. I know I can read from a .json file using PHP but when I learned that it can be done with JQuery I figured it would be less hassle than retrieving the data from a .php file.

     

    The data on stored_houses.json was entered via PHP as a json array and it is confirmed to contain data.

     

    The two alerts in the $.get function output: object Object

     

    The error I get in the JavaScript console is: Uncaught TypeError: Cannot read property '0' of undefined for the 3rd alert.

    var stored_houses;$.get("stored_houses.json", function(data){	alert(data);	stored_houses = data;	alert(stored_houses);});		alert(stored_houses[0].address)

    Contents of stored_houses.json file:

    {"location":"41.5200305, -88.20172930000001","address":"Shorewood, IL"}
  8. There's probably an error message on the console. Although, why not just set the value in the HTML when you create the element?

     

    Lol I do not know. Doh! But it worked so thanks. :)

     

    Oh and I forgot to mention that there was no error on the console. Usually I think of it cuz there is an error but this time there wasn't. It just, did nothing.

  9.  

    If you're getting a PHP error, show the entire contents of the PHP file so we can see where it is. It's probably a simple mistake like a missing semi-colon.

     

    If you're getting a Javascript error, for debugging you can check the value of xmlhttp.responseText without parsing it.

    try {    var data = JSON.parse(xmlhttp.responseText);} catch(e) {    // If it' not working, debug by checking the responseText    alert(xmlhttp.responseText);}

     

    Ran that code and yes, the alert contains the proper value. It displays the array in JSON format. So what does this tell me?

  10. var contentString = '<div id="infoContent">'+					'<strong>'+address+','+price+','+'Mortgage: '+mortgage+' Taxes: '+taxes+' Year: '+year+'</strong>'+					'#<span id="number">'+house_number+'</span>'+					'</div>'+					'<a href="#edit"><span onClick="editDetails()">edit</span></span>';					house_number++					return contentString;}

    This code is returned to a function that creates a Info Window in a Google Map to appear when the user clicks on a marker on the map. The next set of code is what editDetails() does.

    function editDetails(){		var data_edit = "<div id="houseDetails">";	data_edit+=		"<div id="details">";	data_edit+=		"<h4>Details</h4>";	data_edit+=		"Price:<input type="text" id="price" value="" class="boxsize">";	data_edit+=		"Mortgage:<input type="text" id="mortgage" value="" class="boxsize">";    data_edit+=		"</div>";	data_edit+=		"</div>";		document.getElementById("data_edit").innerHTML = data_edit;	document.getElementById("data_edit").style.display = "block";	document.getElementById("new_address").style.display = "hidden";	thishouse = document.getElementById("number").innerHTML;	  	document.getElementById('price').value = "hi";  	document.getElementById('mortgage').value = myhouses[thishouse].mortgage;}

    All those input textboxes appear and then I am attempting to change the value in the textboxes. The first one shows:

    document.getElementById('price').value = "hi";

    Just as a test because I am otherwise not sure why it is not working. If I alert:

    myhouses[thishouse].mortgage

    The expected value does appear, so that is not an issue. The issue is, why does the value not change?

  11. How about this?

    echo json_encode($row);

    That's it, just pass the array itself. No string concatenation or anything.

    The $row variable you're getting is an array.

     

    OH. That was said before but I thought it was just a generalization that I'd send the $row information, thought to myself well I'm sending a lot of stuff...But I get it, $row is an array of ALL the data and by saying $row['location'] I am just specifying which piece in the array I am using.

     

    Ok so, tried it, get the error:

     

    Uncaught SyntaxError: Unexpected token { index.html:1

     

    Doesn't say much, I tried adding:

    echo json_encode($row) or die(mysql_error());

    To try and see the error I might be getting. I alerted the variable on the other end that retrieves the data:

    var data = JSON.parse(xmlhttp.responseText);alert(data);

    And I get the alert 1111 (with the 'or die' bit, no alert occurs, just that error). Not sure what that is about. I checked my PHP error logs, nothing there.

  12. Alright well I seem to be missing some tidbit of how to format the PHP. You say I don't have to manipulate it in any way but I must need to initially set it up for sending. This is what I have and I still cannot get it to work.

    $data = $row['location'] . $row['address'] . $row['price'] . $row['mortgage'] . $row['numBeds'] . $row['numBaths'] . $row['taxes'] . $row['year'] . $row['house'] . $row['livingRoom'] . $row['kitchen'] . $row['bedroom1'] . $row['bedroom2'] . $row['bedroom3'] . $row['bedroom4'] . $row['bedroom5'] . $row['fenced'] .$row['basement'] . $row['garage'] . $row['notes'];echo json_encode($data);

    ^ This is my code without commas or asterisks.

    If you're using json_encode then don't use commas or asterisks. Just give the array as it is. PHP converts the array into a format that Javascript can read.

     

    I think what I am missing is "the array" for PHP to convert. I never had this data in an array originally. Right now I've been passing over a string. Am I suppose to put it in a PHP array? Use PHP to write a JSON object?

     

    The way I send it with commas an asterisks gives JavaScript a way to split it into an array. Otherwise I'm lost.

  13. Which line does the error appear on?

     

    Are you certain that saveLatLng is a string and not something else?

     

    Ok so I used toString() to make it a string first if it wasn't and the code works, thank you again. :good:

     

    Shine some light for me first though..

    var address = document.getElementById('address').value;  geocoder.geocode( { 'address': address}, 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,      });	  	  saveLatLng = results[0].geometry.location;

    This is the code where the variable originates. The user input is text. saveLatLng is numbers. Is it then an integer by default? Therefore making it not a string?

  14. saveLatLng = results[0].geometry.location;chop = saveLatLng.slice(1, -1);alert(chop);

    With the above code, I get an error for the second line: Uncaught TypeError: undefined is not a function

    saveLatLng = results[0].geometry.location;chop = saveLatLng.substr(1);alert(chop);

    With this code I get same type of error. Why??? I'm just trying to trim off the first and last character (I realize the above code with their current parameters won't succeed but right now I'm trying to see what exactly the snippet will do). Right now saveLatLng is something like this: (43.049586, -88.04959684). I don't want the parentheses around it, so I'm just trying to shave it.

  15. This is great, thanks. Could you help me understand the parse and encode? I mean, I have the code working just fine without it:

          while ($row = mysql_fetch_assoc($result))      {	echo $row['location'] . '*';

    (used a asterisk instead because there are already commas in the data)

    retrieve = xmlhttp.responseText.split("*");alert(retrieve[0]);alert(retrieve[1]);

    Does it perfectly. When I research json_encode though to understand it further, I get stuff about sending an array from PHP to JavaScript etc, but it seems to work without it?

     

    Anyway I wasn't able to get it working with my attempt but I am probably not doing it right...

    retrieve = JSON.parse(xmlhttp.responseText.split("*"));alert(retrieve[0]);alert(retrieve[1]);
          while ($row = mysql_fetch_assoc($result))      {	$myRow = $row['location'] . '*';	echo json_encode($myRow);

    I get the error: Uncaught SyntaxError: Unexpected string index.html:1

     

    It's working without so I am happy, but if there is a proper way to do this or problems that could result from it, I'd like to make sure I'm doing it right. :dirol:

  16. I'm trying to retrieve data from a database and be able to utilize it in JavaScript. I'd finally found a way to send info from JavaScript to PHP to place it in my database using AJAX, and I am attempting to use the same strategy to retrieve it. This is what I have so far:

        xmlhttp.onreadystatechange = function() {    	if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {    		retrieve = xmlhttp.responseText;			alert(retrieve);    	}    }		xmlhttp.open("GET","loadAddress.php?",true);	xmlhttp.send();

    The alert successfully alerts the content of multiple rows from the database. Ultimately I want to be able to individually use the rows in a JavaScript function, all the same thing, so if I could get each row into an array, I'd be able to loop through it, individually placing them in the function. I'm stuck how to proceed from here.

    echo $row['location'];

    The PHP echos the rows, which is the only way I know how to get it to the JavaScript onreadystatechange function, perhaps there is another way I need to do? I'm just stumped how to proceed.

  17. Based on my reading here: http://www.w3schools.com/sql/sql_injection.asp

     

    I attempted to change:

    $query= "INSERT INTO houses (location) VALUES ('$location)";mysql_query($query) or die(mysql_error());

    (which works) into this:

    $query= $dbh->prepare("INSERT INTO houses (location) VALUES (:loc)");$query->bindParam(':loc', $location);$query->execute();mysql_query($query) or die(mysql_error());

    The code doesn't work. I am not sure if I translated correctly how to add "parameters" to the code to protect against SQL injection.

  18. Is the database field of type INT?

     

    Try printing out the value instead of adding it to the database to see what you're getting. Use the network tab of the browser's developer tools to see what is being sent and what it being received.

     

    It is an INT yes. Or wait, is that a problem because of the comma between the numbers? Hmm.

     

    When I try to use echo after the GET line in PHP, nothing appears on the screen. I'm not sure why.

    echo '<p>Location:' . $location . '</p>';
  19. Taking from a tutorial I found here: http://www.w3schools.com/php/php_ajax_database.asp

     

    I created the following code:(the code from link example is in function saveAddress)

    var geocoder;var map;function initialize() {  geocoder = new google.maps.Geocoder();  var latlng = new google.maps.LatLng(-34.397, 150.644);  var mapOptions = {    zoom: 8,    center: latlng  }  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);}function saveAddress(str){	 if (str == "") {        alert('Please enter an Address');        return;     } else {         if (window.XMLHttpRequest) {            // code for IE7+, Firefox, Chrome, Opera, Safari            xmlhttp = new XMLHttpRequest();        } else {            // code for IE6, IE5            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");        }        /*xmlhttp.onreadystatechange = function() {            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;            }        }*/		alert(str);        xmlhttp.open("GET","saveAddress.php?location="+str,true);        xmlhttp.send();    }}function codeAddress() {  var address = document.getElementById('address').value;  geocoder.geocode( { 'address': address}, 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,      });	  	  saveLatLng = results[0].geometry.location;	  saveAddress(saveLatLng);	      } else {      alert('Geocode was not successful for the following reason: ' + status);    }  });}google.maps.event.addDomListener(window, 'load', initialize);

    I commented out part of the AJAX because I wasn't sure what else to do with it, I didn't need the link inside that if statement so I got rid of it altogether.

     

    The real issue however is the php file retrieving the request.

    $location = $_GET['location'];

    I tried getting rid of intval because I didn't need it converted to an integer. But it still gives me a 0 (I have it being placed into a table on a database). Honestly though I am a little confused on that part of the code in the example on what it is even doing there, how it is retrieved if it is turned into a '0'.

     

    The last time someone suggested using error_log() when I had a PHP problem but I couldn't figure out where my server's error log is...so if we need that to debug this I am going to need help figuring out how to find that. :boredom:

  20. If you read the post you just quoted, you'll notice that I didn't use innerHTML there. The string is being built first in the variable "prompt_div".

    Not true. I did read the post and I did NOT notice that. Trick of the eyes that is, good assumption tho. I see the difference now.
  21. I would suggest you build the complete string and then use innerHTML once.

    That's not what this guy suggested from another post with a different issue of mine.

    You can use double-quotes, just be sure to escape them with "

    You could break the string into pieces to make it more readable.

    var prompt_div = "<div id='genderCheck'>";prompt_div += "<h4>First of all, select your gender:</h4>";prompt_div += "<input type='radio' name='gender' value='male' onClick='userprompt("male","");'> Male";prompt_div += "<input type='radio' name='gender' value='female' onClick='userprompt("female");'> Female";prompt_div += "</div>";prompt_div += "<div id='ageCheck'>";prompt_div += "<h4>Now a bit more..</h4>";prompt_div += "<input type='radio' name='age' value='adult' onClick='userprompt("","adult");'> Adult";prompt_div += "<input type='radio' name='age' value='child' onClick='userprompt("","child");'> Child";prompt_div += "</div>";prompt_div += "<div id='textPrompt'>";prompt_div += "<h4>Great! Now, go ahead and type a response to your fellow classmates:</h4>";prompt_div += "<textarea id='userResponse'>Type here...</textarea>";prompt_div += "<button type='button' onClick='submitResponse();'>Enter</button>";prompt_div += "</div>";

    Usually, rather than making Javascript to write all this, it's already on the page and you just use CSS and Javascript to make it appear or disappear.

     

    Doing it this way solved an issue with sending parameters with the functions that ran onClick. I had no problems once I implemented this code. I'm just not sure if this is a slightly different circumstance this time that something is acting weird. I don't have parameters to send but I still used this method to keep it more readable, as suggested. I wasn't sure if maybe it had to do with now I have span and p tags I don't know.

  22. Can anyone tell me why the code below:

    var swapTxt = document.getElementById('first_div');	swapTxt.innerHTML="<div id='second_div'>";	swapTxt.innerHTML+="<p>Text</p>";	swapTxt.innerHTML+="<p>More text</p>";	swapTxt.innerHTML+="<p><span>One</span>";	swapTxt.innerHTML+="<span>Two</span>";	swapTxt.innerHTML+="<span>Three</span></p>";	swapTxt.innerHTML+="<p><span>One</span>";	swapTxt.innerHTML+="<span>Two</span>";	swapTxt.innerHTML+="<span>Three</span></p>";	swapTxt.innerHTML+="<p><span>One</span>";	swapTxt.innerHTML+="<span>Two</span>";	swapTxt.innerHTML+="<span>Three</span></p>";	swapTxt.innerHTML+="</div>";

    Outputs this HTML:

    <div id="first_div">  <div id="second_div"></div>    <p>Text</p>    <p>More text</p>    <p><span>One</span></p>    <span>Two</span>    <span>Three</span>    <p></p>    <p><span>One</span></p>    <span>Two</span>    <span>Three</span>    <p></p>    <p><span>One</span></p>    <span>Two</span>    <span>Three</span>    <p></p>  </div></div>

    I'm pretty stumped here, this is basic stuff I've done before and I don't understand why it is acting up so.

  23. One last thing. Using media queries to show a webpage differently for mobile devices, how would I give the user the option to view the site normally? Is there a way to change the meta tag to remove "viewport"?

     

    I suppose the real issue is being able to control when viewport is enabled. Like, I only want a mobile version for small devices such as smartphones and maybe even smaller tablets. I wouldn't want the screen to not zoom out to exactly the screen size if someone is on a larger tablet and then have to accommodate that screen size.

     

    So far what I have put in is

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    On my smartphone, it doesn't zoom out so only shows 360px of the web page (exactly what it is suppose to do) but the problem is that I can still scroll from side to side and certain parts of the web page are still visible beyond the 360px while everything else is cut off. Since I am going to style it to not go beyond a certain amount of pixels this isn't a huge issue, but I would like to understand why certain parts are still visible.

×
×
  • Create New...