Get a php variable back after an AJAX action? - ajax

When I click onto a button of my page, I do the following action :
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(){
alert("Vote done");
}
Then, the page of the url receive my POST variable to treat the vote:
<?php
// I get the timestamp of the last user's vote
list($last_timestamp) = get_last_timestamp($_SESSION['id'], $_GET['id']);
// I get the server timestamp
$timestamp_click=time();
if($timestamp_click-$last_timestamp > $time_limit){
$authorization_vote=false;
}else{
$authorization_vote=true;
}
I would like to get back and send $autorisation_vote to AJAX or jQuery in order to alert the user if his vote has been done. I heard about callback but don't succeed to adapt to my case. How do that ?

there's a couple of ways you could do it.
The quick and dirty way is to just echo "true" or "false" in your PHP and that will be available in to the callback function if you declare it like this
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(data){
alert(data);
}
or you could set the http header to return a status code, which would allow you to declare two call backs in your ajax call on success or failure
The php would look like this
<?php
// I get the timestamp of the last user's vote
list($last_timestamp) = get_last_timestamp($_SESSION['id'], $_GET['id']);
// I get the server timestamp
$timestamp_click=time();
if($timestamp_click-$last_timestamp > $time_limit){
header("HTTP/1.0 423 Locked"); // The resource that is being accessed is locked
}else{
header("HTTP/1.0 204 No Content"); // Processed, but not returning content
}
and your ajax call could look like this
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
statusCode: {
204: function(){ alert("Vote cast"); },
423: function(){ alert("Vote not cast for whatever reason..."); }
}
Which is probably a bit of overkill, but it's good to know these things.

$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(data){
alert(data);
}
(note added data)
and in your php script add
echo "vote done and some data here";
because true is changed to 1 and false would be blank
So example:
if($timestamp_click-$last_timestamp > $time_limit){
$authorization_vote=false;
echo "voted";
}else{
$authorization_vote=true;
echo "vote failed";
}

Related

Detect successful response from ajax function

