i try to send some data from html to process page. i want to do this use javascript.
the javascript is:
$('#search').click(function(){
var param = serialize({
action:"searchmodelqp",
jhead:"aaData",
month:$("#search_month").val(),
year:$("#search_year").val(),
export:"excel"
});
$('#link2excel' ).replaceWith("<div id='link2excel'><a href='shows_merchan.php?" + param + "' target='_blank'>Export result as Excel file</a></div>");
});
and i send it to this:
if(getVar('export')=='excel'){
$expexcel = 'excel';
} else {
$expexcel=0;
}
switch(getVar('action')){
case 'searchmodelqp':
modelqp(getVar('jhead'),getVar('month'),getVar('year'),getVar('export'));
break;
}
function modelqp($jsonhead,$month, $year,$export){
$Month = mysql_real_escape_string($month);
$Year = mysql_real_escape_string($year);
switch($jsonhead){
case 'aaData':
//i put mysql query here
break;
}
if($export==0) {
//do something
} else {
//do something
}
how do i do to make it clear?because i have no result for this(script do nothing).
change your data as below
data:action="searchmodelqp&jhead="aaData"&month=$("#search_month").val()&year=$("#search_year").val()&export="excel"
i change at this part:
var param = jQuery.param({action:"searchmodelqp",jhead:"aaData",month:$("#search_month").val(),year:$("#search_year").val(),export:"excel"});
Related
I have these jQuery code.
I generate 6 digits random number and I need to pass it into .post Serialize every time button is clicked. I want the number generate inside jQuery click function.
Somehow I cannot pass the value of "var tac_no" into .post Serialize.
Here's my code for jQuery
$('#request_code').click(function(e){
var tac_no = Math.floor(100000 + Math.random() * 900000);
var data_tac = $("#form-tac").serialize()+"&type="+"updateTable";
$.post("php/ajax-request-tac.php",data_tac).done(function( data ){
if(data==true)
{
alert('Request Success');
}
else if(data==false)
{
alert('Request failed');
}
});
return false;
});
And here's my php code
<?php
require 'conn.php';
function oracle_escape_string($str)
{
return str_replace("'", "''", $str);
}
if((isset($_POST['type'])) && ($_POST['type']=='updateTable'))
{
$sqlNextSeq = "SELECT SEQ_TAC.nextval AS RUNNO FROM DUAL";
$stid2 = oci_parse($ociconn,$sqlNextSeq);
oci_execute($stid2);
$row = oci_fetch_array($stid2, OCI_RETURN_NULLS);
$query = "insert into table
(
ID,
TAC_NO
)
values
(
'".$running_no."',
'".oracle_escape_string($_POST['tac_no'])."',
)
";
oci_execute(oci_parse($ociconn, $query));
echo true;
}
?>
Any idea how to do that ?
Appreciate if someone can help me. Thanks.
Personally, I'd generate the random number in PHP, but I think the issue is that you're not passing the data properly into PHP with thepost() function:
$.post("php/ajax-request-tac.php",data_tac).done(function( data ){
Instead you should pass it in as an object:
$.post("php/ajax-request-tac.php",{data_tac: data_tac, tac_no: tac_no}).done(function( data ){
Append that number to tac_no directly,
$('#request_code').click(function(e) {
var tac_no = Math.floor(100000 + Math.random() * 900000);
var data_tac = $("#form-tac").serialize() + "&type=" + "updateTable"+"&tac_no="+tac_no;
$.post("php/ajax-request-tac.php", data_tac).done(function(data) {
if (data == true) {
alert('Request Success');
} else if (data == false) {
alert('Request failed');
}
});
return false;
});
Anyway its front end code, user can always see what you are sending, so security won't be covered.
I am sending data to a php file using AngularJS on ng-click. I have 2 buttons and I am trying to send it to the same php file to insert into the db using switch case but it is not updating the db.
How can I fix my php?
insert.php
<?php
include_once('conn.php');
$data = json_decode(file_get_contents("php://input"));
switch($data){
case 'getvou':
$vou = $data->getvou;
$sql = $mysqli->query("UPDATE audiencia SET vou = '".$vou."'");
$mysqli->close();
break;
case 'getnaovou':
$naovou = $data->getnaovou;
$sql = $mysqli->query("UPDATE audiencia SET nao_vou = '".$naovou."'");
$mysqli->close();
break;
}
?>
script.js
$scope.add_vou = function(){
$scope.vou += 1;
$http.post("http://localhost/insert-audiencia.php", {'getvou': $scope.vou}).then(function(resp){
console.log(JSON.stringify(resp));
console.log(resp);
});
}
$scope.add_nao_vou = function(){
$scope.nao_vou += 1;
$http.post("http://localhost/insert-audiencia.php", {'getnaovou': $scope.nao_vou}).then(function(resp){
console.log(JSON.stringify(resp));
console.log(resp);
});
}
$data will be a JSON object, which will not equal either of those strings, so no case will be matched in your switch.
With the way you're currently sending the data, you need to be checking instead to see if the JSON object has a property.
if (property_exists($data, 'getvou')) {
// one query
} elseif (property_exists($data, 'getnaovou')) {
// other query
}
isset($data->getvou) etc. will also work for this.
Little problem about sending PHP array to javascript function, i did homework looked everywhere and i know its not reliable to do this, but at this moment i do not know any other way , so try to just advice me how to finish it anyway.
I got php code executing first , idea is on page load i get some data from MySQL , i filled php array with IDs from that select statement.
<?php
include('config.php');
$TicketExist = "select BetSlipID,probatip1.betslips.MatchID as GameID,
TipID,tim1.Name AS HomeTeam ,tim2.Name AS AwayTeam, UserID
from probatip1.betslips
inner join probatip1.matches matches on probatip1.betslips.MatchID = matches.MatchID
inner join probatip1.teams tim1 on matches.HomeTeamID = tim1.TeamID
inner join probatip1.teams tim2 on matches.AwayTeamID = tim2.TeamID
where UserID = 1";
$TicketResult = mysql_query($TicketExist);
$TicketNum = mysql_numrows($TicketResult);
mysql_close();
if($TicketNum != 0)
{
$s=0;
while($s < $TicketNum)
{
$GameID = mysql_result($TicketResult,$s,"GameID");
$TipID = mysql_result($TicketResult,$s,"TipID");
$ArrayIDs[$s] = $GameID;
echo "<script>window.onload=GetInfo($GameID,$TipID); </script>";
$s++;
}
}
?>
So i got it everything i want filled and wrote on my page , idea now is on user click , to call javascript to take this '$ArrayIDs' and execute code from script
Here is code im calling script
<ul>
<li
id="ConfirmButton" name="Insert" method="post"
onclick="GetAllIDs(<?php $ArrayIDs ?>)"><a>POTVRDI</a></li>
</ul>
And my script code
function GetAllIDs(Ticket) {
$("td.ID").each(function () {
var MatchID = $(this).attr('id');
var lab = "Label";
var Label = lab + MatchID;
var Final = document.getElementById(Label);
var TipID;
if (Final.innerHTML == '1') {
TipID = 1;
}
else if (Final.innerHTML == 'X') {
TipID = 2;
}
else if (Final.innerHTML == '2') {
TipID = 3;
}
else {
return;
}
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var AlreadyPlayed = false;
if (Ticket != null) {
var TicketExists = Ticket;
for (var i = 0; i < TicketExists.length; i++) {
if (TicketExists[i] == MatchID) {
AlreadyPlayed = true;
break;
}
}
}
if (http != null) {
if (AlreadyPlayed == true) {
http.open('get', 'update.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
else {
http.open('get', 'insert.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
http.send(null);
}
});
if (Ticket == null) {
alert('Tiket je napravljen');
}
else {
alert('Tiket je promenjen');
}
}
With this posted code when i am debugging code with firebug in mozzila i get that my 'Ticket' parameter that suppose to be '$ArrayIDs' is undefined.
Reason why i want to make array and send it to javascript onclick event is to check if user already placed a bet on some game , if he did i want to send all data for update and if he did not yet placed bet on some game to send data for insert in database.
So i need array and before anything just to check MatchID with all IDs in my array, so i know what to do.
Thanks all in advance for helping out
Your script could do with a bit of cleanup, but in essence you need to change
onclick="GetAllIDs(<?php $ArrayIDs ?>)">
to
onclick="GetAllIDs(<?php echo json_encode($ArrayIDs) ?>)">
I'd also reccomend not outputting
"<script>window.onload=GetInfo($GameID,$TipID); </script>";
for each row in mysql, instead create a single array of the values and create one script after the loop. Using mysql_fetch_row instead of mysql_numrows and mysql_result is probably neater.
while ($row = mysql_fetch_row($result)) {
//...do things here...
}
You need to output the array as valid JavaScript, use json_encode
GetAllIDs(<?php echo json_encode($ArrayIDs); ?>)
So i'm working on a javascript/php chatbox. Everything works except for it updating the contents of my div (this works once, but after that it doesn't keep updating it when a new message has been put into the database). Here is my code:
Javascript part:
<script language=javascript type='text/javascript'>
setInterval(function () {
var arrayOfObjects = <?print_r(getChatArray());?>;
var chat = "";
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
chat += "["+object.date+"]"+object.op+": " + object.msg + "</br>";
}
$('#chat').html(chat);
}, 10);
</script>
Php part:
<?php
function getChatArray() {
$result = mysql_query("SELECT * FROM shouts ORDER BY id DESC");
$to_encode = array();
$count = mysql_num_rows($result);
$size = 0;
if($count > 0) {
while($row = mysql_fetch_assoc($result)) {
$to_encode[$size]['id'] = $row['id'];
$to_encode[$size]['msg'] = $row['msg'];
$to_encode[$size]['op'] = $row['op'];
$to_encode[$size]['date'] = $row['date'];
$size += 1;
}
} else {
return "None";
}
return json_encode($to_encode);
}
?>
Any ideas as to why it isn't continually updating it?
Thanks.
Because every 10 milliseconds your JS is parsing the original chat room contents, you're not fetching any new contents. You'll need to implement an ajax call, and I'd highly recommend changing that setInterval to a recursive setTimeout with a more realistic delay of say 500ms so you don't kill the client.
Instead of this:
setInterval(function() {
var arrayOfObjects = <?print_r(getChatArray());?>;
...
You would use something like this:
(function updateChat(){
var arrayOfObjects,
chat,
max,
_object,
i = 0;
$.ajax({
url : '/getChatArray.php', // php echoes the json
success: function(arrayOfObjects){
for (max = arrayOfObjects.length; i < max; i++) {
_object = arrayOfObjects[i];
chat += "["+_object.date+"]"+_object.op+": " + _object.msg + "</br>";
}
$('#chat').html(chat);
setTimeout(updateChat, 500);
}
});
}());
Obviously you would populate that ajax handler to your needs, add some more params like dataType, etc, and some error handling.
Your database contents will only be output to the page on initial navigation to it.
This code:
var arrayOfObjects = <?print_r(getChatArray());?>;
Will only output the contents of getChatArray()'s return when PHP renders the page. So the script can only see one state of that functions return at the time of rendering.
You need to use AJAX to retrieve the content from your database asynchronously.
I suggest you:
Create a PHP script which outputs your data in JSON format
Use jQuery, specifically the getJSON function to retrieve that script's output
Do what you want to do with that data.
I am wanted to get the id's of all the divs on my page with the class archive and put them in a MySQL query to check and see if the ids are archived in the database.
So basically I am wondering how I can do this: $div = $(this).attr('id');
Then I would throw it into the loop to check:
$matches = mysql_query("SELECT * FROM content WHERE `div` = '$div'");
while ($post = mysql_fetch_assoc($matches))
{
if (mysql_num_rows($matches) > 0)
{
//DO THIS
}
}
UPDATE
I have this code for the AJAX now:
$('div.heriyah').each(function() {
var curID = $(this).attr('id');
$.post("admin/btnCheck.php", { div : curID }, function(data) {
if (data == "yes") {
$('#' + curID).html('<div class=\"add\"><div id=\"add_button_container\"><div id=\"add_button\" class=\"edit_links\"> + Add Element</div></div></div><div class=\"clear\"></div></div>');
} else {
$('#' + curID).html('<div class=\"add\"><div id=\"add_button_container\"><div id=\"add_button\" class=\"edit_links\"> + Set As Editable Region</div></div></div><div class=\"clear\"></div></div>');
}
});
});
And my PHP:
$matches = mysql_query("SELECT * FROM content WHERE `div` = '".$_POST['div']."'");
if (mysql_num_rows($matches) > 0)
{
echo "yes";
} else {
echo "no";
}
What am I doing wrong?
You cannot throw a javascript variable to PHP script like that. You have to send an ajax request to the page
$div = $(this).attr('id');
$.post("yourquerypage.php", { divid : $div }, function(data) {
// Something to do when the php runs successfully
});
Next, configure your query to get the variable from $_POST()
$matches = mysql_query("SELECT * FROM content WHERE `div` = '".$_POST['divid']."'");
And of course, you have to take measures for injection.
It's simple syntax error. Remove the condition after the else and you should be fine.
else (data == "yes") { // remove (data == "yes")
// snip
}