Hi,

I have ajax call in my script which calls php file. I need to extract its response in two parts to add it on my page to different components each.

For example, say I have these two echo statements in my php:

echo "<option> add to list1 </option>";
echo "<option> add to list2 </option>";

Now, this output has to be added to seperate 'select' tags using jquery. How do I extract this separately from ajax response object?

In my script, say I have this:

$.ajax({
    type:"post",
    url:"myfirst.php",
    success:function(response){
        //insert first option into first select tag and second option into second select tag on my page here
    }
    });

Is there a trick to do this?

Thanks,
VC

Dani AI

Generated

Nice thread. +1 to @diafol for pushing JSON. Two quick points that should fix ’s Chrome error and make this robust long-term:

  • Do not call JSON.parse yourself when you tell jQuery to expect JSON; it already parses. The Chrome "Unexpected token <" means your PHP endpoint is returning HTML (often a notice, redirect, or BOM) instead of valid JSON. That is why Firefox seemed to work but Chrome did not. Also, ’s delimiter idea works in a pinch, but it is brittle compared to structured JSON.

On the server, return structured data and set the content type. Make sure nothing else is echoed (no stray whitespace, BOM, or HTML), then exit.

<?php
// myfirst.php
header('Content-Type: application/json; charset=UTF-8');

$payload = [
    'list1' => [
        ['value' => 'l1a', 'label' => 'add to list1'],
        // more...
    ],
    'list2' => [
        ['value' => 'l2a', 'label' => 'add to list2'],
        // more...
    ],
];

echo json_encode($payload);
exit;

On the client, let jQuery parse the JSON and build options via DOM methods (safer than injecting HTML). Include basic failure logging so you can see the raw response if PHP ever emits markup.

$.getJSON('myfirst.php')
  .done(function(data){
    var $a = $('#firstSelect').empty();
    var $b = $('#secondSelect').empty();

    data.list1.forEach(function(opt){ $a.append(new Option(opt.label, opt.value)); });
    data.list2.forEach(function(opt){ $b.append(new Option(opt.label, opt.value)); });
  })
  .fail(function(xhr){
    console.error('JSON request failed. Status:', xhr.status);
    console.error('Raw response:', xhr.responseText); // if this starts with "<", PHP sent HTML
  });

If the error persists, open DevTools Network tab and check the Response. Remove any PHP notices, ensure files are saved as UTF-8 without BOM, and confirm your script is not being redirected to an HTML page (auth screens are a common culprit).

Recommended Answers

All 6 Replies

Check this Exg

Your index file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form -  validate - Exg</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form  method="post" name="myForm">

    <select id="sltOption" name="sltOption">
    </select>
</form>

<script type="text/javascript">
$(function (){
    $.ajax({
    type:"post",
    url:"phpfile.php",
    success:function(response){
        $('#sltOption').html(response);
    }
    });

})
</script>
</body>
</html>

&
your php file:

<?php
echo "<option> add to list1 </option>";
echo "<option> add to list2 </option>";
?>

i have a solution like as follows

  1. make your results(list1_values,list2_values ) which are coming from myfirst.php as
    follows

i mean append those two list options values any of the sign like "$" (or) "," like any other charecter as follows in myfirst.php

results = list1_values."&".list2_values;
echo results;
  1. spilt the response coming to the jquery by using the charecter(whatever you used in myfirst.php )

  2. after this you will get the result whatever you want and then place the results in different <select> tag values as you need by using jquery

i hope you understand the solution

let me know if you have any doubts in my clarification

Member Avatar for Member #120589

I'd use json:

$.ajax
({
    type: "POST",
    url: 'myfirst.php',
    dataType: 'json',
    success: function (response) {
        $('#firstSelect').html(response.first);
        $('#secondSelect').html(response.second);
    }
})

Your php could be:

$array = array('first' => "<option> add to list1 </option>", 'second' => "<option> add to list2 </option>");

echo json_encode($array);

Thanks everyone for your suggestions.

Diafol, that's good method. Thanks. Its working.

Thanks,
VC

Diafol, I had to use JSON.parse(response) in success function of ajax call to get the right output. It works if Firefox. But in Chrome, it shows an error for line 'JSON.parse(response)'.
Error thrown is:' Uncaught syntax error: unexpected token <'

Is there any reason that you know why this is happening for chrome?

Thanks,
VC

Member Avatar for Member #120589

If you could post your js code and the array from php, e.g.

$array = array('first' => "<option> add to list1 </option>", 'second' => "<option> add to list2 </option>");

I'll see if I can reproduce it. Make sure that there's no other output in the php file - no html or similar.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.