0

I have the following code for requesting data from a mysql database:

jquery/javascript:

ajaxGet = function (url) {
    var result = $.ajax({
        url:url,
        type:"POST",
        data:{action:'call_this'},
        dataType: 'json',
        success:function(data) {
      }
    });
    return  result;
}

php:

<?php 
if($_POST['action'] == 'call_this') {  
// call waypoint search
include ('link.php');

$sql="SELECT * FROM Waypoints"; //data in table Waypoints
$result = mysqli_query($link,$sql);

$wptdata=array();

while($line = mysqli_fetch_assoc($result)){
    $wptdata[] = $line;
};

mysqli_close($link);
echo json_encode($wptdata);
};
?>

To get the data as a javascript array, I would like to be able to say something like this:

wpdata=ajaxGet('datacall.php');

Suggestions on how to get this to work? If I put alert(data[0].name) within the success function, it comes up with the right result, so the call to the database table is definitely working. But I can't seem to figure out how to get the array out of the $.ajax call.

Thanks for any help- have been searching through other questions, and just came seem to find a solution. I would like to keep the ajaxGet function if at all possible- once I get it working, I will be able to update it so that it is flexible as to what kind of data are called from the table.

1
  • 1
    fyi, you do not need a ; after a } - and please start indenting your code! Commented Mar 9, 2014 at 17:41

1 Answer 1

3

The answer is no. You cannot do this is any way that is sane. Use callbacks/promises - that's the way to go!

function ajaxGet(url) {
    return $.ajax({
        url: url,
        type: "POST",
        data: {
            action: 'call_this'
        },
        dataType: 'json'
    });
}

ajaxGet().done(function(wpdata) {
    // use wpdata here
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.