Support the ongoing development of Laravel.io →
Requests Views Forms
Last updated 2 years ago.
0
Last updated 2 years ago.
0

jimgwhit said:

See if this helps:
http://php.net/manual/en/function.json-decode.php

Thanks! I am aware of the function, issue is that:

  1. I don't know how to pass the jason string to the function when its being returned using laravel response::json()

  2. The response is triggered when the file uploader is done, which is a jquery/ajax that works asynchronously and there is no page load to update the function.

but I'm sure I'm just missing some obvious piece.

I see how I could iterate over an array created by json_decode to create and set some hidden fields. Thanks again.

Last updated 2 years ago.
0

I thought you said you had json data sitting in your view, sorry if I mis-understood. Now is this json data you are sending or receiving?

Last updated 2 years ago.
0

jimgwhit said:

I thought you said you had json data sitting in your view, sorry if I mis-understood. Now is this json data you are sending or receiving?

No worries, my post is likely overly confusing ; )

Receiving.

I have a controller method that returns a json response:

https://www.dropbox.com/s/6ql7kry9tw4bbxw/Screenshot%202014-12-05%2015.45.05.png?dl=0

just not sure what do I do with a json response? thought I could trigger a callback function when using an event handler like: onreadystatechange like so...

https://www.dropbox.com/s/8tfqecmlsctsf5a/Screenshot%202014-12-05%2015.46.54.png?dl=0

Last updated 2 years ago.
0

Try this see the line in your dropbox pic:

document.getelementbyid('ajaxstuff').innerhtml=ststushtml;

You need to make a field in your form called "ajaxstuff" same id="ajaxstuff"
Try this un-hidden at first to see if it works. That's what

document.getelementbyid('ajaxstuff').innerhtml=ststushtml;

is trying to do, put a status in a field with an id og ajaxstuff.

Last updated 2 years ago.
0

Would it be easier to just use php to do your file uploading?

Last updated 2 years ago.
0

yea thats what I was thinking. Lets back up a second I think the issue I'm having is that I'm not doing doing something write with my js code.

So If my controller method returns a respons::json($data, $status)

In my js when I do:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
	if(xhr.readyState === 4) {

		var images = JSON.parse(xhr.responseText);

		console.log(images);

	}

I should see in my console the json string correct? I don't currently

I think my issue is with the following opening and sending of the request, since my controller is sending a repsonse, not sure how the requesting part work in terms of method and url.

xhr.open('get', 'upload'); xhr.send();

Last updated 2 years ago.
0

jimgwhit said:

Would it be easier to just use php to do your file uploading?

Hahah, yea probably. I think this stuff is just to far above my head. WIse suggestion

Last updated 2 years ago.
0

I think it was also that I was interested in how to use Laravel's response::json()

Like, I get how you execute that code in the route or controller, but not how you access the data it in the view.

Last updated 2 years ago.
0

Here's another way to ask my question in a more academic sense.

As I understand it the ajax process is as follows:

  1. create a new xhr object

  2. create a callback function (i.e. the program you want to run when you get a response)

  3. open a request (specifying a method and a url to send the request)

  4. send the request

However what I want to understand is what do you do differently when your using laravel routes that return json responses.

Last updated 2 years ago.
0

Normally I return json from a popup, sorry I have not done it from a controller. Look at this code:

