Hi,
I have the below code and it works fine except the part where I need to access data.Picture. I know its a syntax error but I can't seem to understand what.

$.post("rpc.php",arr, function(data)
{
$('#dorants').append(data);
$('#dorants').append(data.Picture);

Like always appreciate the help :)

Dani AI

Generated

Short answer: data.Picture only works if the AJAX callback actually receives a JavaScript object (parsed JSON). In this thread was getting an HTML/text response from rpc.php, so data was a string and data.Picture was undefined. @developer's approach of parsing the returned HTML and extracting the element you need is the right fix when the server returns HTML.

How to decide and fix it

  • Inspect the response in the browser Network panel: look at the response body and the Content-Type header. If it starts with { or [ and the header is application/json, treat it as JSON. If it is HTML, parse it as DOM.
  • If you want data.Picture to work, have the server return valid JSON (and set Content-Type: application/json). Ask jQuery to expect JSON (see jQuery.ajax dataType: 'json') so jQuery hands your callback a real object rather than a text string.
  • If you must work with HTML, parse the response into a detached container and use DOM queries to pull out the piece you need (this is what @developer suggested). That avoids appending and re-parsing the whole page.

Troubleshooting tips and cautions

  • Use console.log(typeof data, data) and console.dir(data) to see what you actually received.
  • Common problems: wrong Content-Type, invalid JSON (or leading BOM/whitespace), or cross-origin/CORS issues preventing proper parsing.
  • Don’t inject untrusted HTML directly; prefer returning structured data (JSON) and building DOM elements safely on the client to avoid XSS.

References: jQuery AJAX options and dataType behavior are documented in the jQuery.ajax API (https://api.jquery.com/jQuery.ajax/). If manual parsing is needed, see JSON.parse on MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).

Recommended Answers

All 4 Replies

Try with this while appending the response data to the div,don't know whether that works..

$('#dorants').html(data);

HI,
I was hoping I could access the variable in data by something like data.Picture ?

$('#dorants').append(data.Picture);

Ok..I think you can do it in jQuery.Suppose want to access class test which is the response html.Put a div outside it on the page(rpc.php)like ..

<div><div class="test"/> </div>

With tha Ajax response data
ie,

$.post("rpc.php",arr, function(data)
{
//We won't get html from 'data' because it is variable, so
   var content = $(data).find('.test').html();
   $('#dorants').append(content);

@developer thank you it worked !!

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.