AngularJS $http.get() not working - php

I am using ZF2 and AngularJS to create a Quiz Application. When I am running the code, No error occurs, and no result.
(function(angular) {
function MainController($scope,$http) {
$scope.question = function(id)
{
var site = "http://localhost/zf/public/interviewer";
var page = "/jsonquestion/"+id;
alert(site + page);
var reqQuestion = $http.get(site + page);
reqQuestion.success(function(data, status, headers, config) {$scope.question.questions = data;});
reqQuestion.error(function(data, status, headers, config){alert("AJAX failed!");});
alert(data);
}
};
angular.module("app", []).controller("MainController", ["$scope", MainController]);
})(angular);
My zend part is
public function jsonquestionAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
$questions = $this->getQuestionsTable()->getQuestions($id);
$result = json_encode($questions);
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, $result);
fclose($myfile);
echo $result;
return $result;
}
When I m calling http://localhost/zf/public/interviewer/jsonquestion/1 from browser its working and returning Json

You aren't injecting $http to your controller
Try changing to this.
angular.module("app", []).controller("MainController", ["$scope", "$http", MainController]);

Shot in the dark. Your zend function is called jsonquestionAction, but your page call is made to jsonquestion.
Maybe changing this:
var page = "/jsonquestion/"+id;
To this:
var page = "/jsonquestionAction/"+id;
Will help.

Related

Simple example to populate database using JSON, XMLHttpRequest, and PHP file_get_contents("php://input") not working

Now I know this has been asked before, but none of the responses have offered up insight for me to date;
I have an HTML page with the script below (ultimately I shall use this script to suck data out of an app), basically testing to send some data in JSON format to a PHP page which is to populate a MYSQL database with the record.
My problem is that I get no table record update. Nada.
This has been messing me around for a few weeks now; the closest I have got is:
Send JSON data from Javascript to PHP?
My limited success to date has been to grab data from a .json file and update the database that way on a php page. So, the JSON is fine in the script, and the connection to the database is ok. I just don't seem to be able to pass it from an html page to php and populate the db. I cannot understand why this has to be that difficult.
Any suggestions/pointers would be appreciated (I need to keep this simple as I am a relative novice). Thank you in advance.
HTML page script
<script>
var jsonQuizData = {};
var qID = '9';
var learnersName = 'Bart Bundy';
var learnersEmail = 'bbundy#blue.com';
var quizName = 'SomeQuiz99';
var quizScore = '33%';
var result1 = 'Some blob data goes in here?';
var dbString, request;
jsonQuizData = '{ "id":qID, usersName":learnersName, "usersEmail":learnersEmail, "quizTitle":quizName, "qScore":quizScore, "Output1":result1 }';
dbString = JSON.stringify(jsonQuizData);
request = new XMLHttpRequest();
request.open("POST", "process.php", true);
request.setRequestHeader("Content-Type", "application/json");
request.send(dbString);
</script>
process.PHP page
<?php
header("Content-Type: application/json; charset=UTF-8");
//Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection etc. performed here
$data = json_decode(file_get_contents("php://input"));
$id = $data['id'];
$name = $data['usersName'];
$email = $data['usersEmail'];
$qtitle = $data['quizTitle'];
$result1 = $data['Output1'];
$qScore = $data['score'];
//insert into mysql table
$sql = "INSERT INTO quiz01(quiz_id, quiz_title, fName, eMail, quiz_score, q1_answer)
VALUES('$id', '$qtitle', '$name', '$email', '$qScore', '$result1')";
if(!mysqli_query($conn,$sql))
{
die('Error : ' . mysqli_error($conn));
}
else
{
echo "Data inserted successfully";
}
//Close connection
/?>
.... Brick wall time
Your stringify portion in your sample is not right, it's already a string, so I think you mean to do:
var jsonQuizData = {};
var qID = '9';
var learnersName = 'Bart Bundy';
var learnersEmail = 'bbundy#blue.com';
var quizName = 'SomeQuiz99';
var quizScore = '33%';
var result1 = 'Some blob data goes in here?';
var dbString, request;
// Here you have to stringify the data object, not a string of the data object.
jsonQuizData = JSON.stringify({"id":qID, "usersName":learnersName, "usersEmail":learnersEmail, "quizTitle":quizName, "qScore":quizScore, "Output1":result1});
request = new XMLHttpRequest();
request.open("POST", "process.php", true);
// Send the regular form header
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
// Now when it sends, it should send it properly as a post
request.send('json='+jsonQuizData);
Then in the PHP, you don't need to send the line:
header("Content-Type: application/json; charset=UTF-8");
and you can alter this line:
$data = json_decode(file_get_contents("php://input"));
to just:
$data = json_decode($_POST['json'],true);
It should now all be in the regular $_POST, then you need to bind parameters when you insert.
Update:
Right, got it working doing the following:
HTML page
<script>
var jsonQuizData = {};
var learnersName = 'Professor T';
var learnersEmail = 'prof.teerlink#pooh.com';
var quizName = 'TidlyWinks101w';
var quizScore = '100%';
var result1 = 'Balls said the crow';
var dbString, request;
jsonQuizData = JSON.stringify({"quizTitle":quizName, "usersName":learnersName, "usersEmail":learnersEmail, "qScore":quizScore, "Output1":result1 });
$(document).ready(function()
{
$("button").click(function()
{
$.post("working01.php", 'json='+jsonQuizData,
function(data,status)
{
//alert("Data: " + data + "\nStatus: " + status);
document.getElementById("AV1").innerHTML = data;
});
});
});
</script>
And PHP page...
<?php
//Set up connections to database etc...
if (isset($_POST['json']))
{
$str = $_POST['json'];
$contents = json_decode($str);
$qtitle = $contents->quizTitle;
$name = $contents->usersName;
$email = $contents->usersEmail;
$qScore = $contents->qScore;
$result1 = $contents->Output1;
}
$sql = "INSERT INTO quiz01(quiz_title, fName, eMail, quiz_score, q1_answer)
VALUES('$qtitle', '$name', '$email', '$qScore', '$result1')";
if(!mysqli_query($conn,$sql))
{
die('Error : ' . mysqli_error($conn));
}
else
{
echo "Data inserted successfully";
}
//Close connections
?>
But so want to do it utilising the XMLHttpRequest() object and send the json.
as per Rasclatt. Thanks

