Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am getting a very self explanatory error. However the index, as far as I can tell is not only 100% defined, it also contains a value. This is the latest of a series of silly problems that's driving me insane today.
Here is the code you've probably seen a million times that should work.
jQuery
$('#projects').click(function (e) {
alert(aid);
$.post('core/functions/projects.php', { aid: aid })
.done(function(data) {
alert(aid);
$('#home_div').hide();
$('#pcd').fadeIn(1000);
})
.fail(function(jqXHR, status, error) {
alert(error);
});
});
Which alerts me twice with the value of 6
PHP
<?php
require_once "$_SERVER[DOCUMENT_ROOT]/core/init.php";
if(isset($_POST)) {
$aid = $_POST['aid'];
echo $aid;
} else {
echo 'fail';
}
?>
I receive this error:
Notice: Undefined index: aid in C:\xampp\htdocs\core\functions\projects.php on line 5
So I added a little deeper check to my if else and it now looks like this
<?php
require_once "$_SERVER[DOCUMENT_ROOT]/core/init.php";
$account_id;
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
echo $aid;
} else {
echo 'fail';
}
and now it spits back fail. I already went here, to check out the error and it's exactly as I thought it was. That doesn't mean it makes any more sense to me why I'm getting it.
So lets review. My jQuery, is hitting the right PHP file because I am getting responses from that specific PHP file. My variable holds a value because jQuery alerts me twice with the value it holds of 6. However my PHP file is not receiving this value? Can someone please explain to me why?
EDIT
If I add a line to my jQuery I get another message verifying the data is being sent. Yet I STILL receive the error that the $_POST index is not set. This is crazy
$('#projects').click(function (e) {
alert(aid);
$.post('core/functions/projects.php', { aid: aid })
.done(function(data) {
alert(aid);
alert(data);
$('#home_div').hide();
$('#pcd').fadeIn(1000);
})
.fail(function(jqXHR, status, error) {
alert(error);
});
});
Now I get 3 Alert boxes holding the value 6.
1 alert box fires before the post is sent with the $aid variable information of '6'
1 alert box fires after the data is received again with the $aid variable '6'
1 alert box fires after the data is received now with the php response which is again '6'!
I mean WTF? Will this nightmare ever end? That means even the variable in php is being set from the post! How is this possible? I mean look at the php code all it echos is either 'fail' or $aid and $aid cant have a value unless its set by the post and furthermore it would NOT be giving me the error of Undefined index. I need to go take a break, I am gonna lose it.
FIREBUG
In firebug I see
I see POST ->
projects.php ->
POST ->
PARAMETERS ->
aid 6 ->
SOURCE -> aid=%0D%0A6
RESPONSE ->
There is nothing in the response, the brief time I posted a response here was because I left my 'require_once' off and I had my code commented out.
There is something odd in the source though. It says SOURCE aid=%0D%0A6 instead of the normal SOURCE aid = 6
2ND EDIT
I had a large section of code commented out to simplify this example. The code uses the variable and query's for data. Then returns a table created in php. If un-comment the code I can see the table in my RESPONSE in html form. If I go to HTML I can actually see the visual table. So Whats going on? Why is that response inflating my div and not the table? I will now post some more code to explain
<?php
require_once "$_SERVER[DOCUMENT_ROOT]/TrakFlex/core/init.php";
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
try {
$query_projectInfo = $db->prepare("
SELECT projects.account_id,
projects.project_name,
projects.pm,
//...more columns
FROM projects
WHERE account_id = ?
");
$query_projectInfo->bindValue(1, $aid, PDO::PARAM_STR);
$query_projectInfo->execute();
$count = $query_projectInfo->rowCount();
if ($count > 0) {
echo "<table class='contentTable'>";
echo "<th class='content_th'>" . "Job #" . "</th>";
echo "<th class='content_th'>" . "Project Name" . "</th>";
//...more table headers
while ($row = $query_projectInfo->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td class='content_td'>" . "<a href='#'>" . $row['account_id'] . "</a>" . "</td>";
echo "<td class='content_td'>" . $row['project_name'] . "</td>";
//.. more data
echo "</tr>";
}
echo "</table>";
}
} catch(PDOException $e) {
die($e->getMessage());
}
} else {
echo 'could not load projects table';
}
?>
So as you can see my full php file actually sends back a table of data. I can see this table in FireBug -> NET -> XHR -> HTML. I can also see all the php code in FireBug -> NET -> XHR -> RESPONSE. However the div that should hold the table only holds the else statement 'could not load projects table'. So I think I'm getting closer, but I'm still stuck. Any ideas?
POST -> aid 6 shows that the server is indeed receiving the data. Something else is clearing $_POST at some point before it reaches the if statement.
While you had require_once "$_SERVER[DOCUMENT_ROOT]/core/init.php"; commented out, your jQuery data contained the expected value. It was still commented out when you posted the Firebug info, hence the database connection error messages. Those messages, which you've since removed, indicates errors on line 7 of projects.php which tells me that your testing a file with more code than you posted here. It's not uncommon for people to show us a portion of their code, in fact, it's encouraged; however, in this case it's problematic because the error doesn't lie in the code you gave us.
Inorder to validate this finding and save your sanity, rename projects.php temporarily to projects.backup.php.
Create a new file called, "projects.php" and run the following code (and ONLY the following code) through AJAX:
<?php
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
echo $aid;
} else {
echo 'fail';
}
?>
Incidentally, %0D%0A is the Windows® newline combo, CRLF (carriage return + line feed)
Related
This question is more about "good pratices" than a real problem; I just started with php and jquery, but I would know more in details what I'm doing and why.
What I'm trying to get: catch user request (with a form), query database and then show result in a table. All using ajax call and jquery.
Now, I have my controller.php:
class Controller {
public $model;
public function __construct() {
$this->model = new Model ();
}
public function run() {
$action = isset ( $_REQUEST ["action"] ) ? $_REQUEST ["action"] : $action = "home";
switch ($action) {
case "home" :
//doing stuff
break;
case "search" :
//this function will take arguments then perform a query and return results.
$result = $this->search();
//I put $result into a $prod field of my model.
$this->model->prod = $result;
//then I would display acquired data into a table.
echo include 'view/include/result-table.php';
break;
}
}
function search() {
//query DB etc..
}
}
And this is my table (view/include/result-table.php), I would like insert this into a div in my page.
<?php
if (isset ( $this->model->prod )) {
if (count ( $this->model->prod ) == 0) {
echo "<h4 class=\"info\"> No product find";
} else {
?>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Descr</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<?php
foreach ( $this->model->prod as $p ) {
echo "<tr><td> $p->id </td>";
echo "<td>" . ucfirst ( $p->name ) . "</td>";
echo "<td>" . ucfirst ( $p->descr ) . "</td>"
// and so on..
}
?>
</tbody>
</table>
<?php
}
}
?>
Problem 1: the "echo include "view/include/....php" seems to echoes also a 1 (a digit) at the end of the page (or the div). Why?
"Problem 2": This is working pretty well, but I'm not sure that is the correct way to do this. Are there any other solutions to query a DB and display results in a div, with only jquery/ajax request? (I don't want a page refresh every time). Maybe something that can speed up responses and/or improves security.
Thank you very much!
For problem 1: include does not require an echo. Its including the content and the echos are inside the included php file. So the echo include is actualy echoing the result of include, which is true or 1 by success.
problem 2: You are right, ajax would be a solution without refreshing the whole page. All you need to do is to make an ajax request to your php script which returns just the html content you want to replace and append this result to your html dom. jQuery has lots of functions for both making ajax calls and appending the result in your html dom.
A good practice is not to return the raw html content and just append it to your site because if something went wrong you might receive error codes from php or warnings or even mysql errors which is bad to show on your website of course. So in order to tell your ajax request that the result is the expected one just send over a status flag with value true. A good way to do this is by sending the result as json encoded string like this:
{
status : true, //shows you your call was successfull
html : "your result html to place on your site"
}
Only if your ajax call returns the correct status (true) everything went well and you can insert it in your page.
I don't know how to add a comment and keep formatting... anyway:
Thanks for your reply.
I didn't understand the last part, right now I have my ajax call:
$('#submit-btn').click(function(event) {
event.preventDefault();
$.get("index.php", {action : "search" , data : mydata }).done(function(data) {
$('#result').html(data);
});
Removing echo the 1 disappeared, but I don't understand the flag you're talking about and what I should encode. The page I want to append? Only the result of query?
After querying DB, I update my model with new values (coming from db) and then I want to show updated table, in this way will I see the modified table?
I hope my question is clear... :)
Thanks a lot!
Having an annoying small problem. Cannot find the solution that works tried just about everything i could find from searching here and google.
Purpose of this is to pass them along into a "room" that has been created previously.
Seems like it doesn't matter what i try i cannot get it to load into another page using onclick with an href. And i know its an easy fix its just something silly i cannot think of.
and sorry if i am not posting my code just right this is my first time asking a question i normally just lurk around for answers.
//..Left out <?php and my connect info but it is in my script
//--CLEANUP MY MESS
$sql = "SHOW TABLES";
$result = mysql_query($sql) or die('err11');
while ($row = mysql_fetch_row($result)) $testing[$row[0]] = true;// Gets a list of tables in the database and turns them into a handy format
if ($testing['prim']){// Checks to see if table prim exists
$sql = "SELECT * FROM prim"; // Pulling all info again after cleaning
$result = mysql_query($sql) or die('err11');
$_e = '';
while ($row = mysql_fetch_assoc($result)){// Cycle through enteries to see what rooms are up
$_e = $_e . "<a href='' onclick='join(" . $row['room'] . ");'>" . $row['teach'] ."</a><br>";
}
}else $_e = "Sorry no rooms are open";
mysql_close($con);
?>
<!DOCTYPE html>
<html>
<head>
<script>
function join(er) {
alert('ffs is this even firing');//this is a debug statement i was using... it was firing
//THE LINE BELOW DOES NOT SEEM TO WORK
document.location = "http://***late edit to get rid of the web address lol sorry***start.php?name=" + document.getElementById("name").value + "&room=" + er;
//THE LINE ABOVE DOES NOT WORK
}
</script>
<title>Portal</title>
</head>
<body>
Name:<input type="text" id='name' name="name"><br><?php echo $_e ?>
</body>
</html>
I tried many different small variations like window.location window.location.href etc etc.. also messed with returns and just driving me nuts
Grateful for any help and you folks have a nice day
window.open will open a new window for you. (see http://www.javascript-coder.com/window-popup/javascript-window-open.phtml )
Alternatively you could set the href and use target="_blank". That way you don't have to use javascript so it's more accessible.
On first hand I am thinking try
<a href='#' onclick=...
but I will investigate further.
My thought is to try the following and see if it works.
hello
Then at least that will tell you if javascript is working properly on your browser etc.
You could try rename it from join to something another name because join is a javascript function (operating on arrays) maybe its having a conflict?
Try the following and tell me if it works. Then try adding some PHP code to the top and see if it still works.
<script>
function test()
{
alert("testing");
document.location = "http://location_edited_out/provingground/start.php?name=abcd&room=1";
}
</script>
hi
One thing you could try is to move the script out of the "head" section and into the body.
For example:
<html>
<head><title>Portal</title>
</head><body>
<script>
function join(er) {
alert('ffs is this even firing');//this is a debug statement i was using... it was firing
//THE LINE BELOW DOES NOT SEEM TO WORK
document.location = "http://***late edit to get rid of the web address lol sorry***start.php?name=" + document.getElementById("name").value + "&room=" + er;
//THE LINE ABOVE DOES NOT WORK
}
</script>
Name:<input type="text" id='name' name="name"><br><?php echo $_e ?>
</body>
</html>
Also you could try putting the script at the end of the body (after the php echo command).
Also you could try splitting it into two statements maybe it doesn't like doing it on the one line:
var url = "http://webaddr.com/start.php?name=" + document.getElementById("name").value + "&room=" + er;
document.location = url;
http://www.webmasterworld.com/javascript/3285118.htm
Try window.location.href or simply, location.href
top.location
?
The following works in internet explorer, having a button instead of an "a href".
<html>
<body>
<script>
function test()
{
alert("testing");
window.location.assign("http://location_edited_out/provingground/start.php?name=abcd&room=1")
}
</script>
<input type='button' value='Load new document' onclick='test()'>
</body></html>
Not sure if this is an option?
So the code is:
while ($row = mysql_fetch_assoc($result)){// Cycle through enteries to see what rooms are up
$_e = $_e . "<input type='button' onclick='join(" . $row['room'] . ");' value='" . $row['teach'] ."'><br>";
}
...
function join(er) {
alert('ffs is this even firing');//this is a debug statement i was using... it was firing
window.location.assign( "http://***late edit to get rid of the web address lol sorry***start.php?name=" + document.getElementById("name").value + "&room=" + er);
}
Let me know if it works.
I have a modal window that uploads files to server. Works great. Upon completion of the upload I am refreshing a div on the parent page. Almost works. What I need in order for it to work is to be able to grab $_GET['edit']. Hopefully my layout of the code will help show my issue.
Modal Window: upload complete
$('#albumFinished').click(function() {
$('#sortableImages').load('../includes/sortImages.php');
});
sortImages.php
$galleryID = $_SESSION['newGalleryId'];
$getGalleryID = $_GET['edit'];
echo "<ul>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sortImageName = $row['OrgImageName'];
$sortPath = "../data/gallery/" . $getGalleryID . "/images/album/" . $sortImageName;
echo "<li class='sortPhotos' id='recordsArray_{$row['id']}' >";
echo '<img src="'. $sortPath .'"/>';
echo "</li>";
}
echo "</ul>";
Everything is functioning properly except I am unable to grab the $_GET variable. How do I go about grabbing this variable? Also if my explanation is not clear, I will try to clarify further.
I'm sorry maybe I'm not understanding but your not actually sending any data to the sort images.php to get with $_get your simply doing a load which is identical to just typing that url in your browser
try using $.post or $.get or $.ajax to send your get info over similar to this
$.get("../includes/sortImages.php", { edit: "what your editing"},
function(data){
return your data here
});
The load function include an extra param called data. This param is the one you have to use to pass parameters to the server via GETmethod. For example:
$('#albumFinished').click(function() {
$('#sortableImages').load('../includes/sortImages.php',
{newGalleryId: 'specify_an_id', edit: 'some_value'});
});
The third line pass the specified parameters and values to the server. Where you will be able to grab them
I have a personal message system in my website done simply with php/sql. Actually I am facing the trouble to display them using jquery. The db has as fields: message_id, message_from, message_to, message_topic, message_subject and message_status. The way I am showing the message_topic is repeating eight times the following:
echo '<table><tr><td>';
retrieve_msg_topic($result);
echo '</td></tr>'; //of course I won't make 8 tables!!!
the function called is:
function retrieve_msg_topic($result)
{
if($row = mysql_fetch_assoc($result))
{
echo $row['usernombre'];
$message_topic = stripslashes($row['message_topic']);
echo '<div id="msg'.$row['message_id'].'">';
echo $message_topic;
echo '</div>';
//this will return: <div id="msgN">message topic (title, commonly subject)</div>
}
} //end function retrieve msg topic
So far I have a list on a table with the last eight messages sent to the user. The following row is reserved for pagination (next/prior page) and, after that, another row showing the message I select from the list presented, like we see in Outlook. Here is my headache. My approach is to call another function (8 times) and have all of them hidden until I click on one of the messages, like this:
echo '<tr><td>';
retrieve_msg_content($result);
retrieve_msg_content($result); //repeat 8 times
echo '</td></tr></table>';
the function this time would be something like this:
function retrieve_msg_content($result)
{
if($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">
$(document).ready(function(){
$("#msg'.$row['message_id'].'").click(function(){
$(".msgs").hide(1000);
$("#'.$row['message_id'].'").show(1000);
});
});
</script>';
echo '<div class="msgs" id="'.$row['message_id'].'" style="display: none">'
.$row['message_subject'].
'</div>';
}
/* This function returns:
// <script type="text/javascript">
// $(document).ready(function(){
// $("#msgN").click(function(){
// $(".msgs").hide(1000);
// $("#N").show(1000);
// });
// });
// </script>
// <div class="msgs" id="N" style="display: none">Message subject (body of message)</div>
*/
} //end function retrieve msg content/subject
I could simply explain that the problem is that it doesn't work and it is because I do if($row = mysql_fetch_assoc($result)) twice, so for the second time it doesn't have any more values!
The other approach I had was to call both the message_topic and message_subject in the same function but I end up with a sort of accordion which is not what I want.
I hope I was clear enough.
The easiest way to fix your troubles would be to copy the results of the MySQL query into an array
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
And then use that to build your tables.
edit: What I meant was more along the lines of this:
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
echo '<table>';
foreach($yourArray as $i) {
retrieve_msg_topic($i);
}
echo '<tr><td>';
foreach($yourArray as $i) {
retrieve_msg_content($i);
}
echo '</tr></td></table>';
And then removing everything to do with the SQL query from those functions, like this:
function retrieve_msg_topic($result) {
echo '<tr></td>'$result['usernombre'];
echo '<div id="msg'.$result['message_id'].'">';
echo stripslashes($result['message_topic']);
echo '</div><td></tr>';
}
Right now you're doing some weird key mojo with ret[0] being the topic and $ret[1] being the message, which isn't a good practise. Also, I don't see the declaration of $i anywhere in that code.
The error suggests that the result is empty or the query is malformed. I can't be sure from the code I've seen.
A few other notes: it seems weird that you're using stripslashes() on data that's directly from the DB. Are you sure you're not escaping stuff twice when inserting content into the DB?
Always use loops instead of writing something out x times (like the 8 times you said in your question). Think of a situation where you have to change something about the function call (the name, the parameters, whatever). With loops you have to edit 1 place. Without, you need to edit 8 different places.
BTW, another solution to this problem would be using AJAX to load content into the last cell. If you're curious, I could show you how.
more edits:
For AJAX, build your message list as usual and leave the target td empty. Then, add a jQuery AJAX call:
$('MSG_LIST_ELEMENT').click(function() {
var msgId = $(this).attr('id').replace('msg','');
$.get(AJAX_URL+'?msgID='+msgId,function(data) {
$('TARGET_TD').html(data);
})
});
Replace the capitalized variables with the ones you need. As for the PHP, just echo out the contents of the message with the ID $_GET['msgID'].
However, make sure you authenticate the user before echoing out any messages, so that someone else can't read someone's messages by switching the id number. Not sure how authentication works on your site, but this can be done by using session variables.
I have a situation where a user fills out 1 of 2 forms on a registration page and is sent to a software download page. If they sign up as a new user, form is processed inserted into a MySQL database and they go to the page no problem.
Here is my issue. If they are a returning user and enter a license key, the processor script checks to see if its valid against the database and if it is it sends them to the software download page. If it is NOT a valid license key (heres what I dont like) the screen goes to the url of the script, page is white, an alert pops down telling them its not a valid license key and they are returned to the registration page to try again. I hate this. I need to figure out a way to either pop the alert on the registration page w/o leaving it or better yet display some kind of message on the page. One drawback is that the script is and always will be on a different server than my forms. Ive tried curl and had success with other situations but can't close the MySQL connection on this one. Is there another way to achieve some semblance of "cross domain AJAX" I would really like it to not go to the script url/white page/alert then return them. I would like it to happen all on one page. Here is that part of my script:
if ($_POST['license_code'] != "")
{
$result = mysql_query("(//mysql stuff here)");
if (($row = mysql_fetch_assoc($result)))
{
header("Location: http://" . $redirect);
}
//here is the part I dont like
else
{
echo "<html>\n";
echo "<body>\n";
echo "<script language=\"Javascript\">\n";
echo "alert (\"The license ID you entered was not correct.\");\n";
echo "window.location=\"http://www.registrationpageURL.php\";\n";
echo "</script>\n";
echo "</html>\n";
echo "</body>\n";
}
mysql_close($link);
}
//I use jquery valiadate.js for CS validation, but realize this is necessary and would like it to behave like the desired result for the above
else
{
if (strpos($_POST['email1'], '#') === false)
{
echo "<html>\n";
echo "<body>\n";
echo "<script language=\"Javascript\">\n";
echo "alert (\"The email address you entered was not correct.\");\n";
echo "window.location=\"http://www.registrationpageURL.php\";\n";
echo "</script>\n";
echo "</html>\n";
echo "</body>\n";
return;
}
thx
Is it possible to remove the alert and when you redirect to registrationpage.php also send a parameter using the redirect url and popup an alert or error message after the redirect ?
Look into using AJAX. jQuery has a great API for this:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/load/
EDITIED - For cross-domain
You could do something like this:
<div id="results"></div>
<script type="text/javascript">
$("#the_form").submit(function() {
$.getJSON("http://remote.domain/script/to/validate.php?data=" + escape($(this).serialize()) + "&callback=?", function(data) {
$("#results").html(data);
});
return false;
});
</script>
This will (once the IDs are pointed at the correct elements) intercept the form submission, pull together the values from the form (through the serialize() function), and shoot it out to the validation script via AJAX. The output of the script is displayed in the #results div.
Hope this helps!