Yii2 Ajax Submission not working - javascript

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

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;
});'
);
?>

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

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

Related

Codeigniter - Page redirect not working after submitting button

I'm trying to insert and update data in my database using ajax to my controller. Now my data is inserting and updating precisely after I click the button. But my data on my view page is not updating. I need to refresh again the page to update my view and the success message to display
PS: It's firing sometimes, and sometimes not, Can't understand the behaviour
Below is my JS file for ajax
$('#triger').click(function(){
var btn_value = $('#triger').val();
var tenant_id = $('#tenant_id').val();
var calldisp_id = $('#calldisp_id').val();
var disposition_name = $('#disposition_name').val();
var disposition_code = $('#disposition_code').val();
var email = $.map($("#tags span"), function(elem, index){
return $(elem).text();
});
var myJsonString = JSON.stringify(email);
//alert(myJsonString);
if(btn_value == 'Create'){
$.ajax({
url:"<?php echo base_url();?>admin/call_disposition/create_email_dispo_dre",
method:"POST",
data:{email:myJsonString,
disposition_name:disposition_name,
disposition_code:disposition_code,
tenant_id:tenant_id},
dataType: 'json',
success:function(data){
},
});
}
else if(btn_value == 'Update'){
$.ajax({
url:"<?php echo base_url();?>admin/call_disposition/update_email_dispo_dre",
method:"POST",
data:{email:myJsonString,
disposition_name:disposition_name,
disposition_code:disposition_code,
calldisp_id:calldisp_id,
tenant_id:tenant_id},
dataType: 'json',
success:function(data){
},
});
}
});
Below is my Controller
public function create_email_dispo_dre($id){
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->update($id);
} else {
$data = array(
'tenant_id' => $this->input->post('tenant_id',TRUE),
'disposition_code' => $this->input->post('disposition_code',TRUE),
'disposition_name' => $this->input->post('disposition_name',TRUE),
'email' => $this->input->post('email',TRUE)
);
$this->calldisp_model->insert($data);
$this->session->set_flashdata('message', 'admin_faqs_success');
redirect('admin/call_disposition/update/'.$id);
}
}
In the ajax request for update:
In the success section:
success:function(data){
},
you need to call a page reload:
window.location.reload();
so your code becomes:
success:function(data){
window.location.reload();
},
In controller
you have to add
echo json_encode(array('success'=>'1')); instead of redirect('admin/call_disposition/update/'.$id); because you used datatype "json";
and change success function an ajax request Like
success:function(data){
if(data.success=='1'){
window.location.reload();
}
}
In codeigniter when you execute an Ajax call you can't redirect from the controller function. If you want to seemlessly update the page after clicking #trigger you have to echo the result in your controller
echo json_encode($html_you_want_to_display);
and then in your ajax success clause you need to update the div with the result from the echo by setting the innerHtml to the result. Hope this helps

codeigniter or PHP - how to go to a URL after a specific AJAX POST submission

I am successfully inserting data into my database in codeigniter via a an ajax post from javascript:
//JAVASCRIPT:
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
$('body').append(data); //MH - want to avoid this
}
});
//PHP:
public function respond(){
$this->load->model('scenarios_model');
$responseID = $this->scenarios_model->insert_response();
//redirect('/pages/view/name/$responseID') //MH - not working, so I have to do this
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
echo "<script>window.location = '$redirectURL'</script>";
}
But the problem is that I can't get codeigniter's redirect function to work, nor can I get PHP's header location method to work, as mentioned here:
Redirect to specified URL on PHP script completion?
either - I'm guessing this is because the headers are already sent? So as you can see, in order to get this to work, I have to echo out a script tag and dynamically insert it into the DOM, which seems janky. How do I do this properly?
Maybe you can 'return' the url in respond function and use it in js
PHP :
public function respond(){
// code
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
return json_encode(['url' => $redirectURL]);
}
JS :
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
dataType: 'JSON',
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
window.location = data.url
}
});
you have to concatenate the variable. That's all.
redirect('controller_name/function_name/parameter/'.$redirectURL);

Can't process simple form submitted by jQuery ajax

