I would like to pass a PHP array from JavaScript.
PHP Data Table
---------------------------
| adminID | adminEmail |
===========================
| 1 | abc#gmail.com |
| 2 | xyz#ymail.com |
===========================
Javascript
<script>
function checkuser_callback_function($el, value, callback) {
var $array = new Array("xyz#gmail.com","abc#ymail.com");
var valid = false;
if($array.indexOf(value) == -1){
valid = true;
}
callback({
value: value,
valid: valid,
message: "User present."
});
}
</script>
I want to pass that adminEmail here var $array = new Array("..","..");
I have tried alot in php but I didn't get any result.
<?php
include 'config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) {
$array = $row;
$str = "'" . implode ( "', '" ,$array ) . "'";
$parts = split("'", $str);
print_r($str);
}
?>
You can use php to create javascript array. Then use the same in the script later. Please note that , just to differentiate, I have called javascript array jArray instead of $array. Rest is explained along in the script only. Hope this helps..
<?php
include 'config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
//start script tag
echo "<script>\n";
// javascript array decalaration beginning
echo "var jArray = new Array(";
$arrStr = "";
while($row = mysqli_fetch_assoc($result)) {
// $array = $row;
// $str = "'" . implode ( "', '" ,$array ) . "'";
// $parts = split("'", $str);
// print_r($str);
$arrStr .= '"'. $row["adminEmail"] . '",';
}
// drop the last , from the string
$arrStr = substr($arrStr,0,-1);
// now populate javascript array with this string
echo $arrStr;
// end javascript array
echo ");\n";
echo "</script>\n";
?>
<?php
include 'ePHP/config.php';
$sql ="SELECT adminEmail FROM BEadmin";
$result = mysqli_query($con,$sql);
$arrStr = "";
while($row = mysqli_fetch_assoc($result)) {
// $array = $row;
// $str = "'" . implode ( "', '" ,$array ) . "'";
// $parts = split("'", $str);
// print_r($str);
$arrStr .= '"'. $row["adminEmail"] . '",';
}
// drop the last , from the string
$arrStr = substr($arrStr,0,-1);
// now populate javascript array with this string
?>
<script>
function checkuser_callback_function($el, value, callback) {
var $array = Array(<?php echo $arrStr; ?>);
var valid = false;
if($array.indexOf(value) == -1){
valid = true;
}
callback({
value: value,
valid: valid,
message: "User present."
});
}
</script>
Related
how do I write mysql_fetch_array code in codeigniter
<?php
$result = mysql_query("select * from tb_mhs");
$jsArray = "var dtMhs = new Array();\n";
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['nim'] . '">' . $row['nim'] . '</option>';
$jsArray .= "dtMhs['" . $row['nim'] . "'] = {nama:'" . addslashes($row['nama']) .
"',jrsn:'".addslashes($row['jurusan'])."'};\n";
}
?>
Form Input :
<td><input type="text" name="nm" id="nm"/></td>
<td><input type="text" name="jrsn" id="jrsn"/></td>
Javascript :
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(nim) {
document.getElementById('nm').value = dtMhs[nim].nama;
document.getElementById('jrsn').value = dtMhs[nim].jrsn;
};
</script>
If you want to return result as a array from the database, you can use something like this
// in application/config/autoload.php, make database available globally
$autoload['libraries'] = array('database');
// fetch the results from the database
$query = $this->db->get('tb_mhs'); // produces select * from tb_mhs
// get the result as a array
$result = $query->result_array();
// to do the other operations you were doing you can use a loop
foreach ($result as $key => $item) {
// do stuff
}
I know how to pass a PHP variable into JavaScript variable one by one, but now I wish to pass a bunch of variable in a For loop and I just stuck.
<?php
$m = new MongoClient();
$db = $m->data_from_tweeter;
$collection = $db->output;
$cursor = $collection->find();
foreach($cursor as $document){
echo $document['place'] ;
echo $document['fir'];
echo $document['sec'];
}
?>
I want to store 'place' as a String variable, 'fir' and 'sec' as two Num variables, and make them look like:
var num_1 {
some_place : some_fir,
some_place : some_fir,
some_place : some_fir,
....
}
and
var num_2 {
some_place : some_sec,
some_place : some_sec,
some_place : some_sec,
....
}
How can I make it? Thanks in advance!
if $document['fir'] and $document['sec'] are array .You can do like this
<?php
$m = new MongoClient();
$db = $m->data_from_tweeter;
$collection = $db->output;
$cursor = $collection->find();
$num1=array();
$num2=array();
foreach($cursor as $document){
echo $document['place'] ;
$num1 = json_encode ($document['fir']);
$num2 = json_encode ($document['sec']);
}
?>
You can use a JSON string as a object for javascript
var num_1 = <?php echo $num1;?>
var num_2 = <?php echo $num2;?>
The following code snippet might help get you started:
$num_1 = "var num_1 = {\n";
$num_2 = "var num_2 = {\n";
foreach ($cursor as $document) {
$num_1 .= " {$document['place']} : {$document['fir']},\n";
$num_2 .= " {$document['place']} : {$document['sec']},\n";
}
$num_1 .= "};\n";
$num_2 .= "};\n";
echo $num_1;
echo $num_2;
I have a button called rename that when pushed, executes in jQuery a rename.php file. Inside that php file the program selects data from a mysql, creates an array with that data, and processes an array in to json_encode($array);. How can I then get that json encoded array and echo it out into javascript?
I'm trying to echo the array out so that javascript displays my images src's.
This is my second line of ajax so I just wrote the javascript out as if it were php because I'm not sure of the commands or structure in js.
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
/*alert(result);*/
document.getElementById("images_to_rename").innerHTML = foreach(jArray as array_values)
{
"<img src=\""array_values['original_path']"/"array_values['media']"/>";
}
}
}
);
and my jQuery php file:
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if(empty($_GET['image_name']))
{
echo '<div class="refto" id="refto">image_name is empty</div>';
}
else
{
echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach($_GET['image_name'] as $rowid_rename)
{
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE ".$username." SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arri[] = $row;
}
foreach($arri as $rows) //put them into workable variables
{
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
?>
<script type="text/javascript">
var jArray= <?php echo json_encode($arri); ?>;
</script>
<?php
}
echo "something2";
?>
My PHP file is a jQuery url:"test4.php", type: "GET", and is not the main file. The main file is called main.php and the test4.php is something that's called in jQuery when the user clicks on rename.
Somebody suggested console log so here's what chrome says:
<div class="refto" id="refto">image_name is not empty</div>[{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}] <script type="text/javascript">
var jArray= [{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}];
</script>
something2
Your ajax php file isn't render in browser, then the variable jArray is undefined. With your case, let return php file to json and you can get it as variable in result.
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if (empty($_GET['image_name'])) {
//echo '<div class="refto" id="refto">image_name is empty</div>';
} else {
//echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach ($_GET['image_name'] as $rowid_rename) {
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE " . $username . " SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$arri[] = $row;
}
foreach ($arri as $rows) { //put them into workable variables
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
//stop render here
die();
}
?>
php file need return only json string. Then we'll get result as json variable in javascript.
And Js:
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
var jArray = JSON.parse(result);
/*alert(result);*/
var txt = "";
jArray.forEach(function(array_values){
txt += `<img src=\""array_values.original_path."/"array_values.media"/>`;
})
document.getElementById("images_to_rename").innerHTML = txt;
}
}
);
My code PHP generate a string variable
<?php
foreach($rows as $row){
$result .= "['" .$row["Name"]."'," .$row['Value']. "] , ";
}
$result = rtrim($result, ' , ');
//echo $result returns: ['FirstName1 LastName1',10] , ['FirstName2 LastName2',12] , ['FirstName3 LastName3 ',40]
?>
In js how can I convert the 'name' variable into a functional variable for 'data:' ?
<script>
var name = "<?php echo $result; ?>";
Highcharts.chart('container', {
...
data: [
['Shanghai', 23.7],
['Lagos', 16.1],
['Istanbul', 14.2]
];
...
});
</script>
Thank you!
You need to wrap $result in an array:
$result = "[$result]";
But you really should use json_encode like this:
$resultArr = [];
foreach ($rows as $row) {
$resultArr[] = [$row['Name'], $row['Value']];
}
$result = json_encode($resultArr);
I have this json file that I need to make a cron job for and receive SMS notification when data changes http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json
I need to find out if some server is on stock, so I found this code:
<?php
$cellphone = '15551234567';
$a_track = array('143sys12');
$s = file_get_contents('http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json');
$tmp = json_decode($s, true);
$a = $tmp ['availability'];
$data = array();
foreach ($a as $item) {
if (!in_array($item ['reference'], $a_track)) {
continue;
}
foreach ($item ['zones'] as $zone) {
if ($zone ['availability'] == 'unavailable') {
continue;
}
$data [$item ['reference']] .= $zone ['zone'];
}
}
foreach ($data as $item => $availability) {
$message = "SYS STOCK: $item: $availability";
mail('my#email', 'OMG BUY THIS NOW!', $message);
$url = "http://rest.nexmo.com/sms/json?api_key=xxxx&api_secret=yyyy& from=nnnnnnnn&to=$cellphone&text=" . urlencode($message);
$discard = file_get_contents($url);
}
The problem is that when I trigger it I receive SMS no matter if server is on stock or not and the SMSs keep coming with false positives. I also got this message :
]# /usr/bin/php /home/sys.php
PHP Notice: Undefined index: 143sys12 in /home/sys.php on line 22
I changed your code around a bit and moved the sending of the message in a function to be called when the reference is found.
Take a look:
<?php
$a_track = array('143sys12');
$s = file_get_contents('http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json');
$tmp = json_decode($s, true);
foreach ($tmp['availability'] as $item) {
if (in_array($item['reference'],$a_track)) sendMeAnEmail($item);
}
function sendMeAnEmail($item){
$cellphone = '15551234567';
$message = "SYS STOCK: ". $item["reference"] . PHP_EOL;
$gotStock = 0;
foreach ($item["zones"] as $zone)
if ($zone["availability"] != "unavailable" and $zone['availability'] != 'unknown' ) {
$message .= "Available in the " . $zone["zone"]. " zone, with the " . $zone["availability"] . " status." ;
$gotStock++;
}
$url = "http://rest.nexmo.com/sms/json?api_key=xxxx&api_secret=yyyy&from=nnnnnnnn&to=$cellphone&text=" . urlencode($message);
if ($gotStock > 0) {
print $message . PHP_EOL; // to check
mail('my#email', 'OMG BUY THIS NOW!', $message);
$discard = file_get_contents($url);
print "Got stock, sent mail and SMS" . PHP_EOL;
}
}