I need the id in url to make a mysql_query. The problem is that I need to make this from an Ajax call and $_GET['id'] apparently is not working.
Is there an easy way to free myself from this?
Thank you :)
Here is my ajax call:
echo "<div id='loading_utilizadores' class='loading'><img src='".$CONF['HOME']."/images/structure/ajax-loader.gif'/></div>";
echo "<div id='utilizadores'></div>";
echo "<script type='text/javascript'>";
echo "CarregaAjax(\"#utilizadores\",\"#loading_utilizadores\",\"".$CONF['HOME']."/superadmin/box_utilizadores_ajax.php\", \"GET\")";
echo "</script>";
The ajax function:
function CarregaAjax(id,loading,page,method){
if(method=="GET"){
$(document).ready(function(){
//$(loading).ajaxStart(function(){
$(loading).show();
$(id).hide();
//});
$(id).load(page);
$(loading).ajaxStop(function(){
$(loading).hide();
$(id).show();
});
});
}
else{
$(document).ready(function(){
//$(method).submit(function() {
$(loading).show();
$(id).load(page,$(method).serializeArray());
$(loading).hide();
return false;
//});
});
}
And the peace of html ajax call. In this page I try to make the $_GET['id'], but with no success.
if (isset($_GET['id']))
{
$officeID = intval($_GET['id']);
}
else
{
$officeID = 0;
}
if(!isset($crm_users))$crm_users = new crm_utilizadores;
//$officeID = 12;
$resultGetUsers = $crm_users->getUsersByOfficeId($officeID);
$html = "<table class='table1' width='100%' cellpadding='5' cellspacing='1' border='0'>";
if(!empty($resultGetUsers)){
$html .= "<tr>";
$html .= "<td class='table_title1'>Utilizador</td>";
$html .= "<td class='table_title1'>Telefone</td>";
$html .= "<td class='table_title1'>Telemóvel</td>";
$html .= "<td class='table_title1'>E-mail</td>";
$html .= "<td class='table_title1'>Situação</td>";
$html .= "</tr>";
}else{
$html .= "<tr><td class='empty1'>não foram encontrados utilizadores registados neste cliente</td></tr>";
}
//finalizar a tabela
$html .= "</table>";
I guess I'm mising the point, right? :p
This code attempts to read the id value from the URL:
$_GET['id']
But this is the URL you're requesting:
/superadmin/box_utilizadores_ajax.php
As you can see, there is no id value (or any other value). That would look something like this instead:
/superadmin/box_utilizadores_ajax.php?id=123
The value has to be on the URL in order for $_GET to read it.
Now, the page you're currently viewing may have that value in the URL you previously requested. But the server-side code isn't looking at your screen or interacting with your web browser. All it knows is the request that you send it. And that request doesn't contain that value.
You can, when loading the page, put that value on the request. In index.php read the $_GET['id'] value and output it to the JavaScript code which is making that AJAX request. Technically it could be something as simple as this, just to demonstrate:
"/superadmin/box_utilizadores_ajax.php?id=" . $_GET['id'] . "\", \"GET\")"
However, be aware of the dangers of outputting raw user input to the page. This results in things like XSS vulnerabilities. Be mindful of what you're outputting to the page, but ultimately you need to output that value somewhere in order for that JavaScript code to send it to the next (AJAX) request. (Or, alternatively, you could store the file server-side in session state or something similar. Thereby removing the URL from the equation entirely. There are pros and cons either way.)
In short, you need to include the value on the URL being requested if the page at that URL is going to read the value. The code can only read values which are there.
Related
I am trying to make an incredibly simple ajax call, but it wont work.
Here is the php side called by ajax( This returns the correct response )
<?php
$returnValue = '';
$allUploads = array_slice(scandir('./uploads'), 2);
$returnValue .= '<table>';
foreach ($allUploads as $upload) {
$returnValue .= '<tr><a href ="/uploads/' . $upload . '>' . $upload . '</a></tr>';
}
$returnValue .= '</table>';
echo($returnValue);
?>
And here is the javascript thats letting me down
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange =
function ()
{
if (this.readyState == 4 && this.status == 200)
{
alert(this.responseText);
document.getElementById("filedisplaytable").innerHTML = this.responseText;
}
};
xhttp.open("GET", "listuploads.php", true);
xhttp.send();
</script>
Worst thing about this is, that the alert statement is outputting exactly what I want to write:
<table>
<tr>
<a href ="/uploads/DSC001.jpg>DSC001.jpg</a></tr><tr><a href ="/uploads/DSC002.jpg>DSC002.jpg</a>
</tr>
<tr>
<a href ="/uploads/DSC003.jpg>DSC003.jpg</a>
</tr>
</table>
But when I write that into the div it writes the a hrefs 1st followed by an empty table...
Any help is greatly appreciated.... struggling to do such simple things really gets me down
Your HTML is invalid.
An <a> element cannot be a child element of a <tr>.
Only <td> and <th> are allowed there.
The problem you are experiencing is likely the result of the browser attempting to recover from your error by moving the <a> elements to somewhere they are allowed (i.e. outside the table).
Write valid HTML instead. It looks like you don't have a tabular data structure so probably shouldn't be using a table in the first place. A list might be a better bet.
Like Quentin said, your HTML is invalid. <a> tags are allowed in <td> though.
Replace your PHP line of code with this one:
$returnValue .= '<tr><td><a href ="/uploads/' . $upload . '>' . $upload . '</a></td></tr>';
I am tryaing to to make this echo work, but i cant get the grip of it
echo '<script>
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;
return txt.replace(linkRegex, "<img class="sml" src="$1" /><br />");
}
var newHTML = replaceWithImgLinks($(".ms").html());
$(".ms").html(newHTML);';
echo "</script>";
What am i doing wrong? i think i got something wrong with my " ' .
There was a couple of issues. I started by just running it in JavaScript until I got it to work, then moved it into PHP (for the sake of sanity).
<?php
print '
<script>
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9#:%_\+.~#?&\/\/=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&\/\/=]*)?(?:jpg|jpeg|gif|png))/gi;
return txt.replace(linkRegex, "<img class=\"sml\" src=\"$1\" /><br />");
}
var newHTML = replaceWithImgLinks($(".ms").html());
$(".ms").html(newHTML);
</script>';
?>
Shouldn't the regex be something like:
(^|\b)((https?:)?\/\/[^\s]*?\.(jpe?g|png|gif))(\b|$)
Debuggex Demo
You shouldn't be echo'ing scripts, especially scripts in script tags. I would seriously look into just using your back end to fetch, then use an asynchronous technology that fetches data parsed JSON. That way you can call your scripts normally.
I have a wordpress installation where I am currently trying to create a formular where after sending the formular I process the data and save it into a mysql DB.
To achieve this I have created a new .php file which I included in the "function.php" of my theme because i want to add the whole formular/process with a shortcode.
The .php file currently contains this (Simplified):
function FNC_Add_New_Record ()
{
$options = "<option value='unselected'>- Select one -</option>"
. "<option value='option1'>Option 1</option>"
. "<option value='option2'>Option 2</option>";
echo "<br>";
echo "<form id='form1' method='post'>";
echo "<div style='text-align: center;'>";
echo "<font size=5>Selection 1</font><br>";
echo "<input type='text' name='textfield1' placeholder='Insert caption here'><br>";
echo "<select id='selection1'>" . $options . "</select>";
echo "<select id='selection2'><option value='unselected'>- No option1 selected -</option></select>";
echo "<br><br>";
echo "</div>";
echo "</form>";
echo "<br>";
}
add_shortcode('FNC_Add_New_Record','FNC_Add_New_Record');
Because the selection 2 depends on what is selected with the selection 1 I added jquery to the end of the .php file:
?><!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function () {
$("#selection1").change(function () {
var val = $(this).val();
if (val == "option1") {
$("#selection2").html("<option value='none'>None</option><option value='option2'>Option 2</option>");
} else if (val == "option2") {
$("#selection2").html("<option value='none'>None</option><option value='option2'>Option 2</option>");
} else if (val == "unselected") {
$("#selection2").html("<option value='unselected'>- No option1 selected -</option>");
}
});
});
</script>
So, there is probably a lot I have done wrong but this was the only way I was able to get it working. Yes I have searched here and on a lot other sides for proper solutions which tell me to add it to the function.php of the theme and do it with "enqueue". I have tried all of the possible suggest functions and code snippets but nothing worked.
The issue what I have with this solution is that it renders the wp-admin of my wordpress installation useless because it just shows the code which I have added to the .php file as html.
what I get on my site accessing wp-admin:
Also i'd like to note that using the tag "<!DOCTYPE html>" is a solution to another problem I have when adding jquery but i have no idea if it's the correct solution. If I remove this tag the main navigation of my website, instead of being like 15px in height suddenly has a height of almost a whole full HD screen.
Wordpress function.php also includes all JS files, make use of wp_enqueue_scripts to queue up your scripts.
function my_scripts_loader() {
wp_enqueue_script('myjquerylib-js', get_template_directory_uri() . '/assets/js/myjquerylib.js');
}
add_action('wp_enqueue_scripts', 'my_scripts_loader');
I have an html file that contains a table with table rows
<table style="width:auto">
<tr>
<td contenteditable="true"><select id="so"></select></td>
</tr>
</table>
I have a PHP that selects from mySQL DB and returns username
if ($results->num_rows > 0) {
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
echo "<option>
$name
</option>";
}
} else {
echo "0 results";
}
I am trying to incorporate the result of the php into my index.html file within the table so that the option shows up in the table
How can I get the data from PHP into an already built html table row?
Any help would be appreciated.
Two way to get the job done:-
1)Use a class, that is you should, and using its object you can retrieve the data and use it on the webpage .
ex:- see this class, it needs a lot of improvements and changes, but still can give you some idea . I am also trying to learn PDO well, not a PRO, but can be helpful to you.Comments on this class will help you get the idea .
2)Using AJAX, You can request for this data on loading the document or you can request it via get, post, request.. on any event.If you know ajax, you can use that class and ajax, or if you do not have an idea about AJAX, you can get a lot of resources to learn ajax. after this if you need my assistant, I will try to help you.
for this work you should use ajax to load data in html file ...
you can do it with javascript :
create a function for load your php file :
function loadAjax(address,elementId) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(elementId).innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", address, true);
xhttp.send();
}
after create it you can use it when you want (for example after load of page). you should pass address of your php file and id of html element that you want the answer load into it .
for more learn :
http://www.w3schools.com/ajax/
There are couple of methods that can be used here. If the HTML and PHP are in the same file you could do this:
<?php
if ($results->num_rows > 0) {
$options = ''; // declare the variable to hold the options
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
$options .= "<option>$name</option>"; // add the options to the variable
}
} else {
$options = "0 results";
}
?>
And then add the $options to the HTML:
<table style="width:auto">
<tr>
<td contenteditable="true">
<select id="so">
<?php echo $options; ?>
</select>
</td>
</tr>
</table>
Another option, though not as neat, is to embed the PHP in the HTML:
<table style="width:auto">
<tr>
<td contenteditable="true">
<select id="so">
<?php
if ($results->num_rows > 0) {
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
echo "<option>
$name
</option>";
}
} else {
echo "0 results";
}
?>
</select>
</td>
</tr>
</table>
Yet another option would be to use AJAX to call the PHP from the HTML page and return the results to the right location. For instance, if you wanted to use jQuery you could follow a tutorial to learn the basics and then apply that to your code.
I checked php.net and read a few examples of how urlencode( ) works but somehow I just can't get it right. Can someone give me a hand?
it'll be a lot to example so hopefully my brief example would make sense.
I have a page called 2.php and it was called to show some contents of a .txt file choosen in 1.php.
I am told to make a link for 3.php and the link should look something like /3?filename=a.txt
with filename as GET parameter name and Ensure GET parameter value is urlencoded using the urlencode( ) function.
but I'm confused how and where I should put urlencode() to make it work.
I'll paste my 2.php code here...I simplified the codes a bit...
<?php
$fileContents = file("./aaa/" . $_GET["course"] . ".txt");
echo "<table border=\"1\">";
foreach($fileContents as $row)
{
echo "<tr>";
$contents = preg_split("/,/", $row);
foreach($contents as $eachline)
{
echo "<td>";
if(!(preg_match("/#/", $eachline)))
{
echo trim(ucfirst($eachline));
}
else
{
echo trim(strtolower($eachline));
}
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
echo "<a href='./1.php'>Choose another txt file</a><br/>";
echo "or<br/>";
echo "<a href='.3.php?'>Work with this txt file</a>";
?>
BUT…the 3.php option must have a query string appended to it: the name of the text file that was selected in 1, so instead of ./3.php, the url should be something such as ./3?filename=asdf.txt
Use “filename” as the GET parameter name. Ensure the GET parameter value is urlencoded using the urlencode( ) function.
but I'm just not sure how to get it to work....
You can wrap the part that should be url encoded in the function within the string:
$url = 'http://www.google.com?q=' . urlencode($search);
OR in html
http://www.google.com?q=<?php echo urlencode($search); ?>
Where . is the concatenation of 2 outputs.