Update form with ajax - php

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

Related

Ajax visit link without actually visiting link

I've got a basic like button concept on my site that visits url.tld?action=love and adds +1 to the link's database column.
It's a hassle redirecting to another page all the time though. Is it possible to click the button, and send a request to the URL without actually redirecting to a new URL? Also maybe refresh the button afterwards only so that the count updates?
For a general idea of what my download button is this is in the header:
<?php require_once('phpcount.php'); ?>
<p class="hidden"><?php
$time = time();
for($i = 0; $i < 1; $i++)
{
PHPCount::AddHit("$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", "127.0.0.1");
}
echo (time() - $time);
/*echo "PAGE1 NON: " . PHPCount::GetHits("page1") . "\nPAGE1 UNIQUE: " . PHPCount::GetHits("page1", true);
echo "\n\n" . PHPCount::GetHits("page2");
$ntot = PHPCount::GetTotalHits();
$utot = PHPcount::GetTotalHits(true);
echo "###$ntot!!!!$utot";*/?></p>
And this is an example of my "love" button.
Love <span class="count">'. PHPCount::GetHits("$package_get?action=love", true).'</span>
The reason I used this method is because people create pages, and I wanted the like button to work out of the box. When their page is first visited it adds their url to the database, and begins tallying unique hits.
This is basically adding a new link column called downloadlink?action=love, and tallying unique clicks.
use the following code. assgin id="btn_my_love" to that button and add this code to you page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//assign url to a variable
var my_url = <?php echo "https://alt.epicmc.us/download.php?link='.strip_tags($package_get).'?action=love"; ?>;
$(function(){
$("#btn_my_love").click(function(){
$.ajax({
url:my_url,
type:'GET',
success:function(data){
//comment the following result after testing
alert("Page visited");
},
error: function (request, status, error) {
alert(request.responseText);
}
});
//prevent button default action that is redirecting
return false;
});
});
</script>
Yes, it is possible. I am assuming you know what ajax is and how to use it, if not I am not going to give you the code because some simple reading on ajax as suggested by #Black0ut will show you how. But the basic steps are as follows:
Send ajax request to a PHP script that will update +1 vote to the database
In the PHP script, add +1 to the database and return some data to the ajax, maybe the new number of votes
Parse the return data in your JavaScript and update the button accordingly

AJAX within a foreach loop

I am unfamiliar with AJAX and am having a difficult time trying to learn it for what I need.
I need to write ajax calls within a foreach loop.
if i just use PHP calls they will all fire even if i don't use the onclick event.
What im basically doing is writing out a list from the DB and adding a remove button to the row.
when the remove link is clicked, it will fire a query to update a field in the DB for item.
My index.php file
<?php foreach ($items as $item) : ?>
<tr>
<td><?php echo $item['item_name']; ?></td>
<td><a href="#" onclick="ajax call(arguments)" ></a></td>
</tr>
<?php endforeach; ?>
My PHP code: (note: I am using wordpress's $wpdb to query the WP database. query is valid. There is no user input, and its on an admin page so dont worry about prepare() or other injection defenses. )
<?php
$wpdb->query("UPDATE " . $wpdb->prefix."item
SET is_removed =" . $remove_option . "
WHERE item_id =" . $item_id );
?>
($remove_option is populated earlier in the index.php page, and $item_id comes from $items array)
I need to pass 2 variables through the ajax call, populate $remove_option and $item_id.
fire the query, return to index.php page.
How do I use ajax to achieve this? I'm completely unfamiliar with ajax, and i am not using a plugin for WP, only php scripts.
PHP part
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
add_action('wp_ajax_update_this', 'update_this_func');
add_action('wp_ajax_nopriv_update_this', 'update_this_func');
function update_this_func(){
$remove_option = $_POST['remove_option'];
$item_id = $_POST['item_id'];
global $wpdb;
$wpdb->query("UPDATE " . $wpdb->prefix."item
SET is_removed =" . $remove_option . "
WHERE item_id =" . $item_id );
return json_encode(['status' => 'Updated!']); // return status as json
}
Ajax call
http://codex.wordpress.org/AJAX_in_Plugins
function onClickingThis(rem_opt,itemid){
$.ajax({
url: ajax_url, // You can get this from admin_url('admin-ajax.php') function
type: 'POST',
data: {action: 'update_this', remove_option: rem_opt, item_id: itemid },
dataType: 'json',
success: function(response){
console.log(response);
}
});
}
can I achieve this with AJAX?
Yes
is there a better approach to what I'm trying to achieve?
If you want to send data from the client to the server then ajax is the best way to do so.

How to use wordpress function in an ajax php file

I am making a WordPress template, mytemp.php in wordpress 3.9. In this I can use wordpress functions. For example, below works perfectly.
$(document).ready(function() {
alert(<?php echo get_current_user_id() ?>);
}
However, this template file calls some ajax scripts too depending on user input. Over there it doesn't work. For example, below statement returns fatal error "call to undefined function get_current_user_id"
$sql = 'SELECT x,y FROM table WHERE user_id = ' . get_current_user_id();
I am guessing, I need to tell the ajax script to include some wordpress file or some global variable but I am not sure how.
I solved it. All I needed to do was to have below include statement.
include '../../../../wp-load.php';
By including this, it started recognizing the function get_current_user_id()
Try to include wp-load.php file in ajax file, after including this file wordpress functions are working properly in your ajax file or you need to write a plugin like ajax.php, and then use this plugin file for your ajax file.
After that you can access the wp functions.
Hope it'll helps.
Try this. I just answered a question not too long ago with this style of sql syntax using the function get_current_user_id();
$sql = "SELECT x,y FROM table WHERE user_id = %d", get_current_user_id();
Another solution would be to establish a contract between your ajax script and the javascript that posts to it.
So, in your calling php script, you could set up some JSON in your header:
<script>
<?php echo "wp-data = {current_user_id: " . get_current_user_id() "}"; ?>
</script>
And then put it in your ajax call:
$.ajax({
url: "http://yourdomain.com/process_wp_ajax.php",
method: "post",
data: {
. . . //your post data
current_user_id: wp-data.current_user_id;
})
.success(function(response) {})
.fail(function(response) {} )
.complent(function(response, status) {};
Your receive should expect "current_user_id" to be on the POST (or GET).
This involves more work, but you save yourself from loading the WP framework each time you make an ajax call.
Don't use the php above if you want to set multiple values. Set an object instead and just call json_encode on it:
<?php
wp_object = (object) array('wp-val1' => wp_func1(), 'wp-val2' => wp_func2());
?>
<script>
<?php echo "wp-data =" . json_encode(wp_object) . ";"; ?>
</script>
DRY, just pass the wp-data object directly in your ajax:
$.ajax({
url: "http://yourdomain.com/process_wp_ajax.php",
method: "post",
data: {
. . .
wp-object: wp-data,
}
. . .
So in your calling script, you would eventuall arrive at:
$sql = "SELECT x,y FROM table WHERE user_id = %d", $_POST['current_user_id']
or `$_POST['wp-object']['current_user_id']
(of course you would set the $_POST value in a ternary prior to this right?

MySQL database update through AJAX and 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.

ajax $_POST data then redirect to new page

I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.

Categories