Put DIV ID into a PHP Variable - php

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
}

Related

How to pass value into .post Serialize using jQuery?

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.

Couldn't get response from database with jQuery using PHP post request

I cannot get this script work. I try to warn if login that user entered is available. But I cannot manage this script to work:
$( "#myRegForm" ).submit(function( event ) {
var errors = false;
var userAvi = true;
var loginInput = $('#login').val();
if( loginInput == ""){
$("#errorArea").text('LOGIN CANNOT BE EMPTY!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if(loginInput.length < 5 ){
$("#errorArea").text('LOGIN MUST BE AT LEAST 5 CHARACTERS!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if (loginInput.length >=5) {
$.post('checkLogin.php', {login2: loginInput}, function(result) {
if(result == "0") {
alert("this");
}
else {
alert("that");
}
});
}
if (errors==true) {
return false;
}
});
Everything works fine until loginInput.length >=5 else block. So I assume there is a problem with getting answer from PHP file, but I cannot handle it, though I tried many different ways. Here is checkLogin.php's file (note that jQuery script and PHP file are in the same folder):
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}
else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo "0"; // for you to use if(if(result == "0") you should send a string
} else {
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo "1";
}
?>
You're literally sending the string 'loginInput'.
change
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) {
to
$.post('checkLogin.php', {login2: loginInput}, function(result) {
Edit
I would just comment out everything except the following for now and see if that at least works
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) { // put loginInput back in quotes
alert('#'+result+'#'); // # to check for whitespace
});

How do I make an onclick ajax request for favorites button work properly

I have a list on my site that has a favorites button associated with each item on the list. I am using an image as the button to click. The PHP for it is:
echo "<img src=\"./images/emptystar.png\" alt=\"favorite\" class=\"favoritebutton\" billid=\"" . $count['id'] ."\" userid=\"". $_SESSION['userid'] ."\" />\n";
I have javascript/jQuery to make an onclick of that image submit an AJAX request to a PHP file.
$(document).ready(function() {
$(".favoritebutton").click(function () {
var billid = $(this).attr("billid");
var userid = $(this).attr("userid");
var ajaxrequest;
var params = "billid=" + billid + "&userid=" + userid;
ajaxrequest.open("POST","./ajaxphp/favorites.php",true);
ajaxrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxrequest.setRequestHeader("Content-length", params.length);
ajaxrequest.setRequestHeader("Connection", "close");
ajaxrequest.send(params);
ajaxrequest.onreadystatechange=function()
{
if (ajaxrequest.readyState===4 && ajaxrequest.status===200)
{
if(ajaxrequest.responseText === "true")
{
if($(this).attr("src") === "./images/emptystar.png")
{
$(this).attr("src","./images/fullstar.png");
}
else
{
$(this).attr("src","./images/emptystar.png");
}
}
}
};
});
});
The php file at ./ajaxphp/favorites.php is the following:
<?php
include("./includes/dbcxnfunction.inc");
$billid = $_POST['billid'];
$userid = $_POST['userid'];
$query = "IF NOT EXISTS (SELECT * FROM favoritebills WHERE userid = '$userid' AND billid = '$billid' )
INSERT INTO favoritebills (userid,billid) VALUES($userid,$billid)
ELSE
DELETE FROM favoritebills WHERE userid = '$userid' and billid = '$billid' ";
$result = mysqli_query(dbcxn('bill'),$query)
or exit("Couldn't execute query for favorites");
if($result)
{
$request = "true";
}
else
{
$request = "false";
}
echo $request;
?>
In particular I am concerned with the SQL query and the javascript because I am not certain of their correctness, but I used a validator for the javascript with JQuery and everything is valid.
When I click the image on the page, nothing happens even though I have tested both conditions for the image change. Either the javascript is written incorrectly, or there is never a response sent back from the favorites.php file.
The network tab in console.
Use JQuery's .ajax and pass the clicked element by storing it in var before you make the ajax call
$(".favoritebutton").click(function () {
//Store $(this) in var so that it can be passed inside the success function
var this$ = $(this);
var billid = this$.attr("billid");
var userid = this$.attr("userid");
$.ajax( { url : "./ajaxphp/favorites.php", type: 'post', data : { billid : billid , userid : userid },
success : function( responseText ){
if( responseText == "true"){
if( this$.attr("src") == "./images/emptystar.png"){
this$.attr("src","./images/fullstar.png");
}else{
this$.attr("src","./images/emptystar.png");
}
}
},
error : function( e ){
alert( ' Error : ' + e );
}
});
});

Passing js variables to php using jquery

I'm trying to do a realllly simple post of a javascript variable to a php file.
Jquery bit in keyinput.php:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($cat, $site)) ?>];
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).keydown(function (e) {
var key = e.which;
int rightarrow = 39;
int leftarrow = 37;
int random = 82;
if (key != rightarrow && key != leftarrow && key != random) {
return;
}
else {
//next image: right arrow
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
}
//last image: left arrow
if (key == leftarrow)
{
if (imgIndex == 0)
{
imgIndex = imgArray.length;
}
img.src = imgArray[--imgIndex];
}
//random: r
if (key == random)
{
imgIndex = Math.floor((Math.random()*(imgArray.length-1))+1);
img.src = imgArray[imgIndex];
}
}
$.post('./templates/viewcomic.php', {variable: imgIndex});
});
});
</script>
<?php
function getImages($catParam, $siteParam) {
include './scripts/dbconnect.php';
if ($siteParam == 'artwork') {
$table = "artwork";
}
else {
$table = "comics";
}
if ($catParam != null) {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table WHERE catidFK = $catParam");
}
else {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table");
}
$img = array();
while($row = $catResult->fetch_assoc())
{
$img[] = "'" . $row['path'] . "'";
}
return $img;
}
?>
PHP bit in viewcomic.php:
include './scripts/keyinput.php';
$JSIndex = $_POST['variable'];
echo "Index = " . $JSIndex;
//$JSIndex should be equal to the javascript variable imgIndex... but it outputs nothing
Any thoughts would be extremely helpful! I'm trying to get my comics website to go live.
Thanks!
Your logic is wrong: at the moment you define your key variable, e is undefined. Then you attach your event handler inside an if statement that will always evaluate to false so that will never work.
The assignment to key should be inside your event handler and the conditional needs to go, you already have that inside your event handler.
Edit: you should also only do your ajax call if one of your action keys is pressed (put it inside the event handler) and do something with the result.
Edit 2: Checkout the manual on $.post, you should add a callback function to process the return value of your php script.
For example:
$.post(
'./templates/viewcomic.php',
{ variable: imgIndex },
function(data) { /* data contains what you have echoed out in your php script */
alert(data);
}
);

sending php array to javascript function onclick

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); ?>)

Categories