$("#myTable td:nth-child(1)").click(function(event)
{
event.preventDefault();
var $td= $(this).closest('tr').children('td');
var currentCellText = $td.eq(0).text();
var CellText = $td.eq(1).text();

$.ajax({
  url:'/crudv2/admin/getowner',
  type: 'GET',
  data: 'id='+currentCellText,
  dataType: 'json',
  success: function(data) {
  alert(data.username);
  window.opener.$('#firstName').val('data.fname);
  window.opener.$('#lastName').val(data.lname);
    
  self.close();
  }
  });
		
});

Here I have a json array named data, and I am updated two fields with that data, firstname and
lastname. Normally with an ajax update to a form, the form is open in browser, and some event,
such as a click event triggers the update.
Whereas if you are retrieving json data in you controller, it would have to be phased and passed to view.
But this would be strange in that your first pic looks like that line is wanting to update a hidden field with a variable called statushtml.

Have you tryed to use this package with just php alone just to get used of how it works? Also see if there is
a youtube video. I take it this uploading is all done with ajax? If so you may have to cheat a little and have
some code in your view that would normally go in a controller. If that is the case, don't worry, I will keep in our secret.

Last updated 2 years ago.
0

will take a look and see if I can make sense of it.

Thanks so much for your help!

Last updated 2 years ago.
0

Also, I could be wrong, but don't get confused between a json response and an ajax response. The json response is retrieved in the javascript or jquery probably from controller code, when it returns the response (data) back to the browser to update a field, it is regular text being updated. In my example if lastname is Smith, that is
whats returned. So you have a json response and in turn an ajax response. Now this is unless you are retrieving
json data from somewhere, which is all together different.

Last updated 2 years ago.
0

I discovered that the library I'm using for file uploads has a place to set a callback function to execute once files are done uploading where I can use jquery to set the value of the form fields, however I still don't know what it's doing behind the scenes.

I think my question has changed to:

If I have controller code in laravel that returns a json response, how do I setup an event listener in js to execute code when the page receives that response?

0

Can you post your views and controller code here, not pics on dropdox. I'd still attempt a single page app using php/pdo and regular html just to you fully understand how this upload app works, then you would know more of how to do it in
laravel.
That said, usually ajax is triggered from a link or button. You probably have a button or link that says upload on your form, just guessing here. After a successful upload I'm taking it that a status field is supposed to be updated on that same form.
Anyway Your code posted in forum will help me and others help you figure it out.

0

Oh I figured out how to do what I originally wanted already, I was more asking in general what does one do with json responses coming from laravel, since your not initiating a request.

This is a separate from what I was originally posting about, sorry. As I said above in the js code you use to initalize the file upload pluging there was a place to set a callback function to execute when each file is done uploading (multiple file upload). So I was able to use jquery there to add the value to hidden field. Like so:

onFileComplete: function (evt, uiEvt) {
    var file = uiEvt.file;
    var json = uiEvt.result;
    $('#filenames').append('<input name="filename[]" type="hidden" value="' + json.name + '">');
}
0

but just for posterity:

I'm using fileAPI library with jquery wrapper:

https://github.com/mailru/FileAPI http://rubaxa.github.io/jquery.fileapi/

In my view I have the following code for the uploading ui:

<div id="uploader">
    <div class="js-files">
        <div class="js-file-tpl" data-id="<%=uid%>">
            <div class="clearfix">
                <div class="file-preview pull-left"></div>
                    <div class="filename pull-left"><%-name%></div>
                    <div data-fileapi="file.remove" class="btn btn-sm btn-danger pull-right"><i class="fa fa-times"></i></div>
             </div>
             <div class="progress progress-small">
                 <div class="progress-bar progress-bar-primary"></div>
                 <div class="progress-bar progress-bar-success" style="display: none"></div>
             </div>
        </div>
    </div>
    <div class="js-upload" style="display: none">
        <h3 class="btn-txt" style="display:inline-block;margin-top:10px;">Uploading... <small class="js-size "></small></h3>
    </div>
    <div class="js-success">
        <h3 id="success-msg"></h3>
    </div>
    <div class="js-browse btn btn-default">
        <span class="btn-txt">Choose Files</span>
        <input type="file" name="filedata" >
     </div>
     <button class="js-send btn-small btn btn-default" type="submit">Upload</button>
     <button class="js-reset btn-small btn btn-danger pull-right" type="reset">Cancel All</button>
</div>

then the js to initalize the uploader:

window.FileAPI = {
    debug: true,
    cors: false,
    staticPath: '{{ url("vendor/fileapi/FileAPI") }}', // path to '*.swf' files necessary for fallbacks
  };

$(function() {
    $('#uploader').fileapi({
        maxSize : 10 * FileAPI.MB,
        multiple: true,
        accept: 'image/*',
        url: '{{ URL::action("ImagesController@upload") }}',
        elements: {
        list: '.js-files',
        // Controls
        ctrl: {
            upload: '.js-send',
            reset: '.js-reset'
        },
        // Display element depending on upload state
        active: {
            show: '.js-upload',
            hide: '.js-browse'
        },
        // Total size of queue
        size: '.js-size',
        // Filelist options
        file: {
        // Template
        tpl: '.js-file-tpl',
        // Progress bar
        progress: '.progress .progress-bar',
        // Preview file or icon
        preview: {
            el: '.file-preview', // css selector
            width: 50,
            height: 50
        },
        complete: { hide: '.progress' },
    },
		},
<!-- THIS WAS WHAT MY OP WAS ABOUT -->
    onFileComplete: function (evt, uiEvt) {
        var file = uiEvt.file;
        var json = uiEvt.result;
        $('#filenames').append('<input name="filename[]" type="hidden" value="' + json.name + '">');
        }
    });
});	
</script>

and finally the controller code that returns the json using laravel's "response::json()", which is what I was also originally asking about. i.e. my confusion around getting a response from laravel without going through the regular steps of using ajax where you set a request and then get a response.

    /**
     * Upload and move portfolio images
     *
     * @return Response
     */
    public function upload()
    {

        $user = Auth::user();
        $creative = Creative::where('user_id', $user->id)->firstOrFail();

        $file = Input::file('filedata');

        $destinationPath 	= 	'uploads/workimages';
        $filename  			= 	Auth::user()->slug . str_random(6);
        $extension 			= 	$file->getClientOriginalExtension(); 
        $size      			= 	$file->getSize(); 
        $fullName  			= 	$filename.'.'.$extension;
        $upload_success 	= 	$file->move($destinationPath, $fullName);


          if( $upload_success ) {
            return Response::json(['name' => $fullName, 'size' => $size], 200);
          } else {
            return Response::json('error', 400);
            }		
    }
Last updated 9 years ago.
0

In the background: Example isn't laravel, but similar.

  • Say I have an add view for a pet.
  • Part way down there's fields for the pet owner.
  • I place a button next to owner field to open a popup
  • In popup i have a owners table where I select the owner.
  • and here goes:
    Take note of this line:
url: '/mvcpass/owner/getowner',

owner is a controller, getowner is a controller method: Whole thing:

$("#myTable td:nth-child(1)").click(function(event)
{
event.preventDefault();
var $td= $(this).closest('tr').children('td');
var currentCellText = $td.eq(0).text();
var CellText = $td.eq(1).text();
$.ajax({
  url: '/mvcpass/owner/getowner',
  type: 'GET',
  data: 'getownerID='+currentCellText,
  dataType: "json",
  success: function(data) {
  alert(data.ocheck);
  window.opener.$('#ownerid').val(data.ownerid);
  window.opener.$('#petowner').val(data.oname);
  window.opener.$('#ostreet').val(data.ostreet);
  window.opener.$('#odate').val(data.odate);
  if(data.ocheck == '1')
  		{
    	
    	window.opener.$('#ocheck').attr('checked', true);
		}
	else
		{
		 
		 window.opener.$('#ocheck').attr('checked', false); 
		}
  
  self.close();
  }
  });
		
});

This is background involkes controller, controller gets data from model, and retruns it back to above jquery:
controller code partial:

$ownerList = $this->model->getowner($id);
		$noteList = rtrim($noteList, "]");
		$noteList = ltrim($noteList, "[");
		echo $ownerList;

Model code partial:

return json_encode($this->db->select('SELECT * FROM powners WHERE ownerid = :ownerid', 
            array('ownerid' => $ownerid)));

I didn't show the code where I open the popup, but basically the jquery in the background is doing all of this through ajax.
Code like this:

window.opener.$('#petowner').val(data.oname);

is placing the petowner name in that field in my add form. Again the whole time I am in my add form.
Just like your response, this is what's going on in the background.
One thing here, there's no json response, it's ajax, it's json phased. json is just a special javascript array notation.

0

This part supposed to be:

$ownerList = $this->model->getowner($id);
        $ownerList = rtrim($ownerList, "]");
        $ownerList = ltrim($ownerList, "[");
        echo $ownerList;

You echo back an ajax response:

Last updated 9 years ago.
0

Wow very helpful thanks!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

gitdistill gitdistill Joined 22 Oct 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.