MySQL database update through AJAX and PHP - php

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.

Related

Update form with ajax

I have list of table which displays users information. There will be an amend link at the top. I need to update the form through Ajax rather than moving on to another page to update it.
This is my code.
<?php while ($row = mysql_fetch_assoc($displayer)){
echo("<tr><td>First Name</td><td>" . $row['first_name'] . "</td> </tr>");
echo("<tr><td>Last Name</td><td>" . $row['last_name'] . "</td> </tr>");
echo("<tr><td>Email</td><td>" . $row['email'] . "</td> </tr>");
echo("<tr><td>Country</td><td>" . $row['country'] . "</td> </tr>");
echo "<a class='page' href='amend.php?id=" .urlencode($row['users_id']) . "&firstname=" .urlencode($row['first_name']) . "&lastname=".urlencode($row['last_name']) ."'>Amend Record</a></td></tr>";
?>
Could any one tell me how to update the form using Ajax on the same page itself.
much details go into these that would require a very lengthy answer...nonetheless I am going to stress some important starting points.
First you need a JS file with a handler about the link.
When the link is clicked a ajax request must be made...there are various way to do that but I personally use jquery's $.ajax....inside the request you must gather the variables that reflect the values of the form inputs....then you send these values to a PHP script that makes validation and if this is successful update the corresponding values in the database.Inside the request you must also specify the URL that the this script resides.
This ajax request though is comprised of 2 important callbacks...error and success...in them you must write code that will deal with the situation if the request succeeds or not....for example you update he values in form when you are certain that this has indeed happen in the database and you can a make check for that in the PHP script...whatever values the PHP script echoes back must be done with json_encode...and you can access these values with the data argument of the success callback.AS I said there is an error callback also..this is triggered by various causes...it the URL is wrong or JSON is not returned from the server.
These above are just starting points...I am laying out a general approach.
/* AJAX using jQuery */
// attach event to your <a> upon click
$(document).on('click','a.page', function(e) {
e.preventDefault()
var sURL = $(this).attr("href"); // url to call for amend
update( sURL ) // call the function update
});
// update() function that is called after clicking anchor tag
function update( _url )
{
$.ajax({
method: 'POST',
url: _url,
success: function() {
alert("Amend Success)";
},
error: function( c ) {
alert("Internal server error. Check your browser console");
console.log( c.responseText )
}
})
}
NOTE: Put this before </body> tag

input data and run a php script from jquery event

I am having a problem getting data from jquery into a php script. I am trying to load a php script (i.e. send an email) with a variable (email address) from jquery event without leaving the original page and going to a confirmation page. Please help!
Here is my jquery code:
<script>
$("#test").click(function() {
var id = 1;
$("#target").load("javascript_test2.php", id);
});
</script>
<div id="target">hmmm did it work?</div>
</body>
This is the php I would like to receive and process the code:
<div id="S1">
<?php
$id = htmlspecialchars($_POST['id']);
for ($i=1; $i<=2; $i++) {
echo $id . 'Hello world ' . $i . '<br>';
}
require_once('lawyeralertemail.php');
?>
</div>
Thanks!
You can use jQuery ajax to post data into your PHP.
Here is a link:
http://api.jquery.com/jquery.post/
This will allow you to post data without reloading the page and give your user a better experience.
You can then use $_POST to capture the data inside your PHP.

jQuery prevent all forms from submitting at one time

I have a set of HTML form links which I am submitting upon click which have the id "ajaxForm"
for ($year = 2008; $year <= intval(date('Y')); $year++) {
if ($year == $currentYear)
continue;
echo '<div style="float:right;padding-right:20px;"><form name="year' . $year . 'Form1" id= "ajaxForm" action="/managementDashboard#visibleTab-5" method="post"><input name="getRecordsFor" type="hidden" value="' . $year . '"><a id="buttonRed" href="javascript:document.year' . $year . 'Form1.submit();">' . $year . '</a></form></div>' . chr(10);
}
However instead of default submission I use jQuery to post the data with this:
jQuery("form#ajaxForm").click(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* Send the data using post and put the results in a div */
jQuery.post( '/ajaxFunctions?mgmtDbrdPge=5', jQuery("#ajaxForm").serialize(),
function( data ) {
jQuery( "#visibleTab-5" ).empty().append( data );
}
);
});
The problem is that it is submitting ALL the forms instead of the individual one I click. Is there a way I can prevent this without having to write jQuery link for each individual form?
UPDATE - I accepted one of the answers because his method is legitimate but I realized what my issue was. Instead of jQuery("#ajaxForm").serialize(), I should have had it written as jQuery(this).serialize() to only call upon the data that was submitted with the click instead of ALL the forms with that id.
Looks like you are having more than one form with the same id of ajaxForm .
Make sure it is unique
If you know the id's of the Ajax forms in your page.. then you can do this
jQuery("form#ajaxForm ,form#myForm , form#myFormThird ").click(function(event) {
This will make sure the multiple elements are attached to the same event handler..
UPDATED CODE
If you do not know the id's then you can iterate using a for loop and attach the events..
$('form').each(function() {
$(this).click(function(event) {
// Your Function
}
});
Also make sure you use .on() to attach your events .. Instead of just the click so that the events are delegated..
jQuery("form#ajaxForm").on('click',function(event) {

Add to mysql with checkbox and AJAX

I have some data which will be displayed like this;
foreach ($holidays as $holiday)
{
$resultTable .= "<p>{$holiday->title}" . "<br/>" .
"{$holiday->pubDate}" . "<br>" .
"{$holiday->description}" . "<input type=\"checkbox\" name=\"saveCB\" value=\"3\"/>" . "<br /></p>";
}
Is there an easy way by which when the checkbox is clicked and the data would be added to a mysql table using AJAX?
Regards Darren
Yes you need javascript to do this. It can be done pretty easily though, if you are satisfied with the form submitting, and the page refreshing each time a select box is changed (i.e. check/unchecked). If you can't accept this, you'll have to use ajax. That would be your optimal solution, and easy as ajax is, it is a nice to have in your toolbox for future projects.
That said, you can achieve this by giving your form an id attribute, and paste this javascript just beneath your form (and edit the form id var):
<script type="text/javascript">
var formId = "YOUR FORM ID HERE";
function submitForm(){document.getElementById(formId).submit()}
</script>
Then add the following attribute to each checkbox: onchange="submitForm()".
Again, it is highly recommended to use ajax for this sort of stuff, and if you look into jQuery ajax, you'll be impressed how easy this can be done.
EDIT: What you can do to actually implement this in your existing code (replace it):
<form action="php-file-to-process-form.php" id="your-form-id" method="post">
<?php if(count($holidays)>0): foreach($holidays as $holiday): ?>
<p>
<?php echo $holiday->title; ?>
<br>
<?php echo $holiday->description; ?>
<input type="checkbox" name="saveCB[<?php echo $holiday->id; ?>]" value="<?php echo $holiday->id; ?>">
</p>
<?php endforeach; endif; ?>
</form>
<script type="text/javascript">
var formId = "your-form-id";
function submitForm(){document.getElementById(formId).submit()}
</script>
Please note i rewrote parts of your code. But in this case, assuming your $holiday objects has an "id" property, php-file-to-process-form.php should receive a fairly comprehensible post request.
PHP doesn't have onClick events, you would have to use JavaScript for something like that.. Or make it so you post your values with PHP (using a form), then it would be possible.
To avoid page refreshing with a form submit you'll want to use AJAX. You didn't tag your question as using jquery, but I highly recommend it. Here is a jQuery example of what you want:
$('input[type=checkbox]').click(function() {
if ($(this).is(':checked')) {
var name = $(this).attr('name');
var value = $(this).val();
$.post('/path/to/your/php/code', {name: value}, function(data){
//Handle the result of your POST here with data containing whatever you echo back from PHP.
});
}
});
Note that this puts the same click handler on all your checkboxes which might be the wrong assumption. If you have other checkboxes on your form that you don't want to use with this logic you'd just need to change the jQuery selector from 'input[type=checkbox]' to something more restrictive such as inputs that have a certain css class.

embed PHP in jQuery .append()

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.

Categories