-2

I have two problems here, 1st the code below won't work, anybody could tell me what am i missing? 2nd, i want to return the value from php to success function and then that value also will be returned to the parent function...

function myFunc(e){
    $.ajax({
        type: "post",
        url: "path/myPhp.php",
        data: "val="+e,
        dataType: "php",
        success: function(result){
            return result; //i want this result to be returned to parent function myFunc(e)
        },
        error: function(e){
            alert('Error: ' + e);

        }
    }); 

}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Tinker
  • 299
  • 2
  • 4
  • 16

3 Answers3

2

There is no data type named php for jquery ajax. legal data type is as below:

xml
html
script
json
jsonp
text

Do you mean "json" data type?

bakoyaro
  • 2,550
  • 3
  • 36
  • 63
Prometheus
  • 36
  • 2
0

1) You have an invalid value in 'dataType'. Valid values are: xml, json, script, or html.

2) As I see it, you want the ajax call to behave in a synchronous way.

Use 'async: false' to accomplish that. Try:

function myFunc(e){    
    var value = "";
    $.ajax({
        type: "post",
        url: "path/myPhp.php",
        data: "val="+e,
        dataType: "json",
        success: function(result){
            value = result;
        },
        error: function(e){
            alert('Error: ' + e);
        },
        async: false // set synchronous
    }); 
    alert(value); // use value
} 

Or

$.ajaxSetup({async:false});

before issuing $.ajax() call.

A discussion about using synchronous ajax can be found here How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Community
  • 1
  • 1
Alvis
  • 3,543
  • 5
  • 36
  • 41
0

If you want your response to return as function return value, then you need to make it ajax synchronize and later ajax unsynchronize after ajax finish

If your return response is not array ,then I think this will work.

    function myFunc(e){
    var returnValue = '';
    $.ajaxSetup({async:false}); // synchronize
        $.ajax({
            type: "post",
            url: "path/myPhp.php",
            data: "val="+e,
            success: function(result){
                returnValue = result; 
            },
            error: function(e){
                alert('Error: ' + e);

            }
        }); 
    $.ajaxSetup({async:true});//  Unsynchronize
    return returnValue;

    }
bakoyaro
  • 2,550
  • 3
  • 36
  • 63
Justin John
  • 9,223
  • 14
  • 70
  • 129