Inserting Variables From Jquery Always Fails

i have some problem, i made some local website using php.
I have a file called functions.php which this is the code:
public function saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit){
$message = "Waiting input...";
try{
$con = new db();
$conn = $con->connect();
$query = "INSERT INTO mt_pesanan(idmt_salesarea,thn_bln,no_pesanan,tgl_pesan,idms_langganan, idms_kodebarang,quantity,harga,jumlah,disc_cash,disc_kredit) VALUES ($idmt_salesarea, '$thn_bln', '$no_pesanan', '$tgl_pesan', $idms_langganan, $idms_kodebarang, '$quantity', $harga, $jumlah, '$disc_cash', '$disc_kredit')";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn) . " " . mysqli_errno());
if($result == 1){
$message = "Success";
} else if($result == 0){
$message = "Failed";
}
}catch(Exception $exc){
echo $exc->getCode();
}
$con->disconnect();
return $message;
}
i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php
here's the insert.php file:
<?php
include_once 'functions.php';
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
if (($disc_cash == null) || ($disc_kredit == null)) {
$disc_cash = 0;
$disc_kredit = 0;
}
$insert = new functions();
$insert->saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit);
?>
but when i check the error, that is the variable that cannot get from insert.php file (using $_GET statement).
How proper way to gain the variable? because all the parameter is set.
I know this is combining object oriented style and old fashion php coding. Any ideas?
thanks in advance.
UPDATE
here's the index.php file using jquery ajax to sent the data
function sendAll(){
var tgl_pesan = $('#dpc').val();
var sales_area = $('#sales_area').val();
var nopes = $('#no_pesanan').val();
var thnbln = getTahunBulan();
var id_langganan = $('#kode_langganan').val();
var id_barang = $('#kode_barang').val();
var quantity = getQuantity();
var harga = $('#harga').val();
var jumlah = $('#jumlah').val();
var disc_cash = $('#cash').val();
var disc_kredit = $('#kredit').val();
var max = $('#max').val();
$.ajax({
type:"POST",
**url:"insert.php",**
data:{
salesarea:sales_area,
thn_bln:thnbln,
nopes:nopes,
tglpes:tgl_pesan,
idlangganan:id_langganan,
idbarang:id_barang,
quantity:quantity,
harga:harga,
jumlah:jumlah,
disc_cash:disc_cash,
disc_kredit:disc_kredit,
max:max
},
success:function(msg){
alert("Data Inserted");
},
error:function(msg){
alert("Data Failed to save" + msg);
}
});
the ajax itself is pointing to file insert.php which the insert.php is executing function from another file called functions.php
The problem is with this code:
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
For each of those variables, you are assigning the result of isset(), which will evaluate to either TRUE or FALSE. If you want to bind the actual value of your $_GET input, change each line from this syntax:
$idmt_salesarea = isset($_GET['salesarea']);
To
$idmt_salesarea = isset($_GET['salesarea']) ? $_GET['salesarea'] : '';
However this code isn't really maintainable, and I would also recommend using arrays instead of passing that many arguments to your saveAll() method.
In response to your update
If you are sending an AJAX request with type: "POST", you cannot access your input data via the PHP $_GET super global, you have to use $_POST. However, what I said before is still valid, as you aren't binding values to your variables properly.
Although I do not get what you are saying completely, still based on your description the problem can be you sending the variable using ajax call. If the ajax call is async you might not get the value by the time you use it.
So you can either set async:false in the ajax call (which is not a good way) or trigger any thing that uses that variable from within the success callback handler of the ajax call.
It would be really helpful if you can share the piece of code which explains the following statement of yours.... "i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php"

Want to perform php using OnClick function without clearing the current web page

This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'>&nbsp</div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?

Repeating and Changing php values for my Music Player

I would like to know how i can change or repeat certain elements in php.
Right now i am using a script to fetch what song is playing from a shout-cast info page.
And in JQuery i have a player with a playlist that switches stream.
Now the only thing it does right now is just switch to the stream and not display anything.
So how would i go about on calling an php part inside jQuery?
Gosh, i really hope im being clear enough in my explanation.
For those who are able to help me
What parts of my code do you want me to display?
i wil then go ahead and paste that for you Right away! :)
Greets,
Kus.
Code for Arjan:
JQUery
$(document).ready(function(){
var myPlaylist = new jPlayerPlaylist({
jPlayer: "#jquery_jplayer",
cssSelectorAncestor: "#jp_container"
}, [
{
title: "test",
mp3: "http://178.156.201.212:8018/;stream/1",
<?php
$host = "178.156.201.212"; // ip or url of shoutcast server
$port = "8018";
?>
},
{
title: "test2",
mp3: "http://stream1.slowradio.com/;stream/1",
<?php
$host = "http://stream1.slowradio.com"; // ip or url of shoutcast server
$port = "8008";
?>
},
{
title: "test3",
mp3: "http://108.61.73.119:8022/;stream/1",
<?php
$host = "108.61.73.119"; // ip or url of shoutcast server
$port = "8022";
?>
},
], {
swfPath: "js",
supplied: "oga, mp3",
wmode: "window"
});
$("#jquery_jplayer").bind($.jPlayer.event.play, function(event) {
//$('#fetch').html(jPlayerPlaylist.playlist[jPlayerPlaylist.current].title);
$('#fetch').empty();
$('#fetch').append(myPlaylist.playlist[myPlaylist.current].title);
});
});
PHP
<?php
$host = "178.156.201.212"; // ip or url of shoutcast server
$port = "8000"; // port of shoutcast server
$fp = #fsockopen("$host", $port, $errno, $errstr, 30);
if($fp)
{
fputs($fp,"GET /7.html HTTP/1.0\r\nUser-Agent: GET SEVEN (Mozilla Compatible)\r\n\r\n");
while(!feof($fp))
{
$data .= fgets($fp, 1000);
}
fclose($fp);
$data = ereg_replace(".*<body>", "", $data);
$data = ereg_replace("</body>.*", ",", $data);
$data_array = explode(",",$data);
$listeners = $data_array[0];
$status = $data_array[1];
$peak_listeners = $data_array[2];
$maximum_listeners = $data_array[3];
$unique_listeners = $data_array[4];
$bitrate = $data_array[5];
$track = $data_array[6];
}
$title = chop($track);
$select = explode(" - ",$title);
$artist = chop($select[0]);
$title = chop($select[1]);
?>
<?php
if($status == 1)
{
echo $artist. " - " .$title;
}
else
{
print 'document.getElementById("title").innerHTML = "Offline";';
}
?>
Calling PHP inside jquery is done by this code:
$.ajax({
type: "GET",
url: 'this_file.php',
success: function(html) {
var data = html.split(' ');
var host = data[0];
var port = data[1];
}
});
Your PHP would be:
if ( isset($_GET['update']) ) {
die($host.' '.$port);
}
This code loads html from the php file and puts it in the HTML body tag. Ofcourse you can change body to any element.
For more specific help, post some of your PHP and jQuery code please.
Edit: Full documentation on: http://api.jquery.com/jQuery.ajax/
Maybe this works:
<?php
$host = "http://stream1.slowradio.com"; // ip or url of shoutcast server
$port = "8008";
?>
Has to be
<?php
$host = "http://stream1.slowradio.com"; // ip or url of shoutcast server
$port = "8008";
echo 'host: '.$host;
echo 'port: '.$port;
?>
Next time, make sure you give your code right away. That saves a lot of time and downvotes I guess.

