Toniq
Toniq

Reputation: 5006

jQuery Ajax return multiple data

I am using jQuery AJAX to return a string from PHP which consists of some JavaScript, PHP and HTML.

I can successfully do this with the following code:

header("Content-Type: text/html");
echo $content;

$.ajax({
    type: 'POST',
    url: url,
    data: data,
}).done(function(result) {

}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(jqXHR, textStatus, errorThrown);
});

The problem I have now is that I want to return some other simple values along this string as well.

But if I use json_encode to send an array of these values, it will break my string and won't be successful.

How could I send one value as string (without json_encode) and some other values with json_encode? (so I don't json_encode my string)

EDIT1:

Here is formatting issue 1:

return 'autoOpenPopup: '.!empty($options["autoOpenPopup"]) ? $this->int_to_bool($options["autoOpenPopup"]) : $this->int_to_bool(false) . PHP_EOL .';

2:

return '.!isset($options["popupInit"]) ?

                $playerId.' = jQuery("#'.$wrapperId.'").hap(settings);

            ':'

                if(hasLocalStorage){

                    if(!localStorage.getItem("hap_popup_fixed")){
                        '.$playerId.' = jQuery("#'.$wrapperId.'").hap(settings);
                    }
                }else{
                    '.$playerId.' = jQuery("#'.$wrapperId.'").hap(settings);  
                }

Upvotes: 0

Views: 7481

Answers (2)

Anatoliy  Gusarov
Anatoliy Gusarov

Reputation: 808

header('Content-type: application/json');
echo json_encode($data, true);

and in your $.ajax({...dataType:'json'});

Upvotes: 0

Sam Battat
Sam Battat

Reputation: 5745

The best way is to json_encode your data and string together;

$data = array('some', 'array', 'elements');

$string = 'my string';

$data2 = array('more', 'data');

Then you combine all of them in one array:

$result  = array();
$result['data1'] = $data;
$result['string'] = $string;
$result['data2'] = $data2;

Finally json_encode the array:

echo json_encode($result); 

Then you read the result in JS:

$.ajax({
    type: 'POST',
    url: url,
    data: data,
}).done(function(result) {
  var jsonResult = $.parseJSON
  var data1 = result.data;
  var data2 = jsonResult.data2;
  var str = jsonResult.string;

}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(jqXHR, textStatus, errorThrown);
});

Upvotes: 4

Related Questions