L
L
Leshiy666132014-07-31 01:23:26
PHP
Leshiy66613, 2014-07-31 01:23:26

How to get json data back using ajax?

I'm learning web programming, making a simple easy photo uploader. I took part of the code from the example.
here is the function that sends the data

$.ajax({
url:'add_avatar1.php',
type:'POST',
  data: data,
    cache: false,
    contentType: false,
    processData: false,
    dataType: "json",
   beforeSend: function() {
        $('.loading').html('<img src="css/loading.gif" alt="загрузка">');
    },
complete:function(data){
 $('.loading').html('');

var obj = $.parseJSON(data); // что тут надо написать и как чтоб получить обратно данные из пхп обработчика
alert(obj.name); 

console.log(data);
}
});


Handler
$x="Переменная";
  $arr=array('Аватар успешно загружен', $x);
    
    echo json_encode($arr);


It was written in the example how to pass several variables or something else from the handler using JSON. Only here How to process it is not written. Can anyone suggest?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
podvzbzdnul, 2014-07-31
@Leshiy66613

On server:

$x = "123";
$arr=array(
    "result" => 'success',
    "var" => $x
);

header("Content-type: application/json; charset=utf-8");
echo json_encode($arr);

and in js instead of complete:function(data) you need
success:function(data){
   $('.loading').html('');
   console.log(data);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question