Javascript prompt() output to PHP function - php

I've been trying to get user input from a Javascript prompt into a PHP function and have run into a lot a walls doing so. I am at a loss trying jQuery's $.post method- as the PHP simply does not want to execute, not sure why.
Anyways, here is a gist of what I am doing at the moment:
1 A project and its data are loaded from a database- this info is displayed in a table.
2 All data in the table is editable via Javascript prompt(), the code I am using for this is below:
<div id="lvl3"><?php echo $fetchdata['name']; ?></div>
The above work as such: lvl3 is a tag for font styling; blank href to make it act as a link; popupprompt is the prompt function I made, it takes one argument, the 'type' or what is being edited (1 for project name, 2 for project description, ect); return false so the page doesn't reload; php echo to display project data in the table.
3 Once the user clicks the object above- it executes a javascript function called popupprompt taking an argument of 'type', or what project info is being changed. the code for this function is below:
function popupprompt(type) {
switch(type)
{
case 1:
var name = prompt("Project Name:", "");
if (name != null && name != "")
{
//Change Project Name
var getname = name;
var gettype = type;
$.post("edit.php", { type: gettype, name: getname });
} else if (name == "") {
senderror("Please enter a valid Project Name");
} else {
//Prompt canceled
sendnotification('Canceled my ass!');
}
break;
case 2:
//Description?
case 3:
//Version?
case 4:
//Release?
default:
alert("There was an error processing your request.");
break;
} }
Th issue I am having in this function is that nothing in edit.php is executed- and i haven't the slightest clue why. Also, i've had to change the brackets around so it shows properly in the code box- so don't mind those.
4 Anyways, now user input is posted to edit.php- which doesn't work, but i'll post it anyways:
<?php
$type = $_POST['type'];
$name = $_POST['name'];
switch($type) {
case 1:
dbconnect();
$urlext = geturlext();
$authenticated = isauthenticated();
if ($authenticated == false)
{
echo("<script>senderror('Access denied');</script>");
} else {
//Escape and trim input
$input = trim($input);
$input = mysql_real_escape_string($input);
$update = "UPDATE 'projects' SET 'name' = '$input' WHERE 'name' = '$urlext'";
$updatequery = mysql_query($update) or die(mysql_error());
echo("<script>sendnotification('Project Name updated');</script>");
}
break;
default:
break;
}
?>
Again had to move some brackets around. But anyways- this function is supposed to update the data in the database- however, it instead does nothing. I've placed alerts in the beginning and they are never called.
Anyways, long story short- if you know what i'm doing wrong please enlighten me, also, if there is a better way to do this- please let me know!
I appreciate all help,
Thanks

Figured it out after a good week of setting it aside. Took a long look at it in firebug, rooted out a typo that was causing most of my issues and also a MySQL syntax error.
I don't know why, but my custom error reporting system does not work when called from a file in this manner. It might be another thing i'm overlooking but firebug sure helped.
Thanks to those who tried to help <3

Related

Checking multiple $_ POST words with PHP

