user2293004
user2293004

Reputation: 55

jQuery AJAX datatype html using

Hi I'm using jquery ajax function with php. Here is the my problem; Firstly I'm using datatype:"html" my problem is php variables not returning.

js

$.ajax({
type: "POST",
dataType: "html",
url: ajaxurl,
data:dataajax,
success:function(data) {
    var $data = $(data);
    $(".list").append($data);
},
error : function(jqXHR, textStatus, errorThrown){
}});

php

echo "<div>".$_POST['value']."</div>";

if I use like this it's working but when I remove the html tags ajax return nothing.

broken php

echo myfunction($_POST['value']);
echo $_POST['value'];

How can I fix this or can I use return $output with jquery ajax?

Upvotes: 2

Views: 9036

Answers (2)

Adam Copley
Adam Copley

Reputation: 1495

The problem is with your success callback function.

data is a html string, and as such you don't need to wrap it in jquery.

Use this.

$.ajax({
type: "POST",
dataType: "html",
url: ajaxurl,
data:dataajax,
success:function(data) {

    $(".list").append(data);
},
error : function(jqXHR, textStatus, errorThrown){
}});

Upvotes: 2

MichaelBadgett
MichaelBadgett

Reputation: 51

Ajax uses JSON data for your request and response. what you are going to want to do is return a JSON variable so that the javascript response function can access elements properly.

Luckily php is designed to do just that thing.

$ajaxData = $_POST['value'];
echo json_encode(array('response' => $ajaxData));

what are you actually trying to do with this data? if all you need to do is wrap some html in a div you can use functions like wrap() in javascript and you wont actually have to send an ajax to the server.

Either way you should really consider your data needs and try to send a json object in the ajax request so that there are actual variables to send. html markup is probably not going to be useful for the php code.

Upvotes: 0

Related Questions