Using jQuery to parse XML returned from PHP script (imgur.com API)

Posted by vette982 on Stack Overflow See other posts from Stack Overflow or by vette982
Published on 2010-04-11T10:13:17Z Indexed on 2010/04/11 10:23 UTC
Read the original article Hit count: 527

Filed under:
|
|
|
|

Here's my jQuery:

var docname =  $('#doc').val();

function  parseXml(xml)
{
  $(xml).find("rsp").each(function()
  {
    alert("success");
  });
}

$('#submit').click(function() {
  $.ajax({
    type: "GET",
    url: "img_upload.php",
    data: "doc=" + docname,
    dataType: "xml",
    success: parseXml
  });
  return false;
});

Note that #doc is the id of a form text input box and #submit is the submit button's id. If successful, I'd like a simple "success" javascript popup to appear.

Here's *img_upload.php* with my API key omitted:

<?php
    $filename = $_GET["doc"];
    $handle = fopen($filename, "r");
    $data = fread($handle, filesize($filename));

    // $data is file data
    $pvars   = array('image' => base64_encode($data), 'key' => <MY API KEY>);
    $timeout = 30;
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, 'http://imgur.com/api/upload.xml');
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);

    $xml = curl_exec($curl);

    curl_close ($curl);
?>

When directly accessed with a GET argument for "doc", img_upload.php file returns the following XML format:

<?xml version="1.0" encoding="utf-8"?>
<rsp stat="ok">
        <image_hash>cxmHM</image_hash>
        <delete_hash>NNy6VNpiAA</delete_hash>
        <original_image>http://imgur.com/cxmHM.png</original_image>
        <large_thumbnail>http://imgur.com/cxmHMl.png</large_thumbnail>
        <small_thumbnail>http://imgur.com/cxmHMs.png</small_thumbnail>
        <imgur_page>http://imgur.com/cxmHM</imgur_page>
        <delete_page>http://imgur.com/delete/NNy6VNpiAA</delete_page>
</rsp>

What's the problem here? Here's the Imgur API page for reference.

© Stack Overflow or respective owner

Related posts about php

Related posts about jQuery