wdbphoto
wdbphoto

Reputation: 23

Why won't my .ajax request work?

The code I want to work:

    $.ajax({
        type: "POST",
        url: "_Source/ajap/ajap.nlSrch.php",
        data: { sndJson : jsonData },
        dataType: "json", 
        processData: false,
        success: function(html) {
      $("#srchFrm").append(html);}
    });

The code that works:

    $.ajax({
        type: "POST",
        url: "_Source/ajap/ajap.nlSrch.php",
        data: { sndJson : jsonData },
        success: function(html) {
      $("#srchFrm").append(html);}
    });

Unfortunately when I send the first one my post data looks like this "Array ()" and when I use the later I get this "Array ( [sndJson] => [\"8\",\"3\",\"6\",\"7\"] )".

I know that there has to be a simple explanation but I haven't been able to figure it out.

Help please!

Upvotes: 1

Views: 355

Answers (4)

James
James

Reputation: 10412

The following examples above are not reusable. I am a huge fan of reuseable code. here is my solution.

Software design 101:
DRY Don't repeat your self. You should wrap your code into an object. This way you can call it from anywhere.

var Request = {
    version: 1.0, //not needed but i like versioning things
    xproxy: function(type, url, data, callback, timeout, headers, contentType) 
    {
        if (!timeout || timeout <= 0) { timeout = 15000; }
        $.ajax(
        {
            url: url,
            type: type,
            data: data,
            timeout: timeout,
            contentType: contentType,
            success:function(data) 
            {
                if (callback != undefined) { callback(data); }
            },
            error:function(data) 
            {
                if (callback != undefined) { callback(data); }
            }, 
            beforeSend: function(xhr)
            {
                //headers is a list with two items
                if(headers)
                {
                    xhr.setRequestHeader('secret-key', headers[0]);
                    xhr.setRequestHeader('api-key', headers[1]);
                }
            }
        });
    }
};

Usage:

<script type="text/javascript">
var contentType = "applicaiton/json";
var url = "http://api.lastfm.com/get/data/";
var timeout = 1000*5; //five seconds
var requestType = "POST"; //GET, POST, DELETE, PUT

var header = [];
header.push("unique-guid");
header.push("23903820983");

var data = "{\"username\":\"james\"}"; //you should really deserialize this w/ a function
function callback(data)
{
   //do logic here
}
Request.xproxy(requestType, url, data, callback, timeout, header, contentType);
</script>

Upvotes: 0

Yang
Yang

Reputation: 8701

You can use shorthand $.post instead of using low level ajax class --- because you don't need to advanced handling. So, this one will be great enough.

$(document.ready(function(){    
  $("#submit_button").click(function(){     
    $.post('php_script.php', {
     // here's what you want to send  
     // important -- double quotes, 'cause It's evals as valid JSON
     "var1" : "val1"  
     "var2" : "val2"    
    }, function (respond){
       try {
           var respond = JSON.parse(respond);
        } catch(e){
           //error - respond wasn't JSON
        }
    });  
  });
});

PHP code:

<?php
/**
 * Here you can handle variable or array you got from JavaScript
 * and send back if need.
 */ 
 print_r($_POST); // var1 = val1, var2 = val2

?>

Back to your question, Why my .ajax request doesn't work? This is because JavaScript throws fatal error and stops further code execution.

You can catch and determine the error occasion, simply by adding

try {} catch(){} block to the statement you think may occur any error

Upvotes: 1

Kabilan S
Kabilan S

Reputation: 1094

Try sending your data in a query string...

$.ajax({
        type:"POST",
        url:"_Source/ajap/ajap.nlSrch.php?json="+jsonData,
        dataType:"json", 
        success: function(data) {
              $("#srchFrm").append(data);}
        error: function(xhr, ajaxOptions, thrownError)
        {alert("Error!");}
    });

Upvotes: 2

Dondi Michael Stroma
Dondi Michael Stroma

Reputation: 4800

When you specify dataType: json, jQuery will automatically evaluate the response and return a Javascript object, in this case an array. You're taking the result and adding it as html to #srchForm, so it does not make sense to convert it to a javascript object. Use dataType: html, or none at all.

http://api.jquery.com/jQuery.ajax/

Upvotes: 0

Related Questions