$('select[name="third_category"]').change(function() {
var first_cat = $('#main_category').val();
var second_cat = $('#top_category').val();
var third_cat = $(this).val();
$.ajax({
type:'POST',
url:'ajax/fields_ajax.php',
data:{'first_cat':first_cat, 'second_cat':second_cat, 'third_cat':third_cat},
success:function(data){
var field_box = document.getElementsByClassName('field_box');
$(field_box).append(data);
}
});
});
My goal is, when user select third option i collect all the option's values on the page. Then i'm going to use them for my mysql queries. That is my fields_ajax.php file.
<?php
session_start();
ob_start();
include 'inc/session.php';
include 'inc/config.php';
include 'inc/mysql.class.php';
ini_set('display_errors', 0);
if( isset($_POST) ){ // secure script, works only if POST was made
$first_cat = $_POST[first_cat];
$second_cat = $_POST[second_cat];
$third_cat = $_POST[third_cat];
$category_field_query = "SELECT * FROM categories WHERE id = $first_cat";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
echo "<p>".$cat_field->fields."</p>";
} ?>
I can carry all values without problem. But when i use them on query, there's no response. Mysqli connection working correctly, my query works on other php files. And when I try something else instead of trying mysql query, ajax file response it without problem.
Related
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"
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'> </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()?
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.
I'd like to store some div content when a button is pressed. I need/want to save the html tags as well in order to reuse.
When I replace the post variables by any type of string, it works flawlessly. I tried cleaning the html variable from line breaks but it didn't do it, tried also to shell the $HTML post in a $var = <<<HTML HTML, but this didn't work either.
Here is the javascript :
$("#save").click(function(){
var pageHTML = $("#page_wrap").html();
var name_page = "name";
jQuery.ajax({
type: "POST",
url: "php/saveModel.php",
data: { nHTML: pageHTML,
page : name_page
},
success:function(data){
var responseData = jQuery.parseJSON(data);
var new_div = responseData.message;
$("#page_wrap > *").remove();
$("#page_wrap").prepend(new_div);
$('.editable').aloha();
}
})
})
And here is the php :
<?php
mysql_connect('localhost','name','pwd');
mysql_select_db('db');
mysql_query("SET NAMES 'utf8'");
$id = $_POST['page'];
$HTMLpost = $_POST['nHTML'];
$insertSignup = mysql_query("UPDATE Table_name SET model_test='$HTMLpost' WHERE identifiant='$id'");
if($insertSignup){
$status = "success";
$message = "OK";
}
else {
$status = "error";
$message = "NOT OK";
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
Thanks !
Simple answer: use mysql_real_escape_string() to change the quotes to make it safe for entry into the database.
$HTMLpost = mysql_real_escape_string($_POST['nHTML']);
$insertSignup = mysql_query("UPDATE Table_name SET model_test='$HTMLpost' WHERE identifiant='$id'");
Longer answer: You should not be using the mysql_() functions as they are being depreciated. Check out prepared statements with PDO or mysqli instead - they will safely handle this for you (and they are not being depreciated).
Reading: http://php.net/manual/en/pdo.prepared-statements.php or google for more - plenty of examples around. Best to learn now before you get stung when the mysql_() functions do get removed.
I use a comment box in my web page and saved user input comments. Now what I want is to display them using AJAX. I set a javascript timer to get comments one by one. But I don't know how to use AJAX to retrieve data. This is the php file
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
$comment_number = rand(1,$counter);
$query_comment = mysql_query("SELECT * FROM comment WHERE comment_id = '$comment_number'");
if (!$query_comment) {
die('Invalid query: ' . mysql_error());
}
while($result_comment = mysql_fetch_array($query_comment)) {
echo $result_comment['comment'];
}
?>
following is the script part in the main file.
function timeMsg()
{
var t=setTimeout("show_comment()",3000);
}
function show_comment(){
}
How should i write the AJAX code to the?
function show_comment()
If someone can explain the AJAX code line by line, I'll be great full.
You have to move your all php script to another php file say getdata.php and use your ajax function in your file where you want to show the data say it is index.php. (this is for easy to use code). Now your index.php file should look like
<html>
<body>
<div id="comments"></div>
</body>
<script src="include/jquery.js" type="text/javascript"></script>
<script type="text/javascript>
function show_comments() {
$.ajax({
url:getdata.php
success:function(data){
$("#comments").append(data);
}
});
</script>
</html>
I am using jquery.ajax function of jquery. This is some hint how you can do this. I hope it will help you to accomplish your task.
Use jQuery's .get() method using the link to your PHP script as URL. That should call your PHP script and your script should echo the output.
You should consider json_encode-ing your output from php script before echoing it.
And I think, instead of doing this -
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
you can query SELECT COUNT(comment_id) from comment and get the count.