Is this possible? I know the code below looks a whole heap of mess but i want to make it more messy by embedding PHP into it. On each click i'm appending a row onto a table, but i need to include a dynamic dropdown into one of these <td>'s by pulling results from a mysql db. Where it says this: <td><p class="add_edit">Add/Edit</p><input type="text" class="project_ref_input" name="project_ref_input" /><p class="project_ref"></p></td>
Instead of p tags i'm going to have a PHP built dropdown...how can i achieve this?
$('#items').append('<tr class="tableRow">
<td><a class="removeItem" href="#"><img src="/admin/images/delete.png"></img></a></td>
<td class="supp_short_code">' + supp_short_code_db + '</td>
<td class="om_part_no">' + omPartNo + '</td>
<td>' + supPartNo + '</td><td>' + cat + '</td>
<td class="description">' + desc + '</td>
<td>' + manuf + '</td>
<td>' + list + '</td>
<td>' + disc + '</td>
<td><p class="add_edit">Add/Edit</p><input type="text" class="quantity_input" name="quantity_input" /></td>
<td class="price_each_nett price">' + priceEach + '</td>
<td class="cost_of_items"></td>
<td><p class="add_edit">Add/Edit</p><input type="text" class="project_ref_input" name="project_ref_input" /><p class="project_ref"></p></td>
<td class="cost_total_td"></td>
</tr>');
Because Jquery is client side - you cant append PHP like you suggest.
You would have to write a PHP script that is triggered by a callback from Jquery, the PHP script would recieve some parameters, and return the HTML that would be needed to achieve your solution.
Does this help?
step 1: add row
// Your code
//just call another function to get db driven combo.
get_education_combo();
step 2: write following javascript function for retriving the result from php code and sending to html element.
function get_education_combo()
{
var url ="print_education_list";
//alert(url);
var contents = AjaxRequest(url);
//alert(contents);
//return contents;
//send the result to html
document.getElementById("elementID").innerHTML=contents;
}
function AjaxRequest(url)
{
//alert(url);
if(xmlhttp != null){
if(xmlhttp.abort)
xmlhttp.abort();
xmlhttp = null;
};
if(window.XMLHttpRequest) // good browsers
xmlhttp=new XMLHttpRequest();
else if(window.ActiveXObject) // IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if(xmlhttp == null)
return null;
xmlhttp.open("GET",url,false);
xmlhttp.send(null);
// alert(xmlhttp.status);
if(xmlhttp.status >= 200 && xmlhttp.status < 300)// 2xx is good enough
return xmlhttp.responseText;
else
return null;
}
step 3: php code
print_education_list()
{
$education="your query";
echo '<select name="edu_name" id="edu_name" style="width:70px;">';
foreach($education as $edu)
{
echo '<option>';
echo $edu->sEducationName;
echo '</option>';
}
echo '</select>';
}
That's It. BEST OF LUCK. I have prepared this combination during development of DeskTop application by php.
You would generate the dropdown on the server, then fetch the dropdown using the jQuery $.ajax method. Alternatively you could return a JSON array of option/values and build your dropdown using something like $.each to iterate the array.
If you are thinking about having the PHP in the javascript then sending that back to the server to be executed then DON'T. That's a WTF of the highest order. You didn't mean that right? (You might want to change the title of your question - becasue that's what it looks like).
edit: For all you guys saying client side PHP is impossible. Check this out!
http://thedailywtf.com/Articles/Client-side_PHP.aspx
PHP is server-side only, so you can't embed it into the JS that you send to the client's browser and expect it to run. In order to achieve your result, you'll either need to use PHP to render the list in the initial page, or use an AJAX call to pull the list from a service URI.
If you are generating this code dynamically on the server, i.e. you want to add the mysql results to the HTML markup before sending it to the client, you would do something like this:
<td><?php $VARIABLE_TO_ADD ?></td>
This is assuming you know how to pull the data out of the DB and create a variable with that data. PHP looks for the <?php ?> tags within an HTML document and parses whatever is between them.
Related
I have broken down my problem to provide a concise example with no overhead.
Yet enough to give you an idea.
I have a simple index.php
<?php
include 'myClass.php';
?>
<html>
<head></head>
<body>
<div> <?php myClass->printTable(); ?> </div>
</body>
</html>
The function returns an entire table filled with data that is being prepared in the backend.
<?php
function printTable()
{
// printing static table header
echo ' <table class="table" style="zoom: 0.75;">
<thead class="thead-dark">
<tr>
<th scope="col">Date</th> // current date
<th scope="col">Order Number</th> // an int
<th scope="col">Current Value</th> // an int
</tr>
</thead>
<tbody>
';
$result = mysqli_query($this->link, "SELECT * FROM `someData`");
while ($row = mysqli_fetch_assoc($result))
{
$orderNumber = $row['orderNumber'];
$currentValue = $row['currentValue'];
$date = $this->getDate($orderNumber); // member function that returns a timestamp from the database
//printing actual table
echo ' <tr>
<td>'. $date .'</td>
<td>'. $orderNumber .'</td>
<td>'. $currentValue .'</td>
</tr>
';
}
echo ' </tbody>
</table>
';
}
?>
The data I'm querying from my database is constantly changing. I want a "live" view on the frontend. I know this is done by using Ajax. But I don't understand how to do it. I looked up different resources, although none of them were actually specific enough in this approach.
On a high level: You need a PHP file ("endpoint", e.g. 'localhost/data.php') returning only the HTML code from printTable. You then use JavaScript (e.g. jQuery - $.ajax, you can lookup how it works in detail) to fetch the contents of this page each n seconds and insert into your page.
I was looking for broad or unspecific way to get some data from the backend and display it within a div on my page.
The solution was to create a separate PHP (fetch.php) file that echoes only the data I need to display within my div
from my page which contains my div I'd do the following:
<div id="result"></div>
<script>
function load_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('#result').html(data);
}
});
}
load_data()
</script>
Inside fetch.php I can do whatever I want, including querying my database and store the values in a variable which will be echoed at the end. This response (echo) from fetch.php will then be displayed inside my div.
Similarly, I could also specify a .txt inside the ajax function (url:"sometext.txt")
The contents of the .txt could also be displayed inside my div this way. My lack of understanding of how this works made it really difficult to understand.
Additionally, I have added a function to refresh the contents (or response) every second.
If I would echo time() from fetch.php it would automatically increment without page reload inside my div
setInterval(function(){
load_data()
}, 1000);
I have been going to stackoverflow for hints and tips in my programming journey but I have yet to register. . .till now.
My question is, is it possible to update/edit mysql data which I've inserted into an html/css table without having to go to another page?
for example:
when looking at the table in my browser, I wanted to edit my email information. I could just simply press the edit button then the email field becomes a text field right on the same page then I could just update it and hit save?
thanks!
EDIT(added my code):
$(button#edit).on('click', function() {
// get email inline to this edit button
var email = $(this).parent().siblings('td.email').html();
// change button from edit to save
$(this).attr('id', 'save-email').html('Save');
// change email display to input field
$(this).parent().siblings('td.email').html('<input type="text" id="user-email" value="'+email+'" />');
});
and this is the table I used which is formatted with php which also grabs data from my database:
echo ' <tr>';
echo ' <td>' . $row['name']. '</td>';
echo ' <td>' . $row['age']. '</td>';
echo ' <td>' . $row['sex']. '</td>';
echo ' <td>' . $row['email']. '</td>';
echo ' <td>' . $row['contact_no']. '</td>';
echo ' <td>' . $row['school_name']. '</td>';
echo ' <td>
<button id = "edit">EDIT</button>';
nothing happens,your help is greatly appreciated!
Yes, it is possible. Here are a few hints:
Use jQuery to listen to a click-event on the button and insert the text-field.
On Submit, use jQuery to send an ajax-request to a different php-file (like save.php).
Inside this file, you can do any mysql-queries you would normally do.
Again through jQuery, display the result of the queries to the user.
Yes. It's possible. Make a hidden div tag in your html code.
By means of ajax when you press button that div tag will be filled up by textbox / text.
Go through some tutorials related to ajax.
Sharing you an idea on how it works
JS script:
$('button#update').click(function(){
$.ajax({
url : 'yourpagehere',
data : {
id : '1' // send sample data to url
},
type: json,
sucess: function(response){
//Your script
});
});
});
PHP:
function yourpagehere(){
$id = $_POST['id']
$result = updateUserInfo($id); //Your script updating info in your database
json_encode($result); //Your response
}
Then you use firebug and check the console log on what you're ajax returned.
Yes, It is possible using AJAX.
AJAX is very powerful jQuery tool which is used to make asynchronous javascript calls which means you can submit data to another page without page loading.
As well as you can fetch data and fill dynamically in your page using AJAX without reload/load page.
You can find many tutorial and examples of AJAX.
I'm an absolute beginner in the HTML/Php/JavaScript world. I'm trying to make this page:
dropdown list with titles of documents
when something is selected, populate input fields below with data from PostgreSQL to allow for update
submit button to update database with corrected values from user.
1 and 3 are ok (already tried this with an insert-only form).
My code looks like this (simplified, without dbconn):
echo "<select name='listedoc' size=1>";
while ($ligne = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo '<option value="'.$ligne['id_doc'].'">'.$ligne['doc_titre']. '</option>';
}
echo "</select>";
The input fields (simplified, there are 4 fields actually):
<p><form name="saisiedoc" method="post" action="docupdins.php"></p>
<table border=0>
<tr><td>Texte</td>
<?php
echo '<td> <textarea name="content" cols="100" rows="30"></textarea> </td>';
?>
</tr><tr>
<td colspan=2>
<input type=submit value="Valider la saisie" name="maj"> </td>
</tr>
</table>
</form>'
Then JQuery script :
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
});
});
</script>
The php to select fields (docsel.php):
<?php
include('../scripts/pgconnect.php');
$iddoc = $_POST['id'];
$sql="SELECT * FROM document where id_doc = $iddoc";
$result = pg_query($db, $sql);
if (!$result) {
echo "ERREUR<br>\n";
exit;}
$row = pg_fetch_row($result);
$doctyp = $row[1];
$doctitre = $row[2];
$docauteur = $row[3];
$doccontent =$row[4];
pg_free_result($result);
pg_close($db);
}
?>
Whatever I do, I can't get back values. I tried value="'.$doctitre'" in the input,
echo $doctitre, to no avail . Is my code logic correct ? Thank you for your help
you are close. the script docsel.php needs to return the data to the html-page.
you have it already setup to receive the data in the callback function
$.post("docsel.php", {id:id},function(data) {
$('textarea[name="content"]').text(data.content);
});
in order to have something in data.content, the php script sends json data:
$result = [];
$result['content'] = $doccontent;
echo json_encode($result);
maybe you need to read the docs on $.post and json_encode... good luck.
There are a couple of things you need to change here.
Firstly, and most importantly your docsel.php script has a gaping security hole. You should never ever ever place unsanitised input e.g. directly from a user, straight into a SQL query because it allows for SQL injection. Essentially, SQL injection allows a malicious user to end the programmers query and submit their own. To get round this you must sanitise any user input - so in this case pass the user input through the function pg_escape_literal() before putting it into your query.
Secondly, your docsel.php script must put out some kind of output for the AJAX request. You can do this by using echo and I would recommend you encode it into JSON. Code example:
$return_vals = array("doctype" => $doctyp, "doctitle" => $doctitre, "docauthor" => $docauteur, "doccontent" => $doccontent);
echo json_encode(array("document" => $return_vals));
Lastly, in your jQuery script, you aren't actually doing anything with the data that is returned from your AJAX post request. Inside the callback function, you need to then add the returned fields to your select dropdown. Code example:
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
//FILL THE DROPDOWN HERE
$(data).each(function(elem) {
$("#dropdown-id").append("<option value='" + elem.doctitle + "'>" + elem.doctitle + "</option>");
});
}, "json");
});
</script>
A mute and pedantic point, but when making requests for content then you should be using GET instead of POST.
I am attempting to retrieve data from a table on another website using YQL and display the data in a form on my website using jQuery. I have been successful retrieving the data and displaying it on my website as-is, however, I am not sure where to start to put the data into my form inputs.
The data being retrieved looks like this:
<table>
<tbody>
<tr class="">
<td class="nobr">
C Borup
</td>
<td class="num IP">
<p>0.2</p>
</td>
<td class="num H:pitching">
<p>2</p>
</td>
[...]
</tr>
</tbody>
</table>
I guess I can do 1 of 2 things at this point.
1) Try to convert the p tags in this table to inputs, but just as important I would need to apply the class from the td to the input as well.
2)retrieve the value from the p tag in the table and place it in the existing form based on the td class (is this possible?).
My jQuery to retrieve and display the data look like this:
jQuery("#bbnuke_retrieve_gamechanger_results_btn_id").bind('click', function() {
var gameID = jQuery("#bbnuke_plugin_gamechanger_import").val();
var pitchLink = 'http://www.gamechanger.io/game-' + gameID + '/boxscore/pitching/standard';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select tbody FROM html where url ="' + pitchLink + '" and xpath="//table[#id=' + "'tbl_home_pitching'" + ']"') + '&format=xml&callback=?';
jQuery.getJSON(yql, cbFunc);
function cbFunc(data) {
if (data.results[0]) {
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
jQuery("#gamesitedump").html(data);
}
else {
jQuery("#gamesitedump").html("Error");
throw new Error('Nothing returned from getJSON.');
}
}
});
Any help is much appreciated!
You could "convert" the <p> into <input> this way :
$("td > p").each(function() {
// creates a new <input> element
$newInput = $("<input type='text'/>");
// find the parent of the current <p>, and applies its class to the new <input>
$newInput.addClass($(this).parent().attr("class"));
// get the value of the current <p>, and set the value of the new <input> to this
$newInput.val($(this).text());
// replace the current <p> element with its <input> equivalent
$(this).replaceWith($newInput);
});
You can find a jsFiddle example here .
How can javascript pass data, for example from an HTML table, without using AJAX?
I am lacking the understanding of how to actually pull data, format (into json likely), and pass it.
I am trying to pass data to a php function that sends a file to the user to download. (something ajax can't handle as I understand it)
EDIT - please give an example of posting of some rather complex data.
EDIT2 - an exmample...
I populate a table via an ajax response Object. What would be a good way to get this data I am formatting into a form that I can send to a php file via a form?
function getSalesByDeviceComplete(responseObj)
{
var cashTotal = parseInt(responseObj.data[0].cash_total).toFixed(2);
var creditTotal = parseInt(responseObj.data[0].credit_total).toFixed(2);
var grandTotal = (parseInt(responseObj.data[0].cash_total) + parseInt(responseObj.data[0].credit_total)).toFixed(2);
htmlStr += '<ul>';
htmlStr += ' <li>';
htmlStr += ' <table class="ui-widget ui-widget-content contentTable">';
htmlStr += ' <thead>';
htmlStr += ' <tr class="ui-helper-reset ui-widget-header">';
htmlStr += ' <th class="contentTableKey">Payment Device</th>';
htmlStr += ' <th class="contentTableValue">Sales</th>';
htmlStr += ' </tr>';
htmlStr += ' </thead>';
htmlStr += ' <tbody>';
htmlStr += ' <tr>';
htmlStr += ' <td class="contentTableKey">Credit Card</td>';
htmlStr += ' <td class="contentTableValue">$'+creditTotal+'</td>';
htmlStr += ' </tr>';
htmlStr += ' <tr>';
htmlStr += ' <td class="contentTableKey">Cash</td>';
htmlStr += ' <td class="contentTableValue">$'+cashTotal+'</td>';
htmlStr += ' </tr>';
htmlStr += ' </tbody>';
htmlStr += ' <tfoot>';
htmlStr += ' <tr>';
htmlStr += ' <td></td>';
htmlStr += ' <td id="salesTotal" class="contentTableValue">$'+grandTotal+'</td>';
htmlStr += ' </tr>';
htmlStr += ' </tfoot>';
htmlStr += ' </table>';
htmlStr += ' </li>';
htmlStr += '</ul>';
$("#contentData").html(htmlStr);
}
The response object looks something like...
<response_GetSalesByDevice>
<data>
<cash_total>0.00</cash_total>
<credit_total>0.00</credit_total>
</data>
<success>1</success>
</response_GetSalesByDevice>
Alas, there are several response objects that are much more complex than this.
By posting form data to a PHP script via the browser, rather than using an asynchronous HTTP request.
The way it "used" to be done (which is of course still very current):
http://www.w3schools.com/html/html_forms.asp
If by "Without AJAX" you mean without using XMLHttpRequest, then the most common way is to fill a hidden field in a form.
Javascript can change a hidden field, then when the user submits the form as usual, the hidden value is passed through as well.
This can be used for things like gathering stats on screen size etc, which are non-critical and can be passed through when Javascript is enabled, or not when it isn't.
You seem to have some crossed understanding of what AJAX and JSON are/do or most likely I do not understand what you mean from your question.
If you do not want to use ajax you will have to use the normal submit just like the two people above me suggested.
However, if you are sending a relatively small amount of data you might be able to send a GET request to your PHP script with ajax, which will then respond with a file. Something like:
http://yourserver.com/test.php?getVariable=29472938472
Test.php script looks at the get variable and returns the associated file.
Entirely possible with AJAX.
Please tell me if I've gone down the wrong path.
You could post via a form in the usual way.
The form, however, is targeted at a hidden iframe. This way you stay on the current page and the file that the server returns is handled in the usual browser way.
Instead of calling the data directly, you should call a php file that contains:
/myphpfilethatgetsstuff.php
http://mydatadomain.com/?q=getmesomexmlplease";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
echo "<pre>";
print_r($json_output);
echo "</pre>";
?>
Then iterate over the data creating both the file and the html output.
In the main file use this javascript:
$('div#results').load("http://mydomain.com/myphpfilethatgetsstuff.php");
with this div somewhere:
<div id="results"></div>
and this link:
Your File
One alternative to XMLHttpRequest objects is making asynchronous calls via an iFrame imbedded in the page. This is a documented "AJAX" design pattern when xmlhttprequests cannot be used.
There are some components for jquery (ie, AJAX Upload) that utilize this method.
Documentation and sample here:
http://ajaxpatterns.org/IFrame_Call