views:

289

answers:

2

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&lt;/original_image&gt;
        <large_thumbnail>http://imgur.com/cxmHMl.png&lt;/large_thumbnail&gt;
        <small_thumbnail>http://imgur.com/cxmHMs.png&lt;/small_thumbnail&gt;
        <imgur_page>http://imgur.com/cxmHM&lt;/imgur_page&gt;
        <delete_page>http://imgur.com/delete/NNy6VNpiAA&lt;/delete_page&gt;
</rsp>

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

A: 

It could be that you have not set the header in the php script - this should be your first line.

header('Content-Type: text/xml');
James
+1  A: 
var docname =  $('#doc').val();

Exactly where is this in your code and when will it be evaluated?
My guess is that it's executed either when the <script> tag has been parsed or you've wrapped it in a $(document).ready() handler. Either way it get's evaluated before the user has actually typed something into the input/text control and docname will therefore be '' or even null all the time. You want the script to fetch the value not until the user has pressed the submit button.
Try it with

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

edit: Even better, make the data property an object and let jquery handle the escaping of the value.

data: {doc: $('#doc').val()}
VolkerK
i tried making this change and adding header('Content-Type: text/xml'); to my PHP script but it still doesn't work
vette982