0

Trying to write a social website where funny pics and videos are posted and people can leave and reat on other comments. So far so good and what I've coded so far works but it always fails on the first click I just don't get it. Debugging info on the browser says I get the right response from the php file but it says the function isn't defined.

A temporary fix is for me to call the function once and have it do nothing but it doesn't work when I call use this them fix for my other php scripts

var postresponse;
var initpost=post('findpics.php'); //fails 1st click if i remove this
function post(php,vars){
    $.post(php,vars,function(data){
        postresponse=data;
        })
    return postresponse;
} 

$uploadpic.click(function(){
    var pics_array=post('findpics.php').split(',');
    $pics.empty();
    $.each(pics_array, function(val,text) {
        $pics.append( $('<option></option>').val(text).html(text) )});
    $picbox1.attr('src','/contentuploads/'+$('#pics option:selected').text());
    $dgbox.fadeIn(750);
    }
);
  • `$.post` is asynchronous, so `postresponse` isn't set immediately. So what's happening is that every time you call `post`, it's returning the result from the previous call. – Barmar Oct 14 '16 at 01:36
  • None of them are working, because they're always returning the wrong response. But the first one can't return anything, because there was no previous call to set `postresponse`. – Barmar Oct 14 '16 at 01:37
  • Thanks should I set a while loop to test when its done? – Juan Hung Wong Oct 14 '16 at 01:43
  • That won't work. Javascript is single-threaded, so the callback can't run while the loop is running. You have to do what you want in the callback function. Isn't this explained in the question I marked this as a duplicate of? – Barmar Oct 14 '16 at 01:47
  • I'm new tho this site got it.. read the duplicate thread understood rewrote the whole code and it works now thanks for ur help – Juan Hung Wong Oct 14 '16 at 02:10

0 Answers0