Yamona
Yamona

Reputation: 1140

Ajax store response json in variables

The response of success ajax call is in the form of json like this one:

{"prize_name":"Keys 4","prize_image":"http:\/\/localhost\/web-game-w\/wp-content\/uploads\/2017\/09\/4rare.jpg"}

How I can store "prize_name" & "prize_image" in variables for later use?

Here is the ajax code:

$("#ajax").click(function(e){
    e.preventDefault();
    var data = {
        'action': 'getprize_data',
        dataType: "json", 
        async: false
    };
    $.post(ajaxurl, data, function(response) {
        console.log(response);
        // Store vars 
    });
});

Also I have an issue. This response.prize_name will return error response.prize_name is undefined.

Upvotes: 0

Views: 1083

Answers (2)

Gardezi
Gardezi

Reputation: 2842

declare those variables without using var before the ajax call starts and assign the values to those variables in the success function

    prize_name = prize_image = ""; 
    $("#ajax").click(function(e){
        e.preventDefault();


        $.ajax({ 
          type: "POST", 
          url: ajaxurl, // give url over here
          data: {action: 'getprize_data'}, 
          dataType: 'json', 
          async: false // always avoid false if you can
          success: function(response) { 
            console.log(response);
            response = JSON.parse(reponse);
            // Store vars 
            // assign the values over here 
            // maybe you will need to decode the json 
            // if you are encoding it so use JSON.parse
            // for decoding the json
          }, 

      });

    });

Now the reason why I'm saying to declare variable without using var is because

If you don't use var , the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches.

Upvotes: 1

gaetanoM
gaetanoM

Reputation: 42054

Your post call is wrong. I'd suggest to avoid async to false. But, if you need at all cost such a behavious you can rewrite your post as:

$.ajax({
   type: "POST",
   url: ajaxurl,
   data: {action: 'getprize_data'},
   success: function(response) {
             ......
            },
   dataType: 'json',
   async: false
 });

Instead to create global variables you can take advantage of data attributes.

You can store the values in this way:

$('#ajax').data('prizeName', response.prize_name);

And, in future, when you need such a value you can simply get the value with:

$('#ajax').data('prizeName');

Remember that ajax is asynchronous so the value will be available only when the succes callback will be executed. Hence, I suggest to use a callback function in your ajax success function.

Upvotes: 1

Related Questions