gmaps.js add marker from PHP array - php

I am trying to add a marker to my gmaps.js map. The long. and lat. values are stored in a database, which I select using a PHP Script.
Once fetched, both of the long. and lat. values are stored in an array, under the variable $data.
I wanted to use json_encode($data); in order to pass the variables, however I would have had to change the header to a json application, I have already echoed some PHP onto the page, therefore this is unfeasable.
I have now tried echoing the json_encode into the jQuery function using an $.each loop, however it has been unsuccessful, as not every entry retrieved by the database will have a marker.
What is the best solution, to get an ID, long. and lat. value for max 10 records, pass this to a jQuery function to position on a map?

As not all records have markers, youll have to parse the results so that only the required data gets passed to your js function. I'd create a php array and add the marker I'd, lat,long etc... Under the same key:
$markersarray = array ()
foreach($records as $record){
if($record['lat'] != ““){
$markersarray[] = array(
'id'=>$record['id'],
'lat'=>$record['lat'],
'long'=>$record['long']
);
}
}
$markersjson = json_encode($markersarray);
Then you could use a hidden input to store the encoded json string which then could be passed into your js.
<input id="markersjson" type="hidden" value="<?php echo $markersjson; ?>"/>
in your js function
var markersdata = $('#markersjson').val();
You may need to parse this value to an object
var obj = jQuery.parseJSON(markersdata);
then use a $.each to loop through your obj

Related

How to get last value of an array input text in JS?

This is my code from controller where I used looping to show this.
<input type="hidden" class="notif_date" value="'.$created_at.'">
the sample data of this are multiple dates: 2019-05-28 13:45:45
Now I'm trying the get the last date that will be shown using JavaScript.
Currently I have this code:
var last_date = document.getElementsByClassName("notif_date");
console.log(last_date);
But this only gets the array of input types
So I tried to use last() and place like this console.log(last_date.last()); and this gives me an error like this
Uncaught TypeError: last_date.last is not a function
How can I get the last value of date using JavaScript?
To get last element you can use following code
let elements = document.getElementsByClassName("notif_date");
console.log(elements[elements.length-1]);
This code will provide you the correct output which you want.
Edited
If you want to get value of last element then use this:-
console.log(elements[elements.length-1].val());
Note: But you can't get value directly from document.getElementsByClassName("notif_date"). Because this return multiple object of multiple class elements.
But if you want to get value of all the elements then you need to loop this.
Using new Array.prototype.at() method.
let elements = [...document.getElementsByClassName("notif_date")];
let last_input = elements.at(-1);
let last_value = elements.at(-1).value;
console.log(last_input, last_value);

passing jquery array to php - unexpected format and count() value and variable passing issue

