2

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?

1
  • Please show us what myfunction() does. Commented Mar 28, 2017 at 16:24

2 Answers 2

2

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){
}});
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry my mistake. Thank you!
0

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.

2 Comments

Incorrect that ajax uses JSON. It can use json, but the OP has specified the the ajax call is expecting HTML back.
You're right. my mistake. Either way I think we need to see what myFunction() actually does to better help here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.