Is there any reason why this cron job wouldn't be working

EDIT: Cron line: /usr/bin/php /usr/local/yy/yy/yy/webspace/httpdocs/test.mysite.ie/test.php > /dev/null 2>&1
I have written a script that functions as it should when i navigate to it in the browser. This is my first time trying to use a cron job so i'm not overly familiar with how they work. The script is below. As i said, the script works as it should if i navigate to the url in a web browser.
test.php
<script src="jquery.min.js"></script>
<script>
//SET UP JS VARIABLES
var allMatchedNumbers = new Array();
var matchedthingyNumbers;
var matchedthingyPlus1Numbers;
var matchedthingyPlus2Numbers;
var winningthingyNumbers = new Array();
var winningBonusNumber;
var winningthingyPlus1Numbers = new Array();
var winningPlus1BonusNumber;
var winningthingyPlus2Numbers = new Array();
var winningPlus2BonusNumber;
var thingyList;
var thingyListItems;
var thingyPlus1List;
var thingyPlus1ListItems;
var thingyPlus2List;
var thingyPlus2ListItems;
var userNumbers = new Array();
var displayCounter = 1;
var drawDate;
var thingyNumbers;
var thingyBonus;
var thingyPlus1;
var thingyPlus1Bonus;
var thingyPlus2;
var thingyPlus2Bonus;
//GET RESULTS & DATE FOR thingy, PLUS1, PLUS2 FROM THE DOM OBJECT ONLY
$(document).ready(function fetchResults(){
$.ajax({
url: "scrape_page.php",
success: function(data) {
}
});
$.ajax({
url: "latest_results.txt",
success: function(data) {
var dom = $(data);
//GET thingy DATE
drawDate = dom.find('.date-heading.fooRegular').contents().first().text();
//GET thingy NUMBERS
thingyNumbers = dom.find('.result-block').eq(0).find('.thingy-winning-numbers');
thingyBonus = dom.find('.result-block').eq(0).find('.thingy-bonus');
thingyPlus1 = dom.find('.result-block').eq(1).find('.thingy-winning-numbers');
thingyPlus1Bonus = dom.find('.result-block').eq(1).find('.thingy-bonus');
thingyPlus2 = dom.find('.result-block').eq(2).find('.thingy-winning-numbers');
thingyPlus2Bonus = dom.find('.result-block').eq(2).find('.thingy-bonus');
populateWinningNumbers();
}
});
});
//PUT WINNING NUMBERS IN ARRAY
function populateWinningNumbers() {
//MAIN thingy NUMBERS
thingyList = thingyNumbers;
thingyListItems = thingyList.find('li');
thingyPlus1List = thingyPlus1;
thingyPlus1ListItems = thingyPlus1List.find('li');
thingyPlus2List = thingyPlus2;
thingyPlus2ListItems = thingyPlus2List.find('li');
thingyListItems.each(function(index) {
winningthingyNumbers[index] = parseInt($(this).text());
});
//winningBonusNumber = parseInt($('#mainthingyBonus').find('li').text());
winningBonusNumber = parseInt($(thingyBonus).find('li').text());
winningthingyNumbers.push(winningBonusNumber);
//thingy PLUS NUMBERS
thingyPlus1ListItems.each(function(index) {
winningthingyPlus1Numbers[index] = parseInt($(this).text());
});
winningPlus1BonusNumber = parseInt($(thingyPlus1Bonus).find('li').text());
winningthingyPlus1Numbers.push(winningPlus1BonusNumber);
//PLUS 2
thingyPlus2ListItems.each(function(index) {
winningthingyPlus2Numbers[index] = parseInt($(this).text());
});
winningPlus2BonusNumber = parseInt($(thingyPlus1Bonus).find('li').text());
winningthingyPlus2Numbers.push(winningPlus2BonusNumber);
postDataToDB();
}
//POST OFFICIAL thingy NUMBERS TO DATABASE
function postDataToDB() {
$.ajax({
url: "postToDB.php",
type: "post",
data: {thingyNums:winningthingyNumbers, thingyPlus1Nums: winningthingyPlus1Numbers, thingyPlus2Nums: winningthingyPlus2Numbers, drawDate:drawDate},
// callback handler that will be called on success
success: function (data) {
}
});
}
</script>
scrape_page.php
<?php
include 'simple_html_dom.php';
$html = file_get_html('http://www.site.com');
$file = 'latest_results.txt';
file_put_contents($file, $html);
?>
postToDB.php
<?php
$winningNums = $_POST['thingyNums'];
$winningPlus1Nums = $_POST['thingyPlus1Nums'];
$winningPlus2Nums = $_POST['thingyPlus2Nums'];
$drawDate = $_POST['drawDate'];
$thingyToSave = implode(',', $winningNums);
$plus1ToSave = implode(',', $winningPlus1Nums);
$plus2ToSave = implode(',', $winningPlus2Nums);
//CONNECT TO REMOTE
$con = mysql_connect("172.xx.xx.xx","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//SELECT thingy DB
mysql_select_db("App", $con);
//CHECK IF DATE ALREADY EXISTS IN DB
$date_check = mysql_query("SELECT drawDate FROM thingy WHERE drawDate='$drawDate'");
$do_date_check = mysql_num_rows($date_check);
if($do_date_check > 0){
//DATE ALREADY IN DB
die("Entries already exist");
} else {
mysql_query("INSERT INTO thingy (drawDate) VALUES ('$drawDate')");
mysql_query("UPDATE thingy SET thingyRes = '$thingyToSave' WHERE drawDate = '$drawDate'");
mysql_query("UPDATE thingy SET thingyPlus1Res = '$plus1ToSave' WHERE drawDate = '$drawDate'");
mysql_query("UPDATE thingy SET thingyPlus2Res = '$plus2ToSave' WHERE drawDate = '$drawDate'");
echo "Success";
}
mysql_close($con);
?>
The script you're trying to run contains Javascript - which is executed in a browser. Cron will execute the PHP script on the server, and send the output nowhere (as you're directing it to /dev/null).
There's nothing in that scenario that will interpret and execute the Javascript.
You need to essentially port the logic in your Javascript (which makes requests to the two related PHP scripts) to PHP. (You could possibly run some server side javascript interpreter/php extension, but in this case that would seem a bit crazy.)
If you're calling test.php via wget or similar, that tool php doesn't have a JavaScript engine in it. So naturally any JavaScript-dependent features of the page won't run.
There are tools that will load the page and execute the JavaScript therein. They're called "headless" browsers. For example, PhantomJS, which is a headless browser based on WebKit with a JavaScript engine in it. There are also headless versions of Firefox and such.
You'd have your web server running as normal and point the headless browser at the URL for the page, which would both trigger the PHP (just as though the page had been requested by a browser) and process the client-side JavaScript in the page.

Categories