I am passing a jquery array called 'selected' full of ids along with the opening of an ajax modal.
$('#dtDelete').on('click', function () {
$('#modal-ajax').load('/modals/m__delete.php?selected='+selected);
$('#modal-ajax').modal('show');
});
On the modal php page count($_GET['selected']); always returns 1 no matter what. I am trying to get an actual count of the number of values in the array. Turns out this is because the array is a string as noted below.
var_dump($_GET['selected']); returns something along the lines of string(69) "187419,187420,187413,187414,187415,187416,187417,187418,187421,187422" which is something I am not accustomed to (sort of new to jquery). I need to do processing in php using foreach on this array. Can I 'convert' this to a 'normal' php array so count() will work as expected and I can process it normally in php?
Lastly, this array may or may not be extremely large at times. The jquery function above opens an ajax modal (I am using the modal as a confirmation box for the user whether they really want to delete the entries in the selected array) and I know the $_GET method has limits to the amount of data it can pass. I can't do $_POST because this is a modal and I need to load it then show it... how else can I pass this data?
$_GET['selected']
returns the STRING after the attribute 'selected', and count(string) is 1 not matter what ( it's not a multi-dimension array to be greater than 1).
As for the comma separated string example you gave, you may use the following :
$selected = $_GET['selected'];
//test wether the string has contents
if(strlen($selected)!=0) {
$selected_array = explode(',',$selected); //this is the new array that you want
}
else {
//the string is empty
}
There are many string functions you may check at : http://www.php.net/manual/en/ref.strings.php

Array in hidden variable changes to string

I'm setting an array to a hidden field using JavaScript. However, the issue is that the array gets converted to a string on form submit when I catch it using PHP.
This is the code that sets the hidden input field value:
document.getElementById("hiddenFieldId").value = arrayFromJS;
Is there any workaround for this?
Actually the problem is earlier I had a select box which sent it's values nicely on form submit. But now I've got a custom select box using JS which sets comma separated values in a hidden field... So in a nutshell I want that input field to act like a pseudo-select box
You should JSON encode/decode the value:
On the client side you use JSON.stringify to encode the array:
document.getElementById("hiddenFieldId").value = JSON.stringify(arrayFromJS);
And then on the server side you can use json_decode:
$arr = json_decode($_POST['hiddenFieldId']); // Fetch the data from POST / GET
foreach ( $arr as $value ) {
// iterate the array on the server side.
}
unset($arr); // Remember to unset the $arr variable
If you know you are handeling a simple array (with string only) you can join the string in javascript and explode/split it php:
document.getElementById("hiddenFieldId").value = arrayFromJS.join('/:/');
PHP:
$arr = explode('/:/', $_POST['hiddenFieldId']);
To support older browser you can use this JSON plugin to the front end: https://github.com/douglascrockford/JSON-js

Passing multiple values from MYSQL/PHP table to jQuery

Basically, I have working solution for this, but I'm wondering if it could (should?) be done better in some other way.
I have table I'm creating in PHP with values from MYSQL. Each item in table has multiple values. In each line there is single link and clicking on this link fires up jQuery function. In each link there is also VALUE attribute with values from multiple MYSQL fields and joined with &&:
PHP code is:
foreach ($this->_data as $l)
{
?>
...
<td>Link</td>
...
<?php
}
And jQuery function to fire up when clickin' on link is:
$(".clickMe").click(function() {
myData = $(this).attr('value').split('&&');
});
Script splits string in VALUE attribute on && and creates an array myData with values:
myData[0] => value passed from $l->_data1 in PHP
myData[1] => value passed from $l->_data2 in PHP
Is this the right way to do it?
It's fine, as long as you'll never have && in your data. You could use json_encode() in PHP and then decode this into an array in JavaScript. That would be a more standard solution.
I would recommend against using && which looks like a boolean AND. Instead I would probably use something like a pipe to separate them val1|val2.
I think you're better off passing the whole joined string in to PHP and splitting it out there. It saves you work on both ends having to put the two resultant values into the proper post or get variables to send to PHP.
Then on the PHP side, it's a little easier to validate the one value's format before splitting it, as you can use a single regex like:
// Validate both values at once: 1 or more digits, a pipe, and one or more digits
if (preg_match('/^(\d+)\|(\d+)$/', $_POST['jqueryinput'])) {
// explode() and use in PHP...
list($val1, $val2) = explode("|", $_POST['jqueryinput']);
}

PHP Array to jQuery array with JSON. ($.post, parseJSON, json_encode)

I am trying to get a php file setup to return the results of a MySQL database query from a jQuery AJAX call. The returned results will be an array. I have a very basic start where I am just getting some basic data back and forth to and from the php file, but am stuck with some basic syntax issues:
The PHP code:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
The jQuery code:
$.post("dbFile.php", str, function(theResponse){
alert('the response: ' + theResponse);
var obj = $.parseJSON(theResponse);
alert(obj.a);
I can print out obj.a, obj.b, obj.c... no problem. The problem is I will be incrementing a counter as I increment through the MySQL results. So, the array does not use letters, it uses numbers:
$arr[$i] = mysqlresults ... $i++;
So, in the JavaScript/jQuery I have an object (not an array). I can print out obj.a for example, but I can not print out obj.2 (for example). In other words, if I replace the letters with numbers in the php array, I don't know how to print them out in JavaScript/jQuery. Can I change the object that parseJSON returns into an array somehow (so that I can cycle through it)?
Use the array access syntax:
alert(obj[42]);
You can use:
alert(obj['a']);
See this question for more info.

Categories