user5300122
user5300122

Reputation: 143

Yii2 Ajax Submission not working

Iam new to Yii2 and Ajax

I want to add multiple job for a work ,for that I pass id to WorkJobs Controller

This is my code for ajax submission

<?php

$this->registerJs(
'$("body").on("beforeSubmit", "form#w1", function() {

    var form = $(this);
    if (form.find(".has-error").length) {
      return false;
    }

    $.ajax({
      var jobid =  "<?php echo $id;?>";

      url: form.attr("work-jobs/create&id="+jobid),
      type: "post",
      data: form.serialize(),
      success: function(errors) {
        alert("sdfsdf");
        // How to update form with error messages?
      }
    });

    return false;
    });'
);
 ?>

But it's not working ,I don't know what's wrong in my code ,please help ...........

Upvotes: 0

Views: 864

Answers (3)

Igbanam
Igbanam

Reputation: 6082

Building off jithin's answer, make the following changes to your $.ajax() call

  • Make sure your URL is in quotes. It is a common mistake to forget to quote the URL when interspersing it with PHP. [jithin]

Unlike jithin's answer, you should do the following

  • instead of responding to the beforeSubmit event, handle the submit event. This would allow the Yii clientsoide validations do their job
  • the ajax.success callback takes data as the argument; not error, there's the ajax.failure callback for errors

Upvotes: 0

jithin
jithin

Reputation: 920

change your code like below

<?php
$url=Yii::$app->urlManager->createUrl(['work-jobs/create','id'=>$id]);
$this->registerJs(
'$("body").on("beforeSubmit", "form#w1", function() {

    var form = $(this);

    if (form.find(".has-error").length) {
      return false;
    }

    $.ajax({


      url: "$url",
      type: "post",
      data: form.serialize(),
      success: function(errors) {
        alert("sdfsdf");
        // How to update form with error messages?
      }
    });

    return false;
    });'
);
 ?>

Upvotes: 2

morcen
morcen

Reputation: 368

Try using createAbsoluteUrl() in url like this:

url: "<?php echo Yii::app()->createAbsoluteUrl(\"work-jobs/create&id=\")"+jobid

Upvotes: 0

Related Questions