WordPress - Ajax success function giving empty response - php

I have this script:
<script type="text/javascript">
jQuery(document).on("click",".pending-post-approve-link",function(e){
jQuery('#review_post_status').val('approve');
var globalVar = jQuery(this).find('.review_post_id').val();
jQuery('#review_post_current_id').val(globalVar);
jQuery('#post-preloader-'+globalVar).fadeIn(500);
$.fn.wpjobusSubmitFormFunction();
});
$.fn.wpjobusSubmitFormFunction = function() {
var globalVar = jQuery('#review_post_current_id').val();
jQuery('#wpjobus-pending-posts').ajaxSubmit
({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: jQuery('#wpjobus-pending-posts').serialize(),
type: "POST",
success: function(response)
{
jQuery('#post-preloader-'+response).fadeOut(100);
jQuery('#post-'+response).fadeOut(100, function()
{
jQuery(this).css('display', 'none');
});
return false;
}
});
}
});
</script>
When this script runs, it gives me empty response. I don't know what causing this problem. This is happening in the success function of the ajax success: function(response).
Any help would be appreciated.

You might have done some of those steps, but myself I would take this approach to find the issues:
Use a tool such as Google Chrome console or Firebug for FF to check if your request is being sent to the expected url, and that it is getting an expected response.
If it is not getting the expected response, the issue is serverside and you should look there. You can also make some breakpoint using the same tools (console/firebug) to see if the parameters which you are passing look as expected (you can check the POST header details instead too).
Finally you can try placing a breakpoint on the success function to be sure that it gets executed at all and that the response is an empty string, and not something else.
I hope this helps.

Related

Value from Ajax shows in console but it's not working as a Php value

i've got a little question regarding the usage of Ajax. I've done a search for the same issues but i can't find something to look alike with my problem.
Here is my code.
$(document).ready(function()
{
$("#nume").blur(function() {
numeform = $("#nume").val();
if (numeform){
$.ajax({
type: "POST",
url: "../../index.php",
data: {numeform : numeform},
cache: false,
success: function(response) {
data = numeform;
console.log(data);
}
});
}
});
});
and in the php file i have
$data = $_POST['data'];
echo $data;
The console shows as it should. Any help is greatly appreciated.
The console is logging the variable you are sending not what you're receiving, that is why it looks correct. If you log response then you'd see a problem.
For the PHP part you're reading $_POST['data'] when you should be reading $_POST['numeform'] becuse that is what you sent in your ajax request
{numeform : numeform}

Jquery Ajax response doesn't work on Firefox

This is the response in php. I can confirm the datas are ok.
$ajax_response = array(
'product_code' => $ajax_products,
'filter' => $ajax_filter
);
echo json_encode($ajax_response);
exit();
Here is the code in javascript :
$('#pr_category_filter').submit(function (event) {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
success: function (data) {
if (data.product_code != null) {
$('#pagination_contents').replaceWith(data.product_code);
}
if (data.filter != null) {
$('#category_filter').replaceWith(data.filter);
}
},
error: function (request, status, error) {
return false;
}
});
event.preventDefault(event);
});
This code works well on Chrome and Opera. However, this code doesn't work on Firefox because the php "echo" is displayed on Firefox instead of ajax response. I also tried to put a console.debug('invoked') in the javascript. No result is displayed in Firefox in contrary of Chrome. Do you know the reason ?
The response is the same into browsers tools development.
Thanks
The function .preventDefault() does not accept any arguments.
Probably Firefox therefore does not accept this and simply submits the form. Chrome however does not really care and does accept it.
So change
event.preventDefault(event);
Into
event.preventDefault();
That should do the trick
You need to use the header() function in PHP to specify the content-type of the response you're returning to the AJAX call. Try the following (place it before you echo the response):
header('Content-Type', 'application/json');

jQuery ajax beforeSend interfering with .done()

In a website I have several ajax-parts that are loaded by events, mostly clicks. To inform the visitor a loading partial is shown. This works nice most of the time, but sometimes the ajax call is receiving the respons so quick it interferes with the beforeSend.
My typical structure looks like this:
$(document).on('click', '.handler', function() {
var target = $(this).attr('data-targetElement');
$.ajax({
url: '/ajax.php?someParameter=hasValue',
beforeSend: showLoading(target)
})
.done(function(response) {
console.log('Hi there, I\'m done!');
$('#' + target).html(response);
});
});
// This is in a function because it's used by all ajax-calls
function showLoading(target) {
$('#' + target).html('My loading message');
}
The problem is, when I'm inspecting console messages, that the loading message is still shown even though the .done() was reached, because Hi there, I'm done! is shown.
So it looks beforeSend doesn't seem to have reached a completed state or something like that causing it to 'freeze', because the content in the targetElement is not updated with the response for the ajax-call.
I'm not sure how to solve to this. Any suggestions?
Update,
Sorry for the typo, I just typed the exemplary code in here...
At first, you need to fix all syntax errors in your code.
Remove ; in the middle of the statement.
$.ajax({
beforeSend: showLoading(target);
// ^ SYNTAX ERROR
})
When you write showLoading(target) you call the showLoading() function immediately.
If you need to set pass it as a callback with parameters, you need to pass a function, that returns your callback.
beforeSend: function() {
showLoading(target);
}
Try removing syntax error semicolon ; at close of beforeSend , utilizing var target = $(this).data('targetelement'); for target variable
$(document).on('click', '.handler', function() {
var target = $(this).data('targetelement');
console.log(target)
$.ajax({
type:"POST",
url: '/echo/html/',
beforeSend: function() {showLoading(target)},
data:{html:"Hi there, I\'m done!"}
})
.done(function(response) {
console.log(response);
$('#' + target).html(response);
});
});
// This is in a function because it's used by all ajax-calls
function showLoading(target) {
$('#' + target).html('My loading message');
}
jsfiddle http://jsfiddle.net/4xp1aag8/1/

