Leff7
2566
4
General

Sending a form-data post request with guzzle http

Posted 1 year ago by Leff7

I am using guzzle http, and would like to implement the post request that looks like this when done with js:

               var formData = JSON.stringify( { id: formID, fields: fields, settings: settings, extra: extra } );
            var data = {
                'action': 'nf_ajax_submit',
                'security': nfFrontEnd.ajaxNonce,
                'formData': formData
            }

            var that = this;

            jQuery.ajax({
                url: nfFrontEnd.adminAjax,
                type: 'POST',
                data: data,
                cache: false,
                success: function( data, textStatus, jqXHR ) {
                    try {
                        var response = jQuery.parseJSON( data );
                        nfRadio.channel( 'forms' ).trigger( 'submit:response', response, textStatus, jqXHR, formModel.get( 'id' ) );
                        nfRadio.channel( 'form-' + formModel.get( 'id' ) ).trigger( 'submit:response', response, textStatus, jqXHR );
                        jQuery( document ).trigger( 'nfFormSubmitResponse', { response: response, id: formModel.get( 'id' ) } );
                    } catch( e ) {
                        console.log( e );
                        console.log( 'Parse Error' );
                        console.log( e );
                    }

                },

How can I make a post request form-data with guzzle, I have tried with doing the same thing like this:

        $url = 'http://ytf.app/wp-admin/admin-ajax.php';
        $data = [];
        $data['security'] = $this->getNonce();
        $data['action'] = 'nf_ajax_submit';
        $data['formData'] = $request->all();
        $formData = json_encode($data);

        $client   = new Client();
        $response = $client->request('POST', $url, [
            'body' =>  $formData,
        ]);

        $body = json_decode($response->getBody(), true);

        if ($body['success'] === true && $body['data'] !== false) {
            return $body['data'];
        }

But, that is not working, how should I do this?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.