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;
}
2

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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
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
0

Try this one,

return response()->json($answer);

1 Comment

Please add your string result in question
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;
}

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.