Jquery ajax request showing a old response

Hi I have a jQuery ajax request for a login system. At first, it worked very well. But after a few try, it just started to show negative response. I checked firebug and it says that the response is, in my case "Connected". But the ajax response just shows "Not_connected". I don't know what to do :(. Please help me.
This is my jquery code :
var data_str = "username="+usrn+"&password="+pwd;
$.ajax({
type: "POST",
url: "index.php?rnd=" + Math.random(),
data : data_str,
complete : function(xhr,data){
if(data == 'connected'){window.location.href = 'admin.php';}
else if(data = 'not_connected'){ error_gen.html('Invalid username or password'); }
alert(data);
}
});
AS for the PHP code :
$log_result = $u_obj->login_user();
if($log_result == true)/*user is connected*/
{
echo 'connected';
exit;/*stoping the script after sending the result*/
}
elseif($log_result == false)/*error while logging in*/
{
echo 'not_connected';
exit;/*stoping the script after sending the result*/
}
Look at this thread: Is it possible to cache POST methods in HTTP?
It might be that there are headers which now make browser caching the response (although it's POST).
Also instead of rnd=" + Math.random() you can add write
$.ajax({
type: "POST",
cache: false,
..
Could it be browser caching?
Try adding this $.ajaxSetup({ cache: false });
You are using the wrong $.ajax option to retrieve the result. You should use the success option. Just change the
complete : function(xhr,data){
line for
success : function(data){
It should work.

$.ajax() isn't working properly with ajax

I was coding an usual jquery+AJAX code, but it isn't working and i really don't gettinh why!
This is the part of my code that isn't working properly:
var data = $("#data_res").val();
var infoData = data.split("/");
var dataDb = infoData[2]+"-"+infoData[1]+"-"+infoData[0];
$.ajax({
type: "POST",
url: "reserva_ajax.php",
data: {action: 1, data: dataDb},
success: function(retorno)
{
var qtd = parseInt(retorno, 10);
alert("Qtd: "+qtd);
if(qtd > 0) {
//for now, qtd is always 0
}
else{
var id = $("#id_func").val();
var obs = $("#obs_res").val();
alert("id: "+id+" | obs: "+obs+" | dataDB: "+dataDb);
$.ajax({
type: "POST",
url: "reserva_ajax.php",
data: {action: 1, data: dataDb},
succes: function(a)
{
alert("sucess! a="+a);
},
error: function(b)
{
alert("Error!");
});
alert("passed =/");
}
},
error: function()
{
alert("Erro! Try again.");
}
Maybe the fact of being an ajax request inside another ajax request do the error. But I think that it's not the problem, since the ajax only is executed after the first one has finished.
The first ajax run ok, then the "Qtd: 0" is shown. Then the code goes to the else condition (since qtd isn't greater than 0), the second alert is shown:
alert("id: "+id+" | obs: "+obs+" | dataDB: "+dataDb);
everything OK.
But then, I get the problem! The ajax is executed (I think) but it doesn't execute the success block neither the error block, so the alert printed is:
alert("passed =/");
I know that the ajax is asynchronous and the success and error alert probably will be executed after "passed" one, but they are never executed.
Please someone can help me?!
The php code is that:
<?php
include_once 'classes/reserva_class.php';
if(isset($_POST["action"]))
{
$action= (int) $_POST["action"];
switch($action)
{
case 1:
echo Reserva::getQtdReservasData($_POST["data"]);
break;
case 2:
echo "=)";
break;
}
}
?>
You're missing a closing } on your error action callback, and your success callback is actually called succes. It should look like this:
$.ajax({
type: "POST",
url: "reserva_ajax.php",
data: {action: 1, data: dataDb},
success: function(a)
{
alert("sucess! a="+a);
},
error: function(b)
{
alert("Error!");
}
});
By the way, you shouldn't 'think' that your ajax request is being executed... Pop open Opera Dragonfly or WebKit's Web Inspector or whatever developer tools of whatever browser you're using and hit the 'Network' tab, you will then be able to see every request that is made, and ensure that 2 are being sent.
It looks like you're missing a closing curly brace on your "error" event on the second AJAX call.
If that doesn't fix it, try adding the "Complete" event to see what your ajax page is returning, if you're getting nothing back from "Error" or "Success".
i think you misstyped one of your ajax options : type "Success" instead of "succes"

Categories