R
R
Rashon Zhax2018-07-09 01:11:26
PHP
Rashon Zhax, 2018-07-09 01:11:26

Why doesn't AJAX JQUERY JSON PHP code work?

When alert(result) produces everything correctly, when alert(result.sname) produces - undefined
What's wrong?

Here is the code with Ajax

$('#editprofile').submit(function(event){
  event.preventDefault();
  $.ajax({
    type: $(this).attr('method'),
                url: $(this).attr('action'),
                data: new FormData(this),
                contentType: false,cache: false,processData: false,
    success: function(result) {
      alert(result.sname);
    }
  });
});


Here is PHP:
if(!empty($data['changesname'])){
  $errors = array();
  if (trim($data['changesname']) == '') $errors[] = 'Введите фамилию';			
  if(strlen($data['changesname']) > 50) $errors[] = 'Фамилия слишком большая';		
  if(strlen($data['changesname']) <1) $errors[] = 'Фамилия слишком маленькая';
  if(empty($errors)){
          $user = R::load('users', $_SESSION['id']);
    $user->sname = $data['changesname']; 
    R::store($user);
    echo json_encode(array('sname'=>$data[changesname]));
  }			
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Proskurin, 2018-07-09
@RashonS

Well, there is JSON, parse it and contact.

success: function(result) {
      var obj = JSON.parse(result);
      alert(obj.sname);
}

A
Alex-1917, 2018-07-09
@alex-1917

working php piece:

echo json_encode(array('img' => $img, 'img_title' => $img_title));
exit;

working js piece:
jQuery.ajax({
  type: "POST",
  url: "/send.php",
  data: arrr,
  success: function(data){
    var result = jQuery.parseJSON( data );
    jQuery('.kit_box img').attr('src', result.img);
    jQuery('.kit_box img').attr('title', result.img_title);
  }
});

N
Nikolay, 2018-07-09
@iNickolay

Be careful, or use the IDE:
Well, parse JSON, as Vladimir Proskurin already mentioned .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question