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.
Related
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
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?
I am developing a plugin for WordPress system for some custom media review purpose. I have setup most of the things but few more.
Currently I stuck on the part to update database on click ( onlink ) to update table value using AJAX. Refer below code. It has while loop and I want to use AJAX within the loop to update media status. I am not sure is this the right way or there is another simple way to make it happen. Any suggestion would be appreciated.
Code:
<?php
$media_item = mysql_query($media_sql);
if ($media_item) {
echo '<ul class="rm-media-list">';
while ($media = mysql_fetch_array($media_item)) {
$m_uid = $media['user_id'];
$m_uname = $media['user_login'];
$media_class = new q2a_review_media;
$thumb_path = $media_class->rm_thumbnail_url($pid,$m_uid);
$media_url = $media_class->rm_media_url($pid,$m_uid);
$mediaid = $media['id'];
$image_name = $media['image_name'];
echo '<li>';
echo '<span class="rm-media-user">',$m_uname,'</span>';
echo '<a href="'.$media_url.$image_name.'" rel="lightbox['.$pid.']" title="Post: '.$pid.' | '.$ptitle.' | Image: '.$image_name.' | by: '.$m_uname.' " ><img src="'.$thumb_path.$image_name.'" alt="'.$media['image_name'].'" width="56" class="rm-thumbs-list" /></a>';
echo '<span class="rm-action-links"><a href="#" id="approve-'.$mediaid.'" >Approve</a> | <a href="#" id="delete-'.$mediaid.'" >Delete</a></span>';
echo '</li>';
}
} else {
echo 'No media found';
}
echo '</ul>';
?>
Database Table:
My Plugin Page Output
In above image you can see link called Approve | Delete Here I want to make interaction with database using ajax. When admin click on Approve it will update value from 0 to 1 in status column and when Delete than it will delete the row and images from the directory. Hope I posted enough data to understand. If not please let me know I will try to add some more information.
Million thanks.... :)
Firstly, your statement echo '</ul>'; needs to be in the if part of the loop.
Your AJAX code doesn't have to be inside the while loop. Here is how you can manipulate your code to make an AJAX request.
Let's first modify your <a> tag slightly:
Approve
This change allows you to have a group of buttons with class="approve-button" and id="the id of the item you want to approve"
Now, we can use some JavaScript to make an AJAX request. For convenience, I will use jQuery to make this request:
<script type="text/javascript">
//Attach an onclick handler to each of your buttons that are meant to "approve"
$('.approve-button').click(function(){
//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");
Make an AJAX request
$.ajax({
url: "some-page.php", //This is the page where you will handle your SQL insert
type: "post",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});
});
</script>
As far as some-page.php goes, this is what you need to do:
Have your SQL statements that will make the changes to he database
To access the ID attached to the approve button that was clicked, you can use the $_POST array since the AJAX request was of type "post". Specifically, this is where your ID is stored: $_POST['id']
FYI: To import jQuery on your page, you can use:
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
I am echoing data into a table with values from my database. It looks like this:
<?php
//mysqli_num_rows function
while($row=mysqli_fetch_array //I know this may be wrong, but that's not the point
echo "<tr><td>".$somedata."</td></tr>";
?>
So the value of this table row will be displayed based on how much data is in the database. I want to asynchronously update the page, for example the user wants to delete this from the DB. How can I pass this value to javascript with an onClick function? Or is there another way? If I have a link to delete in the table like:
<td><a onClick="delete(ThisValueOfThisTableRow)">Delete</a></td>
And in javascript or jQuery I want to find this value and set it to a variable, then pass it as:
var some_value = //get this value
.ajax{
url: "somephpfile.php"
data:{some_value:value}
}
I think this would be helpful to anyone if they a responsive member page. Please help out!
maybe something like this:
<?php
//mysqli_num_rows function
while($row=mysqli_fetch_array) {
?>
<tr>
<td><?=$somedata;?></td>
<td><a href='#' class='delete-btn' id='row-<?=$someID;?>'>Delete</a></td>
</tr>
<?
}//end while
?>
and then for the js event
$('.delete-btn').click(function() {
var id = $(this).attr("id");
id = id.split("-");
data = { "id" : id[1] }
//your ajax here, pass in your data obj
});
best of luck-
PHP
while ( $row = mysql_fetch_array( $result ) ) {
echo '<tr><td><a onclick="delete_row(' . $row['id'] . ')">delete row</a></td></tr>';
}
Javascript
function delete_row( id ) {
alert( id ); //To show you are getting the id remove this for production
//ajax goes here
}
I have a php drop down which populates from mysql
When a user selects a drop down item, i would like to store this selected value in a session variable
The reason for doing this is, that i need to call this session variable to dynamically update second drop down based the previous selection..
how can i do this?
Thanks,
while ($row2 = mysql_fetch_assoc($result2))
{
echo '<option value="' . $row2['subject_id'] . '">' . $row2['subjectname']. '</option>';
}
echo '</select>';
You cannot do this in PHP without calling another PHP file, e.g. by sending a form. The code to set a session variable is trivial:
<?php
session_start();
$_SESSION['selectname'] = $_REQUEST['selectname'];
?>
As a previous comment mentioned, to "dynamically" update a session variable you'd have to use javascript (jQuery is a good library to use). If you add a event handlers to the dropdown box: onChange='updateVar();' and then create a javascript function to update the value of the variable. One way this function could work is to use ajax to call a php page which updates the session variable.
A jQuery example:
$("select[name='dropdownBox']").change(function() { //event handler
newvalue = $(this).val(); //get selected value
$.ajax({
type : 'GET',
url : 'ajax.php',
dataType : 'json',
data : {
p : 'updateVar',
v : newvalue
},
success : function(data) {
//on success code
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
//on error code
}
});
} );
Then you just need a simple php script that grabs the $_GET variables and updates the $_SESSION variables required.
Hope this helps