Migwell
Migwell

Reputation: 20127

Not getting the success callback for an ajax query to my php page

Edit: changed $.alert() to alert()

I've got a file, planner.php that uses JQuery to send an ajax request to the same page. Using the debugger, I can see that the php correctly gets the request, accesses my database, and then sends the data. However even after sending it I get no success callback in the javascript. What's wrong?

JQuery:

$(function()
{
    $.post('planner.php', {"want": "keys"}, success_func, 'json');
});

function success_func(result)
{
    //This is never called :(
    alert("Worked");
}

PHP:

<?php
require_once "./php/couch.php";
require_once "./php/couchClient.php";
require_once "./php/couchDocument.php";

if (count($_POST) > 0 && array_key_exists("want", $_POST)) {
    $couch_dsn = "http://localhost:5984/";
    $couch_db = "subjects";
    $client = new couchClient($couch_dsn, $couch_db);
    header('Content-type: application/json');
    $response = $client->getView('subject_views', 'keys');
    echo json_encode($response);  //This all seems to work fine
}
?>

It's that simple. All of the PHP code there is just accessing couchDB which you don't have to worry about because I know that $response is set correctly.

Upvotes: 0

Views: 77

Answers (4)

Migwell
Migwell

Reputation: 20127

Credit to vivek for giving me a method to work out the problem.

Basically I fundamentally didn't understand how php worked. The code for sending the POST response was halfway down the page, so PHP was sending back the entire page along with any extra json I had encoded, and then JQuery attempted to parse this html page as json, failed, and then didn't run the success function because it never succeeded in its request. Read this answer for some more insight

The obvious solutions are:

  1. Make a new page for the response
  2. Put the php at the top of the page.

I ended up going with option #2 for simplicity's sake.

Thanks everyone!

Upvotes: 0

vivek
vivek

Reputation: 329

For knowing where the ajax call is done or faced a error

 $(function()
 {
 $.post('planner.php', {"want": "keys"},function(){
  alert( "success" );
 })
 .done(function(){
    alert("second success");
  })
 .error(function(){
    alert("error");
  });
});

link : http://api.jquery.com/jquery.post/

Upvotes: 2

Agha Umair Ahmed
Agha Umair Ahmed

Reputation: 1020

you can use like that it may be your sucess function not calling

var data = 'want=keys';
$.post(
  'planner.php',
  data
).success(function(resp){
   json = $.parseJSON(resp);
   alert(json);
});

Upvotes: 0

Filip G&#243;rny
Filip G&#243;rny

Reputation: 1769

This is probably be cause there is no such thing like $.alert(), use simple alert() instead.

Also your success_func is declared below the ajax call, move it up before $.post();

EDIT:

as the function is declared, there is no need to type it before executing.

Upvotes: 0

Related Questions