I'm working with a page that, once a link is called this script checks and if the POST contains the keyword it and then finds that page. However no matter how I organize this if it doesn't work.
<?PHP
if($_POST['page']) {
$page = (int)$_POST['page'];
$exists = file_exists('pages/page_'.$page.'html');
if($exists) {
echo file_get_contexnts('pages/page_'.$page.'html');
} else {
echo 'There is no such page!';
}
} else if ($_POST['course']) die("0"); {
$course = (int)$_POST['course'];
$exists = file_exists('courses/course_'.$course.'html');
if($exists) {
echo file_get_contexnts('courses/course_'.$course.'html');
die("1");
} else {
echo 'There is no such page!';
}
}
?>
The error I'm currently receiving with this setup is:
Notice: Undefined index: course in C:\wamp\www\Home Page\load_page.php on line 12
Call Stack
# Time Memory Function Location
1 0.0003 253944 {main}( ) ..\load_page.php:0
Is it because there is no 'course' in the page? I might be confused of the code I'm modifying a tutorial of a simple ajax website. It is possible what I am trying to do does not work.
In that case how could I possible go about doing what I want to do.
Right now I have a home page and it loads in another page without switching pages. I like the floridness of it. I would like to have a sort of sub call. So if you are on the home page and you go to courses page then you can click on a specific course and that will load from a different directory within the courses directory.
Homepage (when you click on courses you go to...)
pages/courses_home.html (when you click on a course you go to...)
courses/course_1.html (you can view course and then click back to directory above or go to home)
That is the structure I'm looking to try to achieve.
If more information is needed please let me know what and I'll do my best to include it. Thank you.
The syntax should be:
if(isset($_POST["page"])) {
} elseif(isset($_POST["course"])) {
}
I am not sure why you have a die statement there, but I don't think it belongs. Also, keep in mind the logic for what happens if neither of these conditions is met.
Edit: also keep in mind that isset doesn't prevent empty strings, so you may want to check for that as well. A function you could use is
function checkPost($value) {
return isset($_POST[$value]) && $_POST[$value] !== "";
}
To use:
if(checkPost('page')) {
//some logic
}
Wrong syntax.
elseif ($_POST['course']) {
without die statement.If 'course' undefined else statement works and does not get error. Sorry for bad English.
Try this:
if isset(($_POST['page'])) {
...
} else if isset(($_POST['course'])) die("0"); {
instead of this:
if($_POST['page']) {
...
} else if ($_POST['course']) die("0"); {

php countering in javascript doesn't work

okay here is my code :
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php $i++; ?>
}
i'm still learning about this whole php and javascript thing, and i know there are many things that i still had to work to to improve my understanding to this both language. that's why i really need your help in this
i'm trying to get the while iteration to work so i can compare the variable from javascript with variable from php which took the value from database. the php variable ('$mfr' and '$mto'), as you can see, is an array. now i want it to look at every element of both and if it meets the condition then it will update the variable 'comp' and stop the whole while iteration
but the problem is the '$i' variable doesn't do the iteration thing. it runs only once so my '$mfr' and '$mto' value doesn't go anywhere. how can i fix this so i can compare the javascript value with the php '$mfr' and '$mto' value?
your help would be much appreciated, thank you :)
EDIT
well, it is actually a function of custom validation for jqgrid.
and i do know that php is a server-side and javascript is a client-side language theoretically, though i don't really know it is practically
what i'm actually trying to do is when a user input a value and submit it, the system will check whether the value that was entered are between value of 'fromid' and 'toid' column of a table in database
here is my full code of the function
function checkid(value)
{
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php echo $i++; ?>
}
if (comp != 'T')
{
return [true, "", ""];
}
else
{
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
while this is how i got the '$mfr' and '$mto' variable
<?php
$db=new database($dbtype, $dbhost, $database, $dbuser, $dbpassword, $port, $dsn);
$db->query("select fromid, toid from CORE_ID");
$i = 0;
while($row = $db->get_row())
{
$mfr[$i] = $row[fromid];
$mto[$i] = $row[toid];
$i++;
}
?>
if theres any better way to do this, then please do tell me
Typically, PHP is for server side logic and JS is for client side logic. If you want to send a value from JS to be processed in PHP, you'll probably need to use something like AJAX, which jQuery makes pretty easy with jQuery.ajax().
Getting the client value to be processed is the difficult part. Once you can do that, rewriting your code logic in full PHP should not be difficult.
EDIT: If I'm misunderstanding where variable value comes from, please say so!
EDIT 2: It looks like you want to have client input compared to server side data. JS will not have access to your PHP variables unless they are specifically sent there. Likewise, you can send your JS value to the server for validation in the PHP.
In your case, you could use JSON to send send the JS your validation dates. Assuming you don't have too many dates, it will probably be faster than sending a value to the server and waiting for a response.
I found a good example of using JSON at another post. You can send an array like:
<?php
$xdata = array(
'foo' => 'bar',
'baz' => array('green','blue')
);
?>
<script type="text/javascript">
var xdata = <?php echo json_encode($xdata); ?>;
alert(xdata['foo']);
alert(xdata['baz'][0]);
// Dot notation can be used if key/name is simple:
alert(xdata.foo);
alert(xdata.baz[0]);
</script>
For your code, you could put $mfr and $mto into a single 2D array. Here is how your new JS might look, assuming xdata contains $mfr and $mto:
function checkid(value) {
var co = 0, comp = '', i = 0, nrows = xdata.mfr.length;
while (co < nrows) {
if ((parseInt(value) >= xdata.mfr[i]) && (parseInt(value) <= xdata.mto[i])) {
comp = 'T';
break;
}
co++;
i++;
}
if (comp != 'T') {
return [true, "", ""];
} else {
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
You have a loop in your Javascript, not your PHP. So the PHP is only going to get executed once. You need to rethink your approach. Without knowing what the script is supposed to actually achieve it's difficult to provide working code, but you at least need to put the loop into the PHP instead of the Javascript.
Before I can answer you should understand what's going on exactly:
PHP is being executed on the server, then sends back the result (HTML and Javascript) to the client (the browser).
Javascript is being executed on the client side. So this only starts after PHP is completely done. For this reason you can't mix Javascript and PHP.
Check the source of the page, then you'll see exactly what the server returns (what HTML/Javascript PHP generates) and you'll get a better insight of what happens.
Now, if you understand this, you may be able to solve your own problem. I don't exactly know what you want to do, but I can advice you that if you need Javascript to check values from the database, you should generate Javascript using PHP that defines these values in the Javascript like for example this:
var my_js_var = <?=$my_php_var?>
var another_var = <?=$another_one?>
Now they are defined in Javascript and you can use them (and check them).
When you have a large database it can become inefficient to do it like this and you might want to look into a technology called AJAX, which allows Javascript to do a request to the server and get back data from a PHP script.
You would also want to do this if there's data involved you don't want to be publicly viewable (because everyone can look into the source of your page.

How Can I Move This <td> Tag To The Next Line?

I have a problem:
Here's a block of the code:
function draw()
{
$out_string="";
$out_string.=$this->script;
reset($this->fields);
$num_list_box=0;
while( $field = each($this->fields) )
{
if (isset($this->fields[$field[1]->field]->options))
{
if (preg_match("/<script type=\"text\/javascript\">/i",$this->fields[$field[1]->field]->options[0][1])&& $this->fields[$field[1]->field]->value!="")
{
if ($num_list_box==0) $out_string.= "<script type=\"text/javascript\">levels.forValue(\"".$field_prev[0]."\").setDefaultOptions(\"".$this->fields[$field[1]->field]->value."\");</script>\n";
else $out_string.= "<script type=\"text/javascript\">levels.forValue(\"".$field_prev[0]."\").forValue(\"".$field_prev[1]."\").setDefaultOptions(\"".$this->fields[$field[1]->field]->value."\");</script>\n";
$field_prev[]=$this->fields[$field[1]->field]->value;
$num_list_box++;
} else
{
$field_prev[0]=$this->fields[$field[1]->field]->value;
$num_list_box=0;
}
}
}
$out_string.=$this->draw_title();
$out_string.=$this->draw_header();
$out_string.= "<table class=\"forms\">\n";
$field=array_keys($this->fields);
reset($field);
$ind_first=true;
while( list($pos,$field_name) = each($field) )
{
if ($this->num_cols>0) {
if ($this->fields[$field_name]->col==1){
if ($ind_first) $ind_first=false;else $out_string.="</tr>";
$out_string.="<tr><td class=\"field_title\">";}
else $out_string.="<td class=\"field_title\">";
$out_string.= $this->fields[$field_name]->title."</td>";
$colspan="";
if ($this->num_cols>1) {
if ($this->fields[$field_name]->col==1 && array_key_exists($pos+1,$field) && $this->fields[$field[$pos+1]]->col==1)
$colspan="colspan=\"3\"";
}
$out_string.="<td class=\"field_value\" $colspan>";
$out_string.=$this->fields[$field_name]->draw()."</td>";
} else
{
if ($ind_first) $ind_first=false;else $out_string.="</tr>";
$out_string.="<tr><td class=\"field_value\">".$this->fields[$field_name]->title."<br />";
$out_string.=$this->fields[$field_name]->draw()."</td>";
}
}
$out_string.= "</tr></table>\n";
return $out_string;
}
This above block of code produces something like this:
I want it such that in the example provided that the word "Transaction" is above the text box.
Please help, the person that programmed this part is indisposed and we've got a deadline.
Thanks for the help.
P.S. The CSS class name for the text is: field_title and the one for the textbox is field_value
Thanks once more.
You will have to debug that code to find out when the label "Transaction" is getting inserted into that cludge of table code. Once you find where "Transaction" is inserted you can then create new logic to add another TR that colspans the table and place the label on that new row.
Good luck, looks like a headache.
Your code is apparently building a rather complex form based on some data ($fields property of the class). I guess some "field settings" (like col) describe how the form should look like.
So, your code is doing things that are neither described in your question nor in the code itself. Furthermore, we have no clue what the complete form currently looks like, so we can't even guess the intention of the code.
Your request, to let the description appear above the selection box(?) could be done probably throwing away half of the code, but that won't help you.
PS: Please check the FAQ - this site is for questions, not for finding people to do your (or elses) work. You should really have a programmer solve your problem directly having access to the whole page.

Running a function by typing in URL

I have searched all over the internet to run a function from URL and found out it is not possible.
I am asking if there is another way to do this. I will explain below what I am trying to achieve.
On my website I have several functions that when a hyperlink is clicked on that cracks.php page, the main content changes accordingly. Now I want to direct people from a single URL to that cracks.php page with the function already called.
Example - www.example.com/cracks.php?AC ( which will call a function named AC and the content changes before the page loads)
Ive found this method below, but couldnt get it to work.
if(document.location.search == '?AC')
{
AC();
}
Sorry for the messy code on the website. Thanks for reading, any help would be appreciated.
You can call www.example.com/cracks.php?do=AC and then get do with $doMethod = $_GET['do'];. What you then do is, use a switch function or a few ifs to check and execute when e.g. $doMethod equals AC.
Like this:
$doMethod = $_GET['do'];
switch($doMethod)
{
case "AC":
//some random stuff to do
break;
case "BD":
//some random stuff to do
break;
case "XY":
//some random stuff to do
break;
default:
break;
}
That depends if you need to do that dynamically or you can do it hard coded. Because that hard coded is too simple (with if's and switches), what you have to do is:
$functionsList = Array('func1', 'func2');
function func1(){
echo '1';
}
function func2(){
echo '2';
}
if (function_exists($_GET['f']) and in_array($_GET['f'], $functionsList)){
call_user_func($_GET['f']);
}
Then call your_file_name.php?f=func1 and your_file_name.php?f=func2 and you'll see different outputs.
With the help of Mark Koopman I managed to use his Javascript method and it worked like I wanted.
So heres the method in Javascript:
<html>
<body>
<script>
function handleOnload()
{
if(location.search == "?AC")
alert("the query string is " + location.search);
}
window.onload=handleOnload;
</script>
</body>
</html>

PHP session not working with JQuery Ajax?

Update, Solved:
After all this I found out that I was calling an old version of my code in the update ajax.
'boardControl.php' instead of 'boardUpdate.php' These are the kinds of mistakes that make programing fun.
I'm writing a browser gomoku game. I have the ajax statement that allows the player to play a piece.
$(document).ready(function() {
$("td").live('click',function(){
var value = $(this).attr('id');
$.get('includes/boardControl.php',{play: value, bid: bid});
});
});
value = board square location
bid = board ID
Before creating a user login for player identification, the server side php had a temporary solution. It would rotate the piece state for the squares when clicked instead of knowing what player to create them for.
After creating login stuff I set a session variable for the player's ID. I was hoping to read the session ID from the php during the ajax request and figure out what player they are from there.
session_start();
...
$playerId = $_SESSION['char'];
$Query=("SELECT p1, p2 FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$p1 = mysql_result($Result,0,"p1");
$p2 = mysql_result($Result,0,"p2");
$newPiece = 0; //*default no player
if($playerId == $p1)
$newPiece = 1;
if($playerId == $p2)
$newPiece = 2;
For some reason when I run the full web app, the pieces still cycle though, even after I deleted the code to make them cycle.
Furthermore, after logging in If i manually load the php page in the browser, it modifies the database correctly (where it only plays pieces belonging to that player) and outputs the correct results.
It seems to me that the session is not being carried over when used with Ajax. Yet Google searches tell me that, sessions do work with Ajax.
Update: I'm trying to provide more information.
Logging in works correctly. My
ID is recognized and I printed it
out next to the board to ensure that
I was retrieving it correctly.
The ajax request does update the
board. The values passed are
correct and confirmed with firebug's
console. However instead of placing
pieces only for the player they
belong to it cycles though the piece
states (0,1,2).
When manually browsing to
boardUpdate.php and putting in the
same values sent from the Ajax the
results seen in the echo'ed response
indicates that the corresponding
piece is played each time as
intended.
Same results on my laptop after
fresh load of firefox.
Manually browsing to
boardUpdate.php without logging in
before hand leave the board
unchanged (as intended when no user
is found in the session).
I've double checked the that
session_start() is on the php files
and double checked the session ID
variables.
Hope this extra information helps, i'm running out of ideas what to tell you. Should I load up the full code?
Update 2:
After checking the Ajax responce in fire-bug I realized that the 'play' request does not get a result, and the board is not updated till the next 'update'. I'm still looking into this but I'll post it here for you guys too.
boardUpdate.php
Notable places are:
Refresh Board(line6)
Place Piece(line20)
function boardUpdate($turnCount) (line63)
<?php
session_start();
require '../../omok/dbConnect.php';
//*** Refresh Board ***
if(isset($_GET['update']))
{
$bid = $_GET['bid'];
$Query=("SELECT turn FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$turnCount=mysql_result($Result,0,"turn");
if($_GET['turnCount'] < $turnCount) //** Turn increased
{
boardUpdate($turnCount);
}
}
//*** Place Piece ***
if(isset($_GET['play'])) // turn order? player detect?
{
$squareID = $_GET['play'];
$bid = $_GET['bid'];
$Query=("SELECT turn, boardstate FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$turnCount=mysql_result($Result,0,"turn");
$boardState=mysql_result($Result,0,"boardstate");
$turnCount++;
$playerId = $_SESSION['char'];
$Query=("SELECT p1, p2 FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$p1 = mysql_result($Result,0,"p1");
$p2 = mysql_result($Result,0,"p2");
$newPiece = 0; //*default no player
if($playerId == $p1)
$newPiece = 1;
if($playerId == $p2)
$newPiece = 2;
// if($newPiece != 0)
// {
$oldPiece = getBoardSpot($squareID, $bid);
$oldLetter = $boardState{floor($squareID/3)};
$slot = $squareID%3;
//***function updateCode($old, $new, $current, $slot)***
$newLetter = updateCode($oldPiece, $newPiece, $oldLetter, $slot);
$newLetter = value2Letter($newLetter);
$newBoard = substr_replace($boardState, $newLetter, floor($squareID/3), 1);
//** Update Query for boardstate & turn
$Query=("UPDATE board SET boardState = '$newBoard', turn = '$turnCount' WHERE bid = '$bid'");
mysql_query($Query);
// }
boardUpdate($turnCount);
}
function boardUpdate($turnCount)
{
$json = '{"turnCount":"'.$turnCount.'",'; //** turnCount **
$bid = $_GET['bid'];
$Query=("SELECT boardstate FROM board WHERE bid='$bid'");
$Result=mysql_query($Query);
$Board=mysql_result($Result,0,"boardstate");
$json.= '"boardState":"'.$Board.'"'; //** boardState **
$json.= '}';
echo $json;
}
function letter2Value($input)
{
if(ord($input) >= 48 && ord($input) <= 57)
return ord($input) - 48;
else
return ord($input) - 87;
}
function value2Letter($input)
{
if($input >= 10)
return chr($input += 87);
else
return chr($input += 48);
}
//*** UPDATE CODE *** updates an letter with a new peice change and returns result letter.
//***** $old : peice value before update
//***** $new : peice value after update
//***** $current : letterValue of code before update.
//***** $slot : which of the 3 sqaures the change needs to take place in.
function updateCode($old, $new, $current, $slot)
{
if($slot == 0)
{// echo $current,"+((",$new,"-",$old,")*9)";
return letter2Value($current)+(($new-$old)*9);
}
else if($slot == 1)
{// echo $current,"+((",$new,"-",$old,")*3)";
return letter2Value($current)+(($new-$old)*3);
}
else //slot == 2
{// echo $current,"+((",$new,"-",$old,")";
return letter2Value($current)+($new-$old);
}
}//updateCode()
//**** GETBOARDSPOT *** Returns the peice value at defined location on the board.
//****** 0 is first sqaure increment +1 in reading order (0-254).
function getBoardSpot($squareID, $bid)
{
$Query=("SELECT boardstate FROM board WHERE bid='$bid'");
$Result=mysql_query($Query);
$Board=mysql_result($Result,0,"boardstate");
if($squareID %3 == 2) //**3rd spot**
{
if( letter2Value($Board{floor($squareID/3)} ) % 3 == 0)
return 0;
else if( letter2Value($Board{floor($squareID/3)} ) % 3 == 1)
return 1;
else
return 2;
}
else if($squareID %3 == 0) //**1st spot**
{
if(letter2Value($Board{floor($squareID/3)} ) <= 8)
return 0;
else if(letter2Value($Board{floor($squareID/3)} ) >= 18)
return 2;
else
return 1;
}
else //**2nd spot**
{
return floor(letter2Value($Board{floor($squareID/3)}))/3%3;
}
}//end getBoardSpot()
?>
Please help, I'd be glad to provide more information if needed.
Thanks in advance =)
From the small snippet of code we have, it's difficult to tell what your problem might be. What I can say is that session_start should be one of the first things you do on each page where you're expecting to use the session. After that, I would just immediately do a var_dump of $_SESSION to see that the data is in there (put a die right after that). It is quite possible that your true problem lies somewhere else, and that the session is in fact working. Is there a problem with your login code, for example, that is causing it to wipe out the session?
You can use Firebug to look at the raw results of your AJAX calls, which should be helpful, since your script appears to work if you directly visit the page.
Cases where I've seen sessions not work as expected have generally been that session_start is being called too often or too late. The other possibility is that you have an insanely short timeout, but that sounds unlikely.
Finally, you can make sure that your PHP install is set to use cookie sessions. It's very unlikely at this point that it wouldn't be, but you could look.
One potential problem in this code is the use of $.get - it is cached by IE, so your server code doesn't run every time. Try using $.ajax with cache set to false:
$.ajax({
type: 'GET',
url: 'includes/boardControl.php',
cache: false,
data: {play: value, bid: bid}
});
Just happened to me, in my case was that i was importing a config file with the session_start and since i had deactivated errors i couldn't see that the import was never happening. Just triple check this, I know it's the basic.

Categories