K
K
KRHD2018-03-05 17:13:21
JavaScript
KRHD, 2018-03-05 17:13:21

How to find out if there is a certain variable in the json response or not without js errors?

In general, there is a script

$('form').submit(function(e){
        e.preventDefault();
        $form = $(this);
        $form.find('.notice').html('');
        $button = $form.find('button');
        $button.addClass('loading');
        $action = $form.attr('action');
        $.ajax({
          'url': $action,
          'type': "POST", 
          'dataType': "json", 
          'data': $form.serialize(), 
          'success': function(json) {
                                                  if(json.addons.redirect != null){
                                                   alert('yes');
                                                   }
            $button.removeClass('loading');
            $form.find('.notice').html('<div class='+json.response+'>'+json.msg+'</div>');
          }
        });
      });

The response generates the given php code
function ResponseCreate($response, $msg, $data){ 
    $datas = array(
      "response" => $response,
      "msg" => $msg,
      "addons" => $data,
    );
    
    $data_string = json_encode($datas);  
    exit($data_string);	
  }

And it turns out that the response may or may not be redirect , and how to check it without js errors, otherwise js stops when it does not see this variable

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bhudh, 2018-03-05
@KRHD

Wrap the redirect check in a try|catch and decide what to do in the catch block.
Just specify what format your json is in. Or rather, what type.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question