Laravel – How to use Ajax to send data from a checkbox button to a controller

I'm trying to use a toggle checkbox to change data in my MySQL database. Essentially, I want a nice admin site where I can unlock users with a nice on / off switch for certain features on the site.

Everything seems to be set up correctly, but my controller is not responding or not firing at all.

At the moment I have a working shift key in my view that triggers a javascript function. In this Javascript function, I have already set up data that I want to transfer to my controller.

I have set up Ajax in my Javascript. Apparently Ajax has this part in its code (see my code, if you need to know what I mean), where "success" or "error" is. Before entering the token {{csrf_token ()}}, I always ended up in the error area. However, I always go to the "Success" section when I toggle my button.

Now to my problem:
Although Ajax confirms a success, literally nothing happens in my controller. I have no idea how to change that because there is no error code.

That's my button

id}}) value = {{$company->permissionlevel}} class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $company->permissionlevel ? 'checked' : '' }}>

This is my Javascript (the relevant part)

var test = 12; // A random variable for this example

        $.ajax({
            method: 'POST', // Type of response and matches what we said in the route
            url: 'home/update', // This is the url we gave in the route
            data: {'test' : test, _token: '{{csrf_token()}}'}, // a JSON object to send back
            success: function(response){ // What to do if we succeed
                console.log(response); 
                //alert("Ajax success");
            },
            error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
                console.log(JSON.stringify(jqXHR));
                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                //alert("Ajax error");
            }
        });

This is my controller feature (just to see what happens)

public function update (Request $request)
    {

            //echo "This is a test";
            $data = $request->all(); // This will get all the request data.
            dd($data); // This will dump and die
            return $data;



        }   

route

Route::post('/home/update', 'HomeController@update');

Expected result:
Controller throws something at me. At the moment, I just want to see if my controller responds to the keystroke or if I can request the data Ajax should send.

Actual result:
Nothing happens on the side of my controller

jquery ajax – Add items to Sharepoint Online's modern user interface list using the API

When you use SharePoint Framework to develop and build custom WebParts code, you can (and should) use the context provided in the parent WebPart component this.context and send it via its properties to your root WebPart component (the rendered ones).

Now your component has the context and capabilities to use the provided SPHttpClient, which does the authentication and work for you: this.props.context.spHttpClient. with the methods get(). post() and fetch(),

If you are not using SharePoint Framework now, you are on a SharePoint page where you can no longer retrieve a request digest (and need one to transfer data). You must first ask for one and use it in a X-RequestDigest Headers in your mail requests.

The Office365 app page does not contain a RequestDigest

The method is to create a first POST /_api/contextinfo,

Hope that helps!

Proper Google Analytics on Ajax load more

I have an Ajax on the category page and when loading more, after loading via Ajax and after success function URL changes. On this successful feature, I placed this Google Analytics code to translate the URL into the event.

So that's the right code? I think none of them works.

ga('send', {
  hitType: 'event',
  eventCategory: 'page_views',
  page: 'page/'+page+'/'
});

OR

ga('send', {
            hitType: 'pageview',
            page: ''+'page/'+page,
    });

OR

ga('send', {
  hitType: 'event',
  eventCategory: 'page_views',
  eventAction: 'Page scroll',
  page: ''
});

I also tried static code in the header:



Nothing seems to work.

laravel – Error 500 nolara on Ajax return

The error only occurs when json returns, I tested the route with id
separate and returns normal, but inside the controller does not occur

SCRIPT

