1

im using laravel 5.4 and intervention plugin to upload images as ajax

i will upload images in php controller and it will return a response (file name).

and the returned variables from php is an array but in javascript it going to string and i cant iterate that

 public function upload(Request $request)
{
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    return $answer;
}
K1-Aria
  • 1,093
  • 4
  • 21
  • 34

3 Answers3

0

Try this one,

return response()->json($answer);
Sagar Gautam
  • 9,049
  • 6
  • 53
  • 84
0

Try using json_encode().

This will solve your issue.

public function upload(Request $request)
{
    $answer=array();
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    echo json_encode($answer);
    die;
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Arshad Shaikh
  • 564
  • 1
  • 3
  • 13
  • `echo json_encode(array("answer"=>$answer)); die;` and also write `dataType:'json'` in ajax code so it will get as json in ajax success response – Arshad Shaikh Jul 04 '17 at 07:06
0
public function upload(Request $request) {
    $answer=array();
    $array = $request->file('image');
    $count = count($array);
    $answer=array();
    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[$i] = $rnd;
    }
//here print $answer and check 
//you can also check $answer with function var_dump(); 
    echo json_encode($answer);
    die;
}

Decode this array like

json_decode($json_array,true);
Pang
  • 9,564
  • 146
  • 81
  • 122
Reena Mori
  • 647
  • 6
  • 15
  • its still string in js . from php its array ir json correctly but when i get this with xhr.responseText in js it going to string – K1-Aria Jul 04 '17 at 06:54
  • i solved it from js code. it should to convert to json from javascript : var obj = JSON.parse(xhr.responseText); console.log(obj[1]); tnx – K1-Aria Jul 04 '17 at 07:06