I built an ajax function which works perfectly when i hook it to admin_head or admin_notices hooks but it doesn't work when i hook it to manage_posts_extra_tablenav hook, instead of doing the ajax call it just reload the page and the url of the opened page after page reload is
Request URL: http://localhost/wc/wp-admin/edit.php?s=&post_status=all&post_type=product&_wpnonce=c1a10340ac&_wp_http_referer=%2Fwc%2Fwp-admin%2Fedit.php%3Fs%26post_status%3Dall%26post_type%3Dproduct%26action%3D-1%26product_cat%26product_type%26stock_status%26paged%3D1%26action2%3D-1&action=-1&product_cat=&product_type=&stock_status=&paged=1&action2=-1
and that upper link do a 302 redirect to that link
http://localhost/wc/wp-admin/edit.php?s&post_status=all&post_type=product&action=-1&product_cat&product_type&stock_status&paged=1&action2=-1
This is my code, however both actions connected to the same function but the version on top works fine and the one on the other hook doesn't work, so i was wondering what is the reason and how to solve it?
add_action( 'manage_posts_extra_tablenav', 'apm_update_all_products_ajax' );
add_action('admin_notices', 'apm_update_all_products_ajax');
function apm_update_all_products_ajax() {
$product_ids = wc_get_products( array( 'return' => 'ids', 'limit' => -1 ) );
?>
<div class="apm_bulk_update_prices_wrap alignleft actions">
<button class="button apm_update_prices" id="update_prices" onclick="apm_update_all_products()">Update All Products</button>
<p id="apm_bulk_status">test</p>
</div>
<script type="text/javascript" >
product_ids = <?php echo json_encode($product_ids); ?>;
product_ids_n = product_ids.length;
product_ids_step = 0;
function apm_update_all_products() {
product_id = product_ids[product_ids_step];
$.ajax({
type: "POST",
url: ajaxurl,
dataType: "JSON",
data: {
action: 'apm_update_single_product',
postId: product_id
},
success: function(lookup_data) {
product_ids_step++
$('#bulk_status').text('Updated ' + product_ids_step + ' of ' + product_ids_n );
if (product_ids_step < product_ids_n) {
apm_update_all_products();
}
},
error: function(jqXHR, textStatus, errorThrown) {
}
})
};
</script>
<?php
}
and here is a screenshot showing the place of the 2 hooks
https://snag.gy/zNXUmv.jpg
Related
I understand this has been asked multiple times but I am unsure why this isn't working!
<?php
if(isset($_POST['testingajax'])) {
echo "Received";
} else {
echo "Not received";
}
?>
<button onclick = 'sendAjax()'>click me</button>
<script>
function sendAjax() {
$.ajax({
type: 'POST',
url: 'test.php',
data: {
testingajax: 2
},
success: function(data) {
console.log("AJAX POST SENT");
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
This is what shows after clicking the button, it should say Received
I have tried changing the URL to http://localhost/TESTINGPLANNER/src/test.php and ./test.php but no luck. Also, I have changed testingajax: 2 to 'testingajax': 2. From the network screenshot it seems like AJAX it is working so I am not sure where the issue is.
I'm trying to implement a functionality where user can like and unlike product using javascript I followed this Laravel - Favourite / Un-Favourite button but it doesn't work for me, the button can't be clicked, any idea on how I can fix this?
Routes
Route::get('product/like/{id}', ['as' => 'product.like', 'uses' => 'LikeController#likeProduct']);
Route::get('product/{product}/unlike','LikeController#destroy')->name('product.unlike');
Javascript
<script>
function addToFavourites(productid, userid) {
var user_id = userid;
var product_id = productid;
$.ajax({
type: 'post',
url: 'product/like/{id}',
data: {
'user_id': user_id,
'product_id': product_id,
},
success: function () {
// hide add button
$('#addfavourites' + product_id).hide();
// show delete button
$('#deletefavourite' + product_id).show();
},
error: function (XMLHttpRequest) {
// handle error
}
});
}
Blade file
#if($product->isLiked)
<div id="addfavourites{{$product->id}}" onClick="addToFavourites({{$product->id}}, {{ Auth::user()->id }})"> unlike </div>
#else
<div id="deletefavourite{{$product->id}}" onClick="deleteFromFavourites({{$product->id}}, {{ Auth::user()->id }})" > like </div>
#endif
Make your routes accept a post method because you're posting through Ajax
Route::post('product/like/{id}', ['as' => 'product.like', 'uses' => 'LikeController#likeProduct']);
Route::post('product/{product}/unlike', 'LikeController#destroy')->name('product.unlike');
And use ES6 template string and add a CSRF token header to the Ajax request
function addToFavourites(productid, userid) {
// Redundant
// var user_id = userid;
// var product_id = productid;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: 'post',
url: `/product/like/${productid}`, // Use ES6 template and point to the url from root /
data: {
'user_id': userid,
'product_id': productid,
},
success: function () {
// hide add button
$('#addfavourites' + productid).hide();
// show delete button
$('#deletefavourite' + productid).show();
},
error: function (XMLHttpRequest) {
// handle error
}
});
}
Hope this helps
I know that there is a lot of questions like this out there, but I have been surfing them and other website for like 4 hours trying to figure this out. I am trying to get main.js to post the data via ajax and then the php should echo that data. If it does not work, it will echo "null". It keeps echoing "null" instead of "John". I know that the jquery and main.js links work, I have tested them. Here is main.js:
$(document).ready(function(){
$.post("index.php", { test: "John"} );
});
And here is the php part of index.php:
<?php
$var = "null";
if(isset($_POST['test'])) {
$var = $_POST['test'];
}
echo $var;
?>
I hope you can solve my problem, and thank you in advance.
You are missing the callback function with the response from the server.
$.post( "index.php",{ test: "John"}, function( data ) {
alert(data);
});
Or you can do something like this:
$.post( "index.php",{ test: "John"})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Please check the documentation Documentation
Give this a shot
jQuery
var available agent = 1;
jQuery.ajax({
type: "POST",
url: "your-url",
data: available_agent,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data){
owner = data['round_robin_agent'];
},
error : function () {
alert("error");
}
});
PHP Script
public function round_robin() {
//Do your work
$round_robin_agent = 'rob';
$results_array = array(
'round_robin_agent' => $round_robin_agent
);
return json_encode($results_array);
}
Download HTTP Trace chrome extension, traceback ajax call and share a screenshot.
https://chrome.google.com/webstore/detail/http-trace/idladlllljmbcnfninpljlkaoklggknp
I am trying to delete images with Ajax and all the php seems to work except when I try to send variables to another php document.
Php that shows and grabs neccessary values.
// show images
$image_display = "";
foreach(glob($pathimages.'*') as $filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$name_only = basename($filename, ".".$ext);
$image_display .= "<img src=\"images/" .$targetID."/" .$name_only.".".$ext. "\" width=\"30\" />
<a onclick=\"DeleteImage('".$name_only."','".$ext."','".$targetID"'); return false;\" href=\"javascript:;\">X</a>
<br />";
}
.JS document, I get the sent and the success messages when pressing the X
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
delete_imgs.php document
include('session_check.php');
$name_only = $_POST['name_only'];
$ext = $_POST['ext'];
$targetID = $_POST['targetID'];
$pathimages = "images/$targetID/";
unlink($pathimages . $name_only .".". $ext);
echo "Deleted";
Any thoughts are more than welcome since I have banged my brain out of my head by now ...!
Cheers!
Try with async:false
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
async : false,
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
Maybe that can help
I am doing some Add, Edit, and Delete for my project in school. The codes in the add module went well, in fact I've added few records. Then, here comes the Edit module, at first it was quite good, similar codes was used from the add module. But as I try and try, the post in the edit module was empty.
here's my edit codes:
$(".careersEdit").click(function () {
var careersTableSelect = encodeURIComponent($("input:radio[name=careersTableSelect]:checked").val());
if (careersTableSelect > 0) {
$(".careersEditForm_load").show();
$(".careersEditForm_error").hide();
$(".careersEditForm").hide();
var dataStringCareersEdit = 'careersTableSelect=' + careersTableSelect;
$.ajax({
type: "POST",
url: "admin/careers/process/careersEditGet.php",
data: dataStringCareersEdit,
beforeSend: function(){
alert(dataStringCareersEdit);
},
success: function () {
setTimeout("", 5000);
fetchResult();
},
error: function () {
alert("Post Error");
}
});
function fetchResult() {
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "POST",
dataType: "json",
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result['position']);
$("input#careersEditCompany").val(result['company']);
$("input#careersEditLocation").val(result['location']);
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
}
} else {
$(".careersEditForm").hide();
$(".careersEditForm_load").hide();
$(".careersEditForm_error").show();
}
});
Here's the careersEditGet.php:
<?php
include('connect.php');
error_reporting(0);
$careersTableSelect = $_POST['careersTableSelect'];
//$careersTableSelect = $careersTableSelect + 1;
//echo $careersTableSelect;
$query = "SELECT * FROM atsdatabase.admincareers WHERE refNum ='" . $careersTableSelect . "' LIMIT 0 , 30";
$runQuery = mysql_query($query);
if (!$runQuery) {
die('Could not enter data: ' . mysql_error());
}
$result = mysql_fetch_row($runQuery);
$array = array(
'position' => "" . $result[1] . "",
'company' => "" . $result[2] . "",
'location' => "" . $result[3] . "",
);
echo json_encode($array);
mysql_close($connection);
?>
Yes, the code is ugly/wrong/crap, I'm quite new to jquery stuffs, about 3-4 days. To those that will help, please do correct me. I wanna learn this jquery ajax stuff. Gracias
Maybe try passing data in more common way:
change
data: dataStringCareersEdit,
to
data: { "careersTableSelect" : careersTableSelect },
Call your ajax function once like,
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "POST",
dataType: "json",
data: {careersTableSelect: careersTableSelect},
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result.position);// json not array
$("input#careersEditCompany").val(result.company);// json not array
$("input#careersEditLocation").val(result.location);// json not array
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
Thanks guys for all the effort to answer this question, I've consulted to a friend who's a web developer, taught me how to properly use ajax in jquery. ;)
You are doing something fundamentally wrong when u are posting Data from jQuery.Ajax..
The data should be an object and the key should be the name of the server side POST variable which will be used later in the PHP ...
Example :
data : {"server_side_vriable" : "Your_data_to_Post" }
......
var dataStringCareersEdit = 'careersTableSelect=' + careersTableSelect + "&careersTableSelect=" + careersTableSelect;
$.ajax({
type: "POST",
url: "admin/careers/process/careersEditGet.php",
data: {"careersTableSelect" : dataStringCareersEdit},
beforeSend: alert(dataStringCareersEdit),
success: function () {
alert("Fetching Result");
setTimeout("", 3000);
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "GET",
dataType: "json",
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result['position']);
$("input#careersEditCompany").val(result['company']);
$("input#careersEditLocation").val(result['location']);
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
},
error: function () {
alert("Post Error");
}
});