I have a function which is triggered via AJAX and will run the following when successful:
wp_send_json_success();
I am then doing a console log of the response and trying to detect if success = true:
.done(function (response) {
if( response['success'] == true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Currently I am getting "add to cart failed" despite the output of response looking like it should be successful:
console.log(response);
// Response in the browser console:
{"success":true}
Am I detecting the true response incorrectly?
Update - PHP function the AJAX is triggering. Removed most code just as a test.
function fbpixel_add_to_cart_event_conversion_api() {
echo 'hello world';
wp_send_json_success();
die();
}
add_action('wp_ajax_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
add_action('wp_ajax_nopriv_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'fbpixel_add_to_cart_event_conversion_api',
product_id: productId,
variation_id: variationId,
},
})
.done(function (response) {
console.log(response);
console.log(productId);
console.log(variationId);
console.log(response.success);
if( response.success === true ) {
I always use dot notations to check the response returned from wp_send_json_success, and it always works. So use it like this:
if( response.success === true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Give it a shot and let me know if you were able to get it to work!
I should have pasted the entire code sorry. I had the wrong dataType set within $.ajax:
Before
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'html',
})
After
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
})

Jquery ajax method undefined

So my problem is that data returned in success method is undefined...
Here is my jquery code:
$('document').ready(function(){
$('#save').click(function() {
var dataString = $("#stepform").serialize();
$.ajax({
url: "<?php echo base_url();?>create/save/<?php echo $row->id; ?>",
type: 'POST',
data: dataString,
success:function(response){
alert(response.status);
}
});//end ajax
return false;
});//end click
}); // end document ready
And php code:
$serverResponse["status"] = 'it worked';
echo json_encode($serverResponse);
And all i'm getting from response.status is 'undefined'... I just can't make it work! Any ideas what i'm doing wrong?
-------------EDIT-------------
Finally i have managed to find a solution to invalid json response. If you are using codeigniter you must write exit() after json_encode. Something like this:
exit(json_encode($yourarray));
If you just echo it then it gives a parse error.
jQuery may not be properly guessing that you are returning JSON. Set the dataType: "json" property on the $.ajax argument object, or add
header("Content-type: application/json");
to your PHP script before emission, or both.

when ajax post success i want to refresh a particular <div> in page

i want to refresh a particular div on ajax success, im using the below code but the whole page getting refreshed.
<script type="text/javascript">
$('#post_submit').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
return false;
});
return false;
});
</script>
you have an extra return false which is inside the $.ajax block which most probably causes an error so your form isn't submitted via ajax. If you remove that, you shouldn't have any issues.
Use the submit event of the form and remove the return false from the ajax callback:
$('#myFormId').on('submit', function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
Remove the return false from inside your $.ajax function. Its a syntax error. The $.ajax function only expects a json object as an argument. "return false" cannot be part of a json object. You should keep the JavaScript console open during testing at all times - Press Ctrl-Shift-J in Chrome and select console to see any JS errors.
Also suggest you use <input type=button> instead of <input type=submit> or <button></button>

Jquery: probleme with $.ajax (json datatype)

I have a problem to refresh a bloc in my page.
Here is the request:
> $("#pwd_lost_link").click(function(){
alert('1');
$.ajax({
type : 'POST',
url: 'test.php',
dataType: 'json',
data :{"nom" : "akbar"},
success : function(data){
$("#main_bloc").append(data.msg);
alert('2');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
alert(errorThrown); }
}); })
and here is the php file
<?php
$return['nom'] = "ffrfrfrfr";
echo json_encode($return)
?>
It doesn't work. It give me a status error ( 0 ) and the page is automatically reloaded
Thanks
Michaƫl
Confusing question Michael, not sure what you mean by "the page is automatically reloaded" but you should do 2 things:
In the $.ajax() method, make sure your success called back is handling the data correctly. You are looking for data.msg but I don't see where .msg comes from.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
url: url,
success: function(data) {
// parse data object so you can see what's being returned ex. alert(data) or alert(data[0]) or alert(data.nom)
},
error: function (xhr, status, error) {
// XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp
// check for errors ex. alert(xhr.statusText);
}
});
On the PHP side, you may want to debug there to see what is being received and what you are sending back.
Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful.
And on a final note, if pwd_lost_link is a link elment a id="pwd_lost_link" href="..." then you will have to stop the browser from following the link before you process the AJAX.
$("#pwd_lost_link").click(function(e) {
e.preventDefault();
alert('1');
$.ajax({
...
});
If you aren't seeing the '1' being alerted then that is definitely your first problem.
You're trying to access data.msg, but your PHP script is only creating data.nom. So data.msg doesn't exist. Try changing data.msg to data.nom and see if this does what you want.

Ajax in Wordpress plugin

I am creating a simple wordpress plugin and trying to use AJAX, but I always get 0 in ajax response.
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: '1234'
};
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response) {
alert(response);
});
});
</script>
<?php
add_action('wp_ajax_my_action', 'my_action_callback');
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
echo "test";
die();
}
what am I doing wrong?
You have to put the add_action at the complete bottom of your file or else it won't find the callback function
Try to change :
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response)
To :
jQuery.post(ajaxurl, data, function(response)
And check if it is working on the admin side first. It should work fine.
Error Return Values
If the AJAX request fails when the request url is wp-admin/admin-ajax.php, it will return either -1 or 0 depending on the reason it failed.
Read this
Edit
admin-ajax always return default '0' as output.so while you alerting response you will 0 only.using die() in callback function will terminate that.
Had the same problem, it turned out that my callback was inside a php file which was only included to my "Theme Options" page.
To check if the function is able to trigger trougth admin-ajax.php try to add var_dump(function_exists("your_callback_name")); to the bottom of the wp-admin/admin-ajax.php (before die( '0' );) and then have a look to your ajax output.
Try the following code in your plugin file. or in function.php
jQuery(document).ready(function($){
var ajaxURL = 'http://localhost/taichi/wp-admin/admin-ajax.php';
var dataString = 'action=mnd_news';
$.ajax({
type: "POST",
url: ajaxURL,
data: dataString,
cache: false,
success: function(response){
if(response != 'error') {
alert(response);
}
}
});
});
add_action('wp_ajax_mnd_news', 'get_mnd_ajax');
add_action( 'wp_ajax_nopriv_mnd_news', 'get_mnd_ajax' );
function get_mnd_ajax() {
echo "test";
die();
}

Resources