1

I am facing this strange error in using $.post.

works

$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        alert(data);
                    $('#loader').hide();        
    });
});

The above piece of code, shows me the json array I am receiving using a php file, and also shows the title field here, and hides the loader image.

But when I alert(data.title), it shows me undefined. More over, when I add datatype 'json' to $.post,

doesn't work

$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        alert(data);
                    $('#loader').hide();        
    }, "json"); //Added datatype here.
});

This neither alerts anything nor does it hide the loader image. I also tried,

$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        jQuery.parseJSON(data);
                    alert(data.title);
                    $('#loader').hide();        
    });
});

The above one too neither alerts anything nor does it hide the loader. And then I tried this one too that did nothing.

$("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
        jQuery.parseJSON(data);  //tried without this too.
                    alert(data['title']);
                    $('#loader').hide();        
    });
});

The strangest thing is that I have previously used json as I have shown in the 2nd script(out of 4), and that works normally. My JS console too doesn't show any errors or warning. What am I doing wrong here? How do I access the title field of data?

If this helps, here is how I send the json array,

$json = array("title" => $title, "embed" => $embed, "desc" => $desc, "duration" => $duration, "date" => $date);
print_r(json_encode($json));

I would really appreciate if someone can point out the error and tell me why my scripts are failing, similar functions worked in other js file.

here is my data, that is returned by server,

{"title":"Sunn Raha Hai Na Tu Aashiqui 2 Full Song With Lyrics | Aditya Roy Kapur, Shraddha Kapoor","embed":"\r\t\t\t\t\t\r\t\t\t\t\t</param></param>\r\t\t\t\t\t</param>\r\t\t\t\t\t\r\t\t\t\t\t</embed></object>","desc":"Presenting full song \"Sun Raha Hai Na Tu\" with lyrics from movie \"Aashiqui 2\" produced by T-Series Films & Vishesh Films, starring Aditya Roy Kapur, Shraddha Kapoor in voice of Ankit Tiwari. \n\nSong: SUNN RAHA HAI\nSinger: ANKIT TIWARI\nMusic Director: ANKIT TIWARI\nAssistant Mix Engineer - MICHAEL EDWIN PILLAI\nMixed and Mastered by ERIC PILLAI (FUTURE SOUND OF BOMBAY)\nLyrics:SANDEEP NATH\nMovie: AASHIQUI 2\nProducer: BHUSHAN KUMAR KRISHAN KUAMR Producer: MUKESH BHATT
\nDirector: MOHIT SURI\nMusic Label: T-SERIES\n\nBuy from iTunes - https://itunes.apple.com/in/album/aashiqui-2-original-motion/id630590910?ls=1\n\nEnjoy & stay connected with us!! \n\nSUBSCRIBE T-Series channel for unlimited entertainment\nhttp://www.youtube.com/tseries\n\nCircle us on G+ \nhttp://www.google.com/+tseriesmusic\n\nLike us on Facebook\nhttp://www.facebook.com/tseriesmusic\n\nFollow us\nhttp://www.twitter.com/_Tseries","duration":"391","date":"2013-04-03"}

Edit

This worked suddenly.. :o

  $("#add-video").click(function(){
    var url = $("#new-video-url").val();
    $('#loader').show();
    $.post( base_url + "forms/coach/get_url.php", { url:url, base_url:base_url }, function(data){
            alert(data.desc);
            console.log(data.desc);
            $("#loader").hide();

    }, "json");
});
Optimus Prime
  • 6,817
  • 5
  • 32
  • 60
  • And what shows `console.log(data)` exactly? – u_mulder Aug 17 '13 at 18:20
  • 2
    `jQuery.parseJSON(data);` doesn't modify `data` in place. You'd have to use `data = jQuery.parseJSON(data);`. That shouldn't matter, because setting the `dataType` as "json" should automatically parse it (do what you're doing already). Also, instead of using the callback of `$.post()`, just take advantage of the methods `.done()`, `.fail()` on the result of `$.post()`. For example: `$.post("url", {}).done(function (data) { }).fail(function (_, textStatus, errorThrown) { };` – Ian Aug 17 '13 at 18:21
  • I'm pretty sure there's an error in the parsing, because your code works when you **don't** have the response parsed (meaning it's parsed as text, which has `data` being a string). That means the success callback won't execute, and instead an error callback will, which you can look at with my previous comment – Ian Aug 17 '13 at 18:23
  • I have a feeling it's because you're using `print_r` and not `echo`. Try changing that. And also set the `dataType` parameter for `$.post`, otherwise `data` will be a string – Ian Aug 17 '13 at 18:24
  • @u_mulder same thing as i told with alert. It logs data when I don't use json word or data.title anywhere. But doesn't when I use the last 3 methods in the question. – Optimus Prime Aug 17 '13 at 18:24
  • can you post your json contents? – Moazzam Khan Aug 17 '13 at 18:25
  • @Ian That didn't work, and I used print_r in the previous script too that's working and is similar to the 2nd script(out of 4 here). – Optimus Prime Aug 17 '13 at 18:26
  • @MoazzamKhan Okay i will in a while. – Optimus Prime Aug 17 '13 at 18:26
  • @OptimusPrime Ahh okay, I thought maybe there would be extra whitespace or something that would throw off the parser. Either way, you **need** to use the `.fail()` method, because that's clearly what's being called (not the success `.done()` method) and you can find out more and debug from there – Ian Aug 17 '13 at 18:27
  • @Ian yes the problem is while parsing the data. Or it works well. I will add the data contents, may be that may help. – Optimus Prime Aug 17 '13 at 18:27
  • give me the get_url.php code. I want to know what parameter you have sendint to your ajax page – Chinmay235 Aug 17 '13 at 18:32
  • @Ian I have added the contents of data. Now am trying using .done() and .fail(). – Optimus Prime Aug 17 '13 at 18:32
  • @ChinmaySahu I have just now added the data returned. I hope now php file is not needed. – Optimus Prime Aug 17 '13 at 18:33
  • Go to http://jsonlint.com and copy/paste your JSON; I get an error on validation, which means the parser won't work. It looks like some text inside of the `desc` value, because if I remove that text, it validates fine – Ian Aug 17 '13 at 18:33
  • Actually, that "error" is talking about the line break in the middle of the `desc` (right before `\nDirector:`), which I'm not sure why is there. It should be a `\n` like the others. – Ian Aug 17 '13 at 18:41
  • @Ian Yes I notice that too. But I am using youtube api's to get these info. What can I do to make desc valid. Or so that json can parse it. – Optimus Prime Aug 17 '13 at 18:41
  • @Ian Now something stranger happened, the code I just appended to question, worked :o Now why? for the same video, for same desc, it works. – Optimus Prime Aug 17 '13 at 18:46
  • Two things - are you sure you aren't `echo`ing, or `print_r`ing anything else in your PHP script? Although it seems straightforward, you might want to post that code. Also, what happens if you **don't** include the `desc` key/value in the encoded array? Does the error still occur? – Ian Aug 17 '13 at 18:48
  • Yes, these is the only thing I am echoing. I have one if else. Other things I echo are in if condition, this is in else condition. @Ian – Optimus Prime Aug 17 '13 at 18:50
  • @OptimusPrime Okay, and what about my other question? If you don't include the `desc` key/value? – Ian Aug 17 '13 at 18:52
  • I think the problem was with single `\ `, when the string is getting parsed it should have `\\ ` double slashes – Moazzam Khan Aug 17 '13 at 18:54
  • And I am using youtube api's, so if youtube can send me the data as json array, why can't i use it as json array? – Optimus Prime Aug 17 '13 at 19:07
  • You might read http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call to get a greater appreciation of ajax. – Paul Aug 18 '13 at 03:43

