views:

934

answers:

4

I am trying to send a php script some content to be stored in a database via ajax. I am using the jQuery framework. I would like to use a link on a page to send the information. I am having trouble writing the function that will send and receive the information, everything that I have tried is asymptotic.

EDIT The idea is that the user will click the link, and a coulumn called "show_online" (a tiny int) in a table called "listings" will update to either 1 or 0 (**a basic binary toggle!) On success, specific link that was clicked will be updated (if it sent a 1 before, it will be set as 0).

EDITThere will be 20-30 of these links on a page. I have set each containing div with a unique id ('onlineStatus'). I would rather not have a separate js function for every instance.

Any assistance is much appreciated. The essential code is below.

<script type="text/javascript"> 
    function doAjaxPostOnline( shouldPost, bizID ){
     load("ajaxPostOnline.php?b='+bizID+'&p='+shouldPost", jsonData, callbackFunction);
function callbackFunction(responseText, textStatus, XMLHttpRequest)
{
  // if you need more functionality than just replacing the contents, do it here
}

     }
    }
</script>   


<!-- the link that submits the info -->: 
<div id='onlineStatus<?php echo $b_id ?>'>
<a href='#' onclick="doAjaxPostOnline( 0, <?php echo $b_id ?> ); return false;" >Post Online</a>
</div>

ajaxPostOnline.php

<!-- ajaxPostOnline.php ... the page that the form posts to -->
<?php
    $id = mysql_real_escape_string($_GET['b']);
    $show = mysql_real_escape_string($_GET['p']);

    if( $id && ctype_digit($id) && ($show == 1 || $show == 0) ) {
     mysql_query( "UPDATE listing SET show_online = $show
     WHERE id = $id LIMIT 1" );
    }

    if($result) {
     if($show == '0'){
      $return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, <?php echo $b_id ?> ); return false;' >Post Online</a>";
     }
     if($show == '1'){
      $return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 0,  $b_id ); return false;' >Post Online</a>";
     }
     print json_encode(array("id" => $id, "return" => $return));
    }
?>
A: 

did you really mean to declare your ajax success return function as

function(html)

? .. i think maybe you mean for the param to be 'data' ?

Scott Evernden
+2  A: 

The load() function in jQuery is really cool for this sort of thing.

Here's an example. Basically, you have an outer div as a container. You call a script/service which returns html. You have a div in that html with an id that you will refer to later in the ajax call. The replacement div replaces the inner html of the container div. You pass your data as a json object as the second parameter to the load method, and you can pass a reference to a callback function as the third parameter. The callback function will receive every possible piece of information from the response (the full response text for further parsing/processing, the http status code, and the XMLHttpRequest object associated with this ajax call).

$("#id_of_some_outer_div").load("somepage.php #id_of_replacement_div", jsonData, callbackFunction);

function callbackFunction(responseText, textStatus, XMLHttpRequest)
{
  // if you need more functionality than just replacing the contents, do it here
}

so, in your case you're talking about replacing links. Put the original link inside of a div on both sides of the operation.

Here's the link to the jQuery api doc for load():

load

EDIT:

In response to your comment about doing multiple replacements in one pass:

You can have the callback function do all the work for you.

  1. Add a unique css class to all divs that need replacing. This will allow you to select all of them in one shot. Remember that html elements can have more than one css class (that's what the "c" in css means). So, they'd all be <div id="[some unique id]" class="replace_me"... Then, if you have a variable set to $("div.replace_me"), this will be a collection of all divs with the replace_me style.
  2. Whatever elements that come from the ajax call (whether they're another div container or just a single "a" element) should have a unique id similar to the container they're to be inserted into. For example, div_replace1 would be the id of a container and div_replace1_insert would be the id of the element to be inserted
  3. Inside the callback function, iterate over the replacements using $("div.replace_me").each(function(){ ...
  4. Inside each iteration the "this" keyword refers to the current item. You can grab the id of this item, have a variable like var replacement_id = this.id + "_insert"; (as in the example above) which is now the unique id of the element you'd like to insert. $("#" + replacement_id) will now give you a reference to the element you want to insert. You can do the insertion something like this: this.html( $("#" + replacement_id) );

You may have to edit the code above (it's not tested), but this would be the general idea. You can use naming conventions to relate elements in the ajax return data to elements on the page, iterate the elements on the page with "each", and replace them with this.html()

Rich
This is close to what I am looking for, however, there will be 20-30 of these links on a page. I have set each containing div with a unique id ('onlineStatus<?php echo $b_id ?>'). I would rather not have a separate js function for every instance. How would I go about using the load() in a function?
superUntitled
A: 

Since your php script is returning json you should set the dataType to json. Note that in your posted code sample, the success function() was outside of the $.ajax() and it needs to be inside.

 $.ajax({
   url: "ajaxPostOnline.php?b=" + bizID + "&p=" + shouldPost,
   dataType: "json",
   success: function(json){
     $("#onlineStatus" + bizID).html(json.return);
   }
 });

You might want to check out the getJSON method since it's more concise for this particular situation.

$.getJSON("ajaxPostOnline.php", {b:bizID, p:shouldPost}, function(json) {
    $("#onlineStatus" + bizID).html(json.return);
});

EDIT: Original question was edited and the provided sample changed significantly. I would still recommend the $.getJSON method.

John Wagenleitner
A: 

Unless I am mistaken, it seems you have an error mixing AJAX and server-side scripting.

That depends on whether $return is PHP parsed anywhere after assignment snippet in ajaxPostOnline.php (hardly, if it is called from AJAX!).

$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, <?php echo $b_id ?> ); return false;' >Post Online</a>";

Surely this should be:

$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, ".$id." ); return false;' >Post Online</a>";
Gnudiff