Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax post - how to get data back?

Tags:

jquery

php

I have a profile page that contains a series of images. I want to use jQuery to allow the user to delete an image from the server and have the page update without reloading the entire page. When it's successful, it will remove the image's containing div from the page. My delete function is PHP; fairly simple:

delete.php

<?php 
if (isset($_POST['id'])) {     
    if (unlink($_POST['id'])) { 
        echo "success";
    } 
    else { 
        echo "failure"; 
    } 
} 
?>

(There's already user authentication in place just to get them to the page that calls delete.php.)

Here's the html of one displayed image - there can be up to 5 of these chunks one after another:

<div class="box">
  <img src="uploads/t_10DOT_22C_1111_1300370702_3.jpg" /> 
  <h5><a rel="external" href="uploads/10DOT_22C_1111_1300370702_3.jpg">See full version</a></h5> 
  <a href="#" id="10DOT_22C_1111_1300370702_3.jpg" class="delete" onclick="return ConfirmDelete();" >x</a>
  <div class="clear"></div> 
</div>

My jQuery so far looks like this:

$(document).ready(function() {
$('#load').hide();
});

$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;

$.ajax({
   type: "POST",
   url: "delete.php",
   data: string,
   cache: false,
   success: function(data){
    commentContainer.slideUp('slow', function() {$(this).remove();});
    $('#load').fadeOut();
  }

 });

return false;
    });
});

The part I'm concerned with is the ajax post. How does the success part actually work? What do I need to do in my php file so that ajax knows whether the delete was a success or failure?

like image 617
EmmyS Avatar asked Mar 17 '11 15:03

EmmyS


People also ask

Can Ajax return data?

You can't return anything from a function that is asynchronous. What you can return is a promise. I explained how promises work in jQuery in my answers to those questions: JavaScript function that returns AJAX call data.

What is post back in Ajax?

Using ajax we can send and receive data from server with our reloading the page(postback). So the page will nor refresh if a server call encounters.

Which object can be used to retrieve data in Ajax?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.


2 Answers

Once an ajax post request has finished executing the file you sent the request to, if there was no error, the code you add in the "success" section is executed, in this case

success: function(data){
  /*The code you need*/
});

The previous part if where the code is executed, the "data" variable contains anything you return from your php file, it can be data, it can be a simple "true" or "false", you choose what to send to let your jQuery know if it was successful.

Hope this helps a bit.

Edit Note:

function(applyData){
  if ( applyData.toString() == 'invalid' ){
    $('#pollError').html('Global styles cannot be modified.');
    $('#pollNotice').html('');
  }
  else{
    $('#pollNotice').html('The changes to the style have been applied.');
  }
});

The previous example is a live example of what you can do inside the function in the "success" event. There I handle an "invalid" status and otherwise it's successful, after that I refresh a couple DIVs in case of invalid or update a single DIV in case of success.

This is the php that executes:

if ( !$db->isGlobal($id_css)){
  $data['id_poll'] = $id_poll;
  $data['id_css'] = $id_css;
  $data['css'] = $css;
  $db->applyCssChanges($data);
}
else{
  echo 'invalid';
}
like image 91
Ozmah Avatar answered Oct 12 '22 23:10

Ozmah


You've two obvious options I can think of:

  1. Your returned text should appear in the data parameter supplied to your success callback function - however you'll probably also need to make sure it's in a format compatible with the MIME Content-Type returned by your PHP, or jQuery might complain that it can't parse it, or:

  2. Send back a 5xx Failure type message from your PHP using the header() function if the delete didn't work. That should then trigger an AJAX error callback, which you'll need to supply.

like image 21
Alnitak Avatar answered Oct 13 '22 00:10

Alnitak