3 Answers3

0

In comments, you mention that this AJAX corresponds to a YouTube API.

YouTube's blog announced in 2012 that they would support CORS, which uses server-side header flags that compatible browsers interpret as permitting requests that would otherwise be prohibited by browser security Same-Origin-Policy.

Assuming, as you say, the first example worked, the first issue was "Why did (a subsequent) alert(data.title) fail? (my edit) ". If you type alert(data.title) in the console, it will fail because the scope of data is the callback function where it is defined as a parameter, and in the global scope data is undefined. If you try to pass data back to the global scope somehow, it can still be undefined because $.post returns immediately, before the data has been fetched, and merely queues a request and sets the callback function you supply to handle the reply.

The second example, which explicitly sets the $.post dataType parameter to 'json', may fail with CORS based API because the mime types for json are not allowed to be sent up to the server as Content-Type: for a simple CORS request, and $.post will as far as I know only do simple requests without preflight. $.ajax can possibly do the more complex requests if correctly applied.

The work around to keep using $.post is not to use json as the expected data type, send requests up as form data, the server may send you back json anyway if that is what the API says will happen, which can be verified while testing the code.

From https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

Simple requests

A simple cross-site request is one that:

Only uses GET, HEAD or POST.

If POST is used to send data to the server, the Content-Type of the data sent to the server with the HTTP POST request is one of application/x-www-form-urlencoded, multipart/form-data, or text/plain.

Notice that application/json did not make the list of what Content-Type is permissible in a simple CORS request.

See also A CORS POST request works from plain javascript, but why not with jQuery?

Community
  • 1
  • 1
Paul
  • 26,170
  • 12
  • 85
  • 119
-1

Use ajax as

$.ajax({
url:url,
type:'post',
dataType:'json',
success:callback
})

With this type you can set lots of parameter in low level. With datatype attribute jQuery parses JSON and send data as callback function.

Mironline
  • 2,755
  • 7
  • 35
  • 61
-1

I think you have to replace all single \ with double '\' to feed it to JSON.parse.

Moazzam Khan
  • 3,130
  • 2
  • 20
  • 35