$('#acordo_boletos').click(function(){

    $("#bodyBoletos").html("");


    $.ajax({
        url:"/dashboard/admin/boletos/gera/"+MyApp.negociacao_id,
        type: 'GET',
        dataType: 'json',
        success: function(response){


            var html = '';
                    if(response.errors)
                    {
                    html = '
'; html += '

'; html += response.errors; html += '

'; html += '
'; $('#form_result').html(html); $('#form_result').show(); } var len = response.length; for(var i=0; i" + negociacao_id + "" + "" + parcela + "" + "" + due_date + "" + "R$ " +formatMoney(amount) + "" + "" + url + "" + ""; $('#form_result').hide(); $("#boletos tbody").append(tr_str); } console.log(response); } });

CONTROLLER:

public function geraBoleto($id)
    {

        $boletos = AppBoletos::where('negociacao_id', '=', $id)->get();
        foreach ($boletos as $boleto) {
            if (!$boleto->RequestID) {

                $amount = $boleto->amount;
                $due_date = $boleto->due_date;
                $customer_document_number = $boleto->customer_document_number;

                $id_devedor = Devedor::findOrFail(1);


                $this::gerarBoletoIndividual(
                    $boleto->id,
                    $id_devedor,
                    $amount,
                    $due_date,
                    $customer_document_number
                );
            } /
        }
        return response()->json(Boletos::where('negociacao_id', '=', $id)->get());

    }

WAYS:

Route::get('boletos/gera/{id}', 'BoletosController@geraBoleto');

How do I upload a file in Django with Ajax?

I would like to upload the file in the Django framework with Ajax by clicking on the link
the problem with how to add files with serilaized data
That's my model

class Document(models.Model):
    description = models.CharField(max_length=255, blank=True)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)

and that's the form

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('description', 'document', )

That's the view

def mif request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('home')odel_form_upload(request):

    else:
        form = DocumentForm()
    return render(request, 'core/model_form_upload.html', {
        'form': form
    })

I used this script to send and upload files


and that is the template

{% extends 'base.html' %}

{% block content %}
  
{% csrf_token %} {{ form.as_p }}

Return to home

{% endblock %}

It works with simple data, but not with uploading files

8 – Why does the Ajax button call submitForm?

I have no problem using Ajax in any other form element as a button. When I click on this button

  '#type' => 'submit',
  '#ajax' => (
    'callback' => '::ajax_function',
    'wrapper' => 'my-button-wrapper',
  ),

it reloads the page … well, it does what normal submit buttons would do – calls submitForm (). And I do not need that. I only need this button to call ajax_function ().

Send a list from AJAX to a controller in MVC 5

I want to know how to get a list of objects in Ajax and send them to ActionResult of my controller. I appreciate the help in advance.

Ajax query

$(document).ready(function () {
    var array=(
        {id: "1", nombre: "Darwin", edad: "26", fecha: "28-10-1992"},
        {id: "2", nombre: "Aldo", edad: "30", fecha: "19-11-1988"},
        {id: "3", nombre: "Alexis", edad: "34", fecha: "01-11-1984"});

    $.ajax({
        url: '/Prueba/ExportarExcel',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(array),
        success: function (data) {
            console.log(data);
        }
    })
});

This is my controller, which I want to store in a variable named result

(HttpPost)
public ActionResult ExportarExcel(List array)
{
 var resultado = array;
 return View(resultado.ToList());
}

I want to store Ajax data in a list of Person objects that are displayed in the controller. However, it will display such an error message

The value can not be null. R n Parameter Name: Source

Ajax HTML Answer Problem in Magento 1.9

I face a problem while getting an HTML response from Ajax.
My Ajax response contains an HTML element with the "onclick" attribute. If I removed the onclick, I get the answer, otherwise I get a 500 Internal Server Error.

Phtml File Code Sample (Ajax):

 jQuery( window ).load(function() {
            var temp_quote =jQuery('#quote-list-data').val();
            var compare =jQuery('#compare-data').val();
            var loadcollect = jQuery('#machine-key').val();
            var presentData = jQuery('#parent-class-data').val();
            var catData = jQuery('#cat-data').val();

            jQuery.ajax({
                url: "getUrl('attr/employee/getListing'); ?>",
                type: "POST",
                data: {
                    temp_qquote_list: temp_quote,
                    compare_product: compare,
                     loadcollect: loadcollect,
                    presentData: presentData,
                    catData:catData
                },
                dataType: 'html',
                success: function (response) {
                    console.log("Success Ajax ");
                    jQuery(".similar_data").append(response);

                }
            });
        });

function showCompareLink(id, classname, link)
{
--------- code stmt ----------
}

Controller File Code Example:

public function getListing()
{
    $listData = '';
        $compare_product = ($_POST('compare_product'));

    foreach ($_productCollectionData as $_product) {
          $entity_id = $_product->getId();

    $listData .='
'; if($_product->isSaleable()) { if (in_array($entity_id, $compare_product) && count($compare_product) >= 2) { $addto_class = 'after_compare_checkbox_new_' . $_product->getId(); $addto_display = 'none'; $compare_display = 'block'; } else { $addto_class = 'before_compare_checkbox_new_' . $entity_id; $addto_display = 'block'; $compare_display = 'none'; } if (in_array($entity_id, $compare_product)) { $ckhed = 'checked'; } else { $ckhed = ''; } $showCompareLinkParam = 'new'; $compareUrlForAnchor = Mage::getUrl('catalog/product_compare/index'); $onclickCompare = 'window.open("'.$compareUrlForAnchor.'", "_blank", "location=yes,height=720,width=720,toolbar=no,menubar=no,scrollbars=yes,resizable=yes")'; $_compareUrl = $obj->helper('catalog/product_compare')->getAddUrl($_product); $listData .='
'. $obj->__('Compare').'
'; } $listData .='
'; } echo $listData; }

ajax – custom table + empty values ​​in form_state

In a custom form, I created a table item:

  // Table results.
  $form('table') = (
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => ('id' => 'table-results'),
    '#empty' => t('No results.'),
    '#prefix' => '
', '#suffix' => '
' );

This table is updated when I click on a specific button.

I have to get the output HTML of this table in another function. When I use a dpm ($ form_state-> getValue (& # 39; table & # 39;)); I get an empty array. However, the other values ​​(other fields) can be accessed in $ form_state.

// My second function
public function secondfunction(array $form, FormStateInterface $form_state) {
  dpm($form_state->getValue('table')); // -> empty value...
  dpm($form_state->getValue('textfield')); // I get a value
}

What do I change in my code to solve this problem?

Move the Ajax loader span into contact form 7 from the Send field

Is there a way to tell the contact form 7 to place the Ajax loader span outside the submit field? It automatically adds it to where the [Submit] field is inserted into the CF7 form.

Ignore the void

since I use it as a placeholder for a display: grid setup. I just want two elements in the Demo Submit Div … the

and the field

    

My current form in CF7 looks like this:

[text* first-name id:first-name class:demo-form-field]
[text* last-name id:last-name class:demo-form-field]
[email* demo-email class:demo-form-field]
[tel* demo-phone class:demo-form-field]
[text* demo-organization class:demo-form-field]
[hidden lead-source "http://example.com"]

[submit "Send" ]