How can I return object values the corect way to do it

62 Views Asked by At

I'm trying to return a global variable and set an object in an array.

Could anyone explain what I am doing wrong to retrieve the global variable outPutArray? It become undefined when I try to return it.

var outPutArray = {};
var goAjax = function(data, filePath) {
  data = $(this).serialize() + "&" + $.param(data);
  $.ajax({
    type: "POST",
    dataType: "json",
    url: filePath, //Relative or absolute path to response.php file
    data: data,
    success: function(data) {
      for (x in data) {
        outPutArray[x] = data[x];
      }
      //logs the the wanted value
      console.log('inside ' + outPutArray['json']);
    }
  });
};

goAjax.prototype.getValue = function() {
  console.log('outside ' + outPutArray['json']);
  //logs undefined ??
};

2

There are 2 best solutions below

0
On BEST ANSWER

First I would like to thank every one who tried to help me .The answer is to use a parameter that would work as an interface in java to fire a function inside another function or a method to be fired inside other method .

 /**
   *This is a constructor of javascript firing a server side PHP script.
   * 
 * @param {Object} filePath PHP file path
   */
 var AjsToPHP = function(filePath){
 this.filePath = filePath;
   };
      
       
 /**
  * 
  * Firing server side PHP script and return respond as an array.
 * @param {Object} data Input an array of object to go as POST command.
 * @param {Object} response An interface function to return the respond value.
  */
  AjsToPHP.prototype.PHP_PROCESS_RETURN = function(data,response){
    var PHP_RETURNS= {}; 
    data = $(this).serialize() + "&" + $.param(data);

  $.ajax({
      type: "POST",
      dataType: "json",
      url: this.filePath, //Relative or absolute path to response.php file
      data: data,
      success: function(data) {
      for (x in data) {
       PHP_RETURNS[x] = data[x];
 
        }
          response(PHP_RETURNS);

    
      }
    });
  };



/**
 * 
 * Firing server side PHP script and return respond OK if it success.
 * @param {Object} data Input an array of object to go as POST command.
 * @param {Object} response An interface function to return the respond value.
 */
 AjsToPHP.prototype.PHP_PROCESS = function(data,response){
    var PHP_RETURNS= ""; 
    data = $(this).serialize() + "&" + $.param(data);

  $.ajax({
      type: "POST",
      dataType: "json",
      url: this.filePath, //Relative or absolute path to response.php file
      data: data,
      success: function(data) {     
       PHP_RETURNS= "ok";     
          response(PHP_RETURNS);

      }
    });
 };
   

An example

<script src="jsToPHP.js"></script>  
<script src="js/jquery-1.8.2.min.js"></script>
$("document").ready(function(){


        var data = {
      "action": "test",
      "Name" :"abdulla"
        };



var obj = new AjsToPHP("response.php");

obj.PHP_PROCESS_RETURN(data,function(PHP_RESPONE){ 
 alert('inside '+PHP_RESPONE['json']);
});


obj.PHP_PROCESS(data,function(PHP_RESPONE){
 
 alert(PHP_RESPONE);
 
 
});

The response.php script

<?php



function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}



if (is_ajax()) {
    
       
  if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
    $action = $_POST["action"];
  
    switch($action) { //This is how we are able to create different function according to different function call
      case "test": test_function(); break;
    }
  }
  
  
  
  
}



function test_function(){
 

 //this a correct way of creating an associative array.
  $name = $_POST["Name"];
  $return["name"] = $name;
  $return["favorite_beverage"] = "Coke";
  $return["favorite_restaurant"] = "McDonald's";  
  $return["json"] = json_encode($return); 
  
  //return data to javascript
  echo json_encode($return); 
}













?>

0
On

It's undefined when you try to return it because AJAX is asynchronous.

See this questions, and this question, or Google "return AJAX response" or something similar.

It boils down to the fact that asynchronous calls happen outside of the normal event loops and execution, so when you set a global variable with an asynchronous response, there's no way for JavaScript to "know" when it'll get there.