I'm creating a wordpress plugin and I use the wp_ajax_[your action] callback. In my code the php return nothing to the javascript (no echo, no return). If the php return no value, the 'data' in 'success: function(data)' is empty so why the 'click' trigger work?
the js:
$(document).one('click', '#publish', function (event) {
event.preventDefault();
jQuery.ajax({
type:"post",
url: ajaxurl,
data: {action: 'save_img_data', imgUrlsArray: iUrlsArray, imgNamesArray: iNamesArray, pid: pl_vars.post_id},
success: function(data) {
$('#publish').trigger( "click" );
}
});
});
the php:
function lmg29_img_data() {
$pid = $_POST['pid'];
$iUrlsArray = $_POST['imgUrlsArray'];
$iNamesArray = $_POST['imgNamesArray'];
if (isset($iUrlsArray) and isset($iNamesArray)) {
update_post_meta( $pid, 'lg29_urls', $iUrlsArray );
update_post_meta( $pid, 'lg29_names', $iNamesArray );
die();
}
}
add_action("wp_ajax_save_img_data", "lmg29_img_data");
as you can see there's no response:
The HTTP response code is 200, so it's considered a successful request. Actual data in the response is not required.
And, to be clear, functions in JS don't have mandatory arguments. There's no error if you call a function with arguments in its' declaration without any arguments provided.
A failure occurs if the response code is, for example, 400-something or 500-something. Like 404 or 503. https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
To see how to set a response code read this:
http://php.net/manual/en/function.http-response-code.php
if you make a POST request, there is no data in success.
$.ajax({
url: "/post/url.php",
type: "POST",
data: parameters,
success: successFunction /*no data argument*/,
error: errorFunction
});
Therefore, success is "called" (and your trigger happens) but data means nothing.
Related
jquery.js?ver=1.12.4-wp:4
POST https://xyz/update.php 500 (Internal Server Error)
send # jquery.js?ver=1.12.4-wp:4
ajax # jquery.js?ver=1.12.4-wp:4
myFunction # 6011c7fbf.min.js?ver=1600216310:3
onclick # (index):453
I am getting a 500 error above from the console. What I dont know is whether the error is in my PHP in trying to update the row or elsewhere.
PHP below is contained inside my update-file.php file
function function_1() {
global $wpdb;
$wpdb->query( $wpdb->prepare("UPDATE 'my_table_name' SET `currentstatus` = 'myupdate1' WHERE ID = '1'"));
}
JAVASCRIPT contained on the page
function myFunction() {
jQuery.ajax({
type: 'post',
url: '/wp-content/themes/yummy/update-file.php',
success: function(data){
// callback function
}
});
alert("I've been clicked!!");
}
HTML
Go!
EDIT 1
As per suggestions I have updated as such:
JAVASCIPT
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
action: 'function_1',
success: function(data){
// callback function
}
});
Thinking the above was not correct I also tried :
jQuery.ajax({
type: 'post',
url: my_ajax.https://myurl.com/wp-content/themes/yummy/update-waitinglist.php, // this is the location of the update php below
action: 'function_1',
success: function(data){
// callback function
}
});
PHP below is contained inside my update-file.php file
add_action('wp_ajax_function_1', 'myfunctionname'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'myfunctionname'); // non logged in user can make a call
function myfunctionname() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'my_table_name' SET `currentstatus` = 'myupdate1' WHERE ID = '1'"));
die($results);
}
ADDED TO FUNCTIONS FILE
wp_localize_script('myfunctionname', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
With the EDIT 1 in place, I also get an error - Notice: wp_localize_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. This notice was triggered by the wait list_update handle. Please see Debugging in WordPress for more information. www.xyz.com/wp-includes/functions.php on line 5225 . I must have misunderstood something in the suggestion.
EDIT 2 Got everything else working but the button doesnt seem to update anything.
PHP from functions file -
function my_scripts() {
wp_enqueue_script( 'waitlist_update_call', get_template_directory_uri().'/assets/js/waitlist_update_call.js', array('jquery'), null, true );
wp_localize_script('waitlist_update_call', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
echo getcwd();
//calls Waitinglist data and creates table
}
add_action('wp_enqueue_scripts', 'my_scripts');
add_action('wp_ajax_waitlist_update_function', 'waitlist_update_function'); // logged in user can make a call
function waitlist_update_function() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'mytablename' SET `currentstatus` =
'myupdate1' WHERE ID = '1'"));
die($results);
}
JS
// JavaScript Document
function update() {
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
// add your action inside data object
data: {
action: 'waitlist_update_function'
},
success: function(data){
// callback function
}
});
}
HTML
Go!
The issue should be with the URL, it must be absolute I think.
jQuery.ajax({
//....
url: 'http://yourwebsite.com/wp-content/themes/yummy/update-waitlist.php'
// ...
The WordPress way
You must enqueue your JS file script.js before with same handle
and then localize after it
Localize the script to pass generic data. We will pass the ajax_url with my_ajax object.
functions.php
wp_localize_script('your-script-handle', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
Then in your script file, you can use the my_ajax object to get the AJAX URL. Define a action function_1 which will be executed when this AJAX call is requested.
script.js
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
data: {
action: 'function_1',
}
success: function(data){
// callback function
}
});
Define a function and attach it with Ajax action that will query the database & returns the result.
functions.php
add_action('wp_ajax_function_1', 'function_to_execute_some_query'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'function_to_execute_some_query'); // non logged in user can make a call
function function_to_execute_some_query() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'wp_wpdatatable_4' SET `currentstatus` =
'myupdate1' WHERE wdt_ID = '1'"));
die($results);
}
I tried to pass a json object from my test.php to my jquery in index.html but i can't.
here is my test.php script:
<?php
if(isset($_POST["view"]))
{
$output .= '
<li>No Notification Found</li>
';
$total_row=2;
$data = array(
'notification' => $output,
'unseen_notification' => $total_row
);
echo json_encode($data);
}
?>
and here is my jquery script , "the alert in js show undefined as result":
function load_unseen_notification(view = '')
{
$.ajax({
url:"test.php",
method:"POST",
data:{view:view},
dataType:"json",
complete:function(data)
{
alert(data.notification);
$('.dropdown-menu').html(data.notification);
if(data.unseen_notification > 0)
{
$('.count').html(data.unseen_notification);
}
}
})
}
In PHP, you need to put a header response from the server so that the browser knows what it got in response (see: https://www.iana.org/assignments/media-types/media-types.xhtml , http://php.net/manual/en/function.header.php):
<?php
header("Content-Type: application/json");
In JavaScript, you need to use success event:
$.ajax({
url: "test.php",
method: "POST",
data: {
view: 10
},
dataType: "json",
success: function(data) {
alert(data.notification);
}
});
success - A function to be called if the request succeeds.
Arguments: ( Anything data, String textStatus, jqXHR jqXHR ).
complete - A function to be called when the request finishes (after success and error callbacks are executed).
Arguments: ( jqXHR jqXHR, String textStatus )
Documentation: http://api.jquery.com/jquery.ajax/
If to use complete, then access to data can be got by means of jqXHR Object (see: http://api.jquery.com/jQuery.ajax/#jqXHR):
complete: function(jqXHR) {
if (typeof jqXHR.responseJSON !== 'undefined') {
alert(jqXHR.responseJSON.notification);
}
}
Of course if necessary it is possible to combine different event handlers.
P.S. For debugging use console.log(data) instead of alert(data) and look through the log in the browser. For example, for Google Chorme (F12, Tab: Logs): https://developers.google.com/web/tools/chrome-devtools/console/get-started
It might be a good idea as well to set the content-type header at the top of your PHP script:
<?php
header("Content-Type: application/json");
jQuery will probably interpret the body as JSON instead of 'text'.
I added $.trim()to my data.responseText and finally it's working (i don't know why :) )
var obj = JSON.parse($.trim(data.responseText));
$('.dropdown-menu').html(obj.notification);
Thx a lot for you all for your assisting
I have this JavaScript code:
<script type="text/javascript">
$(document).ready(function() {
$(".deleteImage").on('click', function() {
var idmess = $(this).data("id");
var token = $(this).data("token");
$.ajax({
url: '{{ url('admin/deletemulti') }}/'+encodeURI(idmess),
type: 'DELETE',
dataType: "JSON",
data: {
"id": idmess,
"_method": 'DELETE',
"_token": token,
},
success:function() {
alert("it Work");
}
});
});
});
</script>
is working just fine (data is removing from my DB and I get 200 in network), except I cannot get my alert any idea why is that?
UPDATE
my network
my network response
Delete Function
function destroy(Request $request) {
$image = Image::find($request->id);
Storage::delete($image->name);
$image->delete();
}
try passing an argument in your success function.
success:function(data) {
alert("it Work");
}
You have used ajax with dataType : json
So you need to respond with a valid JSON as HttpResponse else it gets into a error event.
The response of your api call:
{{ url('admin/deletemulti') }}/'+encodeURI(idmess)
should be a valid JSON. Please check api response value and fix it, or share it so that we can help you update that.
In case the response is not a valid JSON, success function will never get triggered and hence alert is not getting executed.
More info :
Ajax request returns 200 OK, but an error event is fired instead of success
When I'm making backend for myown use, and when I'm writing json, I usually put my json on success like session = true, or something like that, so later you can check like :
success: function(json) {
if(json.session == true) {
alert('something')
}
}
Maybe it's not the best solution, but it's working perfectly for me.
So like this post's title says, I'm sending a POST request via jQuery's AJAX method. However, the PHP code it runs does indeed run. Everything in the PHP code works as it should. The only issue is that it's not returning a success in order to run the success function.
Client-Side JS Code:
<script>
function commandUpdate(command, action, element) {
$.ajax({
type: "POST",
url: "update/commands.php",
data: {id: window.location.href.split("?id=").slice(1).join("?id="), type: "NA", command: command, action: action, value: document.getElementById(command + "Text").value},
success: function() {
document.getElementById(element).innerHTML = "🗸"
location.reload()
}
})
}
</script>
Server-Side PHP Code:
<?php
$connection = mysqli_connect("myIP", "user", "pass", "dbName");
$loginID = $_POST["id"];
$type = $_POST["type"];
$value -> command = str_replace("\"", "\\\"", $_POST["command"]);
$value -> action = str_replace("\"", "\\\"", $_POST["action"]);
$value -> value = str_replace("\"", "\\\"", $_POST["value"]);
$value = json_encode($value);
mysqli_query($connection, "INSERT IGNORE INTO requests (loginID, category, type, value) VALUES ('$loginID', 'commands', '$type', '$value')");
mysqli_close($connection);
?>
All of it works, except for the fact that the console has the 500 Internal Server Error and the success: function() {//code} part isn't being executed. Is there something that I'm missing here?
500 Code means something isn't working on the server-side. I had a similar situation where a different server than my own gave this problem even though it provided all of the information itself and seemed to work well.
I couldn't resolve the 500 error, so eventually just put an always() listener on the call and conditioned 200 and 500 codes along with expected data structure.
since you're not storing the call in a var. you can do it like this:
function commandUpdate(command, action, element) {
$.ajax({
type: "POST",
url: "update/commands.php",
data: {id: window.location.href.split("?id=").slice(1).join("?id="), type: "NA", command: command, action: action, value: document.getElementById(command + "Text").value},
success: function() {
document.getElementById(element).innerHTML = "🗸"
location.reload()
}
statusCode: {
200: function(){
document.getElementById(element).innerHTML = "🗸"
location.reload()
}
500: function(){
document.getElementById(element).innerHTML = "🗸"
location.reload()
}
}
})
}
or chain it:
$.ajax({
/*options*/
}).always(function(data){
if(data.statusCode === 200 || data.stausCode === 500){
/*Do things with data*/
}
});
I had this same issue. For me the problem was in the page to which the ajax call was made (calling a function which wasn't available in that page). My suggestion is to go to the page that you are calling in ajax and see the errors in that page. Once you fix that, the ajax call should go through fine.
I'm trying to display the result of a php function that I call in AJAX into a div 'TARGET'. I can't understand what I am doing wrong....
MY HTML
<div id="TARGET"></div>
MY AJAX
$(document).on('click', '.actualiser_btn', function(){
var id_contenu = $(this).attr("id");
$.ajax({
url:"/ajax-script.php",
method:"POST",
data:{id_contenu:id_contenu},
dataType:"json",
success:function(data)
{
$('#TARGET').html(<?php $return ?>);
}
})
});
MY AJAX SCRIPT
...
$return = wysiwyg( $_POST['id_contenu'],'basique') ;
echo $return ;
?>
When I click on the script in my network debugger I exactly see the script that I want so I conclude my function works well... What Am I doing wrong?
You have to use data to update the html like $('#TARGET').html(data.key);
$(document).on('click', '.actualiser_btn', function(){
var id_contenu = $(this).attr("id");
$.ajax({
url:"/ajax-script.php",
method:"POST",
data:{id_contenu:id_contenu},
dataType:"json",
success:function(data)
{
$('#TARGET').html(data.key); /*Since data is json, you might want to access the right key/value to set as html*/
}
})
});
http://api.jquery.com/jquery.ajax/
success function
Type: Function( Anything data, String textStatus, jqXHR jqXHR ) A
function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.
The first parameter of the success function is the data received from the backend.
Replace $('#TARGET').html(<?php $return ?>); with $('#TARGET').html( data );
as shown below.
Also note that the dataType option in the ajax request expects a JSON response therefore, ensure that your response is in a JSON format. Alternatively, remove the option.
$(document).on('click', '.actualiser_btn', function(){
var id_contenu = $(this).attr("id");
$.ajax({
url:"/ajax-script.php",
method:"POST",
data:{id_contenu:id_contenu},
dataType:"json",
success:function(data, status){
$('#TARGET').html( data );
}
});
});