Send SMS if found changes in json file - javascript

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;
}
}

Related

Javascript inside else statement isn't working. Message doesn't appear

I'm making a basic login for a php website, the function is really simple if checks if the data send using POST is in a MySQL table and if it's correct it would allow the user to proceed it the data is incorrect, it should show a message saying credentials are incorrect:
<?php
include("required/datos.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$grupo = mysqli_real_escape_string($db,$_POST['grupo']);
$sql = "SELECT * FROM usuarios WHERE BINARY password = '$mypassword' and grupo = '$grupo'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['grupo'] = $grupo;
$_SESSION['autorizado'] = TRUE;
header('location: horario.php');
}
} else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
?>
The if statement is working so far, and even the else but the message isn't showing out at all, I'm trying to look where exactly is the problem but I can't found it.
Try this code. Your brackets are in the wrong position.
<?php
include("required/datos.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$grupo = mysqli_real_escape_string($db,$_POST['grupo']);
$sql = "SELECT * FROM usuarios WHERE BINARY password = '$mypassword' and grupo = '$grupo'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['grupo'] = $grupo;
$_SESSION['autorizado'] = TRUE;
header('location: horario.php');
} else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
}
?>
Like mentioned in the comments you have one curly braket that messes up your code. The else statement is now checking for the first if statement in which you check the request type. But the else case with the count should be the else case to your if statement that checks the number of rows ($count).
Furthermore you need to concatenate strings in your echo because your JS code doesnt know about variables or values from your PHP script like this:
echo "<script type='text/javascript'>alert('" . $message . "');</script>";
Then try this
}else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
Try this one. Probably you have an extra bracket } or is wrongly positioned and you are echoing $message as a string which is wrong. Use concatenation in this way to print your message
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('" . $message . "');</script>";
header('Refresh: 0; URL=index.php');

Error parsing JSON file - Incorrect Object

I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school

Pass PHP array from Javascript

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>

How to properly load one ajax request after another

I am creating a messaging system for a website that I am making. Basically, it consists of clicking one button and two Ajax Requests afterwards. I am not even sure I am going about this the right way. On click of the button the first Ajax starts to call. The first ajax request loads a file that loads the style of the messages and retrieves them from a database. The problem I am having is that the first request sometimes takes to long to finish and the other request does not get complete. Another problem I am having is that if I put an "animation delay" type thing on it then it will look like the page it running slow. You can run an example at "http://www.linkmesocial.com/linkme.php?activeTab=mes" you must type or copy and past the whole length for it to work otherwise you will redirect to the login page. Any advice would be AWESOME! If there is some easier way to set up a messaging system please feel free to give me some advice or direct me to a tutorial. THANK YOU SO MUCH!
I would also like the know if this is a good practice. Please :)
My Original file. On click of class "mes_tab" a form is submitted. also the function mes_main() is called.
session_start();
$username = $_SESSION['user'];
$messages = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username'");
echo "<div id=\"mes_main-bar_top\" class=\"center\">Messages</div>";
echo "<div id=\"mes_main\">";
echo "<table id=\"mes_main-allView\" class=\"left\">";
echo "<td class=\"mes_tab-change\" >^</td>";
$from=array("","","", "", "", "", "", "");
for ($msgCount = 0; $msgCount < 8; $msgCount++){
$row = mysqli_fetch_array($messages);
$from[$msgCount] = $row['sender'];
for ($prev = 0; $prev < $msgCount; $prev++)
{
if ($from[$msgCount] == $from[$prev] )
{
$cont = true;
break;
}
}
if ($cont)
{
$cont = false;
continue;
}
if ($row['message'] == ""){
break;
}
echo "<tr><td class=\"mes_tab\" onclick=\"mes_main('" . $row['sender'] . "')\">";
echo "<h3 class=\"center\">" . $row['sender'] . "</h3>";
echo "<form id=\"" . $row['sender'] . "\" >";
echo "<input name=\"sender\" value=\"" . $row['sender'] . "\" hidden/>";
echo "<input name=\"id\" value=\"" . $row['id'] . "\" hidden/>";
echo "</form>";
echo "</td></tr>";
}
if ($msgCount == 8)
{
echo "<td id=\"mes_tab-change_bottom\" class=\"mes_tab-change\">V</td>";
}
echo "</table> <!-- end mes_main-allView -->";
echo "<div id=\"mes_main-mesView\" class=\"right\">";
echo "</div> <!-- end mes_main-mesView -->";
echo "</div> <!-- end mes_main -->";
mes_main() function from above. The two ajax functions inside are what I am referring to in the post above.
function mes_main(x)
{
var sender = x;
$( sender ).submit(function( event ) {
event.preventDefault();
});
ajax_req_mes("scripts/home/php/mes_load.php?" + sender , "mes_main-mesView");
ajax_req_mes("scripts/home/php/mes_content.php?" + sender ,"mes_content");
}
mes_load.php
the $sender var is created by passing the sender username through the URL. That is why I do php explode on the url.
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<div id=\"mes_content\"></div>";
echo "<div id=\"mes_field\" class=\"right\"></div>";
mes_content.php
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<table id=\"mesView-table\">";
$REC = array();
$SENT = array();
$ID = array();
for ($i = 0; $i < 25; $i++)
{
$rec = mysqli_fetch_array($recieved);
$sent = mysqli_fetch_array($sent);
if ($rec['id'] > 0)
{
$REC[$i] = $rec['id'];
}
if ($sent['id'] > 0)
{
$SENT[$i] = $sent['id'];
}
}
$ID = array_merge($SENT, $REC);
sort($ID);
for ($x = 0; $x < count($ID); $x++)
{
$key = $ID[$x];
$result = mysqli_query($con, "SELECT * FROM messages WHERE id = '$key'");
$res = mysqli_fetch_array($result);
if (in_array($key, $REC))
{
echo "<tr><td class='mes_recieved'>";
echo $res['message'];
echo "</tr></td>";
}
elseif (in_array($key, $SENT))
{
echo "<tr><td class='mes_sent'>";
echo $res['message'];
echo "</tr></td>";
}
}
echo "</table>";
Set async to false in your ajax requests!That's how the second one will wait for completing the first one and then start.
Also you can catch the on success and on error for the purposes you have.
Just use the "success" and "error" callbacks.
Also you could use the "done" callback
But, IMO, for that kind of problem I think a better alternative would be using Websockets
EDIT:
Here is some example of how you could do it:
jQuery.ajax({
type : "POST",
data : {msg:"your message"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
}).done(secondCall());
function secondCall(){
jQuery.ajax({
type : "POST",
data : {data:"data"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
});
}
EDIT2:
For visibility, here is a tutorial using websockets: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

Export HTML5 form data to CSV?

Any ideas on Exporting HTML5 Form data to CSV please?
I can only use HTML5 or Javascript or both.
Thanks
You could just display the form data in CSV format in the browser (maybe in a popup) and have the user do a File -> Save Page (assuming it doesn't have to be fully automated).
OK, this is what I'm going to have to do: 1. If there IS internet connection ... then save the data to MySQL Table. 2. Using PHP run a script on the MySQL DB to export the data to CSV.
I'll use something like this for example:
<?php
$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j]."; ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>

Categories