My form:
<form id="new-protocol-form" method="post" role="form">
<textarea name="text"></textarea>
</form>
My jquery ajax:
$('#submitProtocol').click(
function() {
$.ajax({
type: "POST",
url: "newProtocol.php",
data: $('#new-protocol-form').serialize(),
success: function() { alert{'ok'} },
error: function() { alert('error'); }
});
}
);
My newProtocol.php:
<script>
alert(<?php echo $_POST['text']; ?>);
</script>
Alert window with 'ok' text triggered by ajax 'success' method is shown, but I can't get alert window with $_POST['text'] value from newProtocol.php file. No error in javascript console.
You need to use $_POST['text']. You're using parentheses where you shouldn't be.
In addition, since you're using AJAX you probably don't want to navigate to the other page. Your alerts in your success function will never fire if you don't prevent the default behavior.
newProtocol.php
<?php
echo $_POST['text'];
?>
jQuery
$('#submitProtocol').click(function(event) {
event.preventDefault(); // stop the default click behavior
$.ajax({
type: "POST",
url: "newProtocol.php",
data: $('#new-protocol-form').serialize(),
success: function(data) {
console.log(data); // show the text being returned
},
error: function() { console.log('error'); }
});
}
);
Also, quit using alert() for getting return values and trouble-shooting.
First, $_POST is not a function, it's an array. So it should be $_POST['text']. Also,
<script>
alert(<?php $_POST('text'); ?>);
</script>
will not create an alert like you expect since an async request does not run any javascript in the target page.
Since you're trying to test if the AJAX is working, the best way is to check what was the date returned from that request. Example:
//...
success: function(data) { console.log(data) },
//...

Have to click submit twice for AJAX request to fire on form submission

My Form HTML looks like this.
<form novalidate action="register.php" method="post" >
<label for="username">Username</label>
<input type="text" name="username" required placeholder="Your username" autofocus/>
<input type="submit" name="register" value="Register" cid="submit" />
</form>
And My jQuery looks like this
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
e.preventDefault();
});
The sad thing is that it logs hello to the console but it never submits the form with one click on the submit button. I need to press two times to submit button.
Can anyone tell me the problem and how can I fix it so that 1 click is sufficient for form submission.
NOTE: The data of form is send for validation not actually for submission . If data like email , username etc are valid i want the form to be submitted with one click.
Try separating the validation from the form submit.
Simply changing this line:
$("form").submit(function(e) {
to
$("input[name='register']").click(function(e) {
First of all I think it would be cleaner to use a success function instead of a .done() function. For example:
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
// Merge the check.php and register.php into one file so you don't have to 'send' the data twice.
url: "register.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON",
success: function() {
console.log("This form has been submitted via AJAX");
}
});
});
Notice that I removed the .unbind() function, as I suspect it might be the reason your code is acting up. It removes the event handlers from the form, regardless of their type (see: http://api.jquery.com/unbind/). Also, I put the e.preventDefault() at the start. I suggest you try this edited piece of code, and let us know if it does or does not work.
EDIT: Oh, and yeah, you don't need to submit it when you're sending the data via AJAX.
Try this one.
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
});
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datatype: "JSON",
success: function(data) {
return data;
}
});
});
So, to break it down.
Stop the form submission with the preventDefault().
Get the form data and submit it to your validator script.
The return value, I assume, is a boolean value. If it validated, it'll be true, or false.
Return the value which will continue the form submission or end it.
NB.: This is a horrible way to validate your forms. I'd be validating my forms on the server with the form submission, because javascript can be terribly easily monkeyed with. Everything from forcing a true response from the server to turning the submission event listener off.
Once I have the same issue
What I found is I have some bug in my url xxx.php
it may return error message like "Notice: Undefined variable: j in xxx.php on line ....."
It may let ajax run unexpected way.
Just for your info.
Instead of doing prevent default when clicking a submit button, you can create a normal button and fire a function when you click it, at the end of that function, submit the form using $('#form').submit();. No more confusing prevent default anymore.
You don't need to call submit() since you are posting your data via ajax.
EDIT You may need to adjust the contentType and/or other ajax params based on your needs. PHP example is very basic. Your form is most likely much more complex. Also, you will want to sanitize any php data - don't rely on just the $_POST
jQuery:
$("form").submit(function(e) {
$.ajax({
'type': 'post',
'contentType': 'application/json',
'url': 'post.php',
'dataType': 'json',
'data': { formData: $(this).serialize},
'timeout': 50000
).done(function(data) {
// Response from your validation script
if (data === true)
{
// SUCCESS!
}
else
{
// Something happened.
}
).fail(function(error) {
console.log(error);
});
e.preventDefault();
});
PHP
$is_valid = FALSE;
$name = $_POST['name'];
if ($name !== '')
{
$is_valid = TRUE;
}
else
{
return FALSE;
}
if ($is_valid)
{
// insert into db or email or whatver
return TRUE;
}

Form or jQuery Ajax?

When a form sends variable with GET Method, the URL changes, putting the variables that you are passing in this way
url?variable=....
How can I get the same result with jQuery Ajax? Is it possible? Thank you
set path in your php layout/view file where you include this code
<script>
var path="<?php echo $this->webroot;?>";
</script>
and add following jquery code to post the data through ajax.
$.ajax({
type: 'POST',
url: path+'homes/createEvent',
data: {eventname:eventname,manager:manager},
async: false,
success: function(resulthtml)
{
alert(resulthtml);
},
error: function(message)
{
alert('error');
}
});
and on homes_controller.php, u will get this ajax data in createEvent function,
<?php
function createEvent()
{
$eventName=$_POST['eventname'];
$manager=$_POST['manager'];
}
?>

Categories

Resources