I am new in ajax . I try to save data in database in Codeigniter framework using ajax.
This is my ajax code:
$('#cmpNameEditForm').submit(function(event) {
event.preventDefault();
$.ajax({
url: '<?=base_url();?>company/home/updateName',
type: 'POST',
data: {
'name': $('#cmpName').val(),
},
success: function(data) {
$('p.error').html(data);
}
});
});
My view page is:-
<div id="name-edit-clone">
<?=form_open_multipart('', array('name'=>'CmpNameEditForm', 'role'=>'form', 'id'=>'cmpNameEditForm'))?>
<h3>Company Name</h3>
<?=form_input(array('name'=>'cmpName', 'id'=>'cmpName', 'placeholder'=>'Company Name', 'value'=>$company_name));?>
<?php echo form_error('cmpName','<p class="error">','</p>'); ?>
<?=form_submit(array('name'=>'submit', 'value'=>'Save', 'class'=>'btn btn-success nameSave'));?>
<?=form_button(array('name'=>'button', 'type'=>'reset', 'content'=>'Cancel' , 'class'=>'btn btn-danger nameCancel', 'id'=>'cmp-name-hide'));?>
<?=form_close()?>
</div>
What i am in wrong. Please help. Thanks you.
Related
i am trying to update data but i am getting error, failed loading post.
AJAX code:
jQuery(document).ready(function($) {
$('#update-data').on('click',function(){
alert("run");
// e.preventDefault(e);
$.ajax({
type: "POST",
url: "teachers/" + $('#update-data').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
beforeSend: function() {
},
success: function (data) {
alert("updated");
},
});
});
});
view:
when i try all text field in div i get error failed loading post,
<div id="update-form">
//all text fields
<button type="button"name="id" value="{{#$teacher->id}}" id="update-data" >UPDATE</button>
</div>
but when i put everything in form my data is being updated correctly, but in this case ajax code is totally ignored and only last record is updating.
<form action="#if(isset($teacher)) {{route('teachers.update', $teacher->id)}} #else {{route('teachers.store')}}
#endif" method="post" id="update-form" autocomplete="off" enctype="multipart/form-data" >
<button type="submit" name="id" value="{{#$teacher->id}}" id="update-data" > UPDATE</button>
</form>
Console Error:
app.js:10216 POST http://todolist.local/teachers/729 405 (Method Not Allowed)
app.js:10216 XHR failed loading: POST "http://todolist.local/teachers/729".
javascript?v=1567677915:4 XHR finished loading: GET "http://todolist.local/_debugbar/open?op=get&id=X15228e3cd6c2213f70bded7c0a69583b".
Update Controller:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
web.php:
Route::get('/', 'TeachersController#index')->name('home');
Route::resource('teachers', 'TeachersController');
Update your ajax request as below:
jQuery(document).ready(function($) {
$('#update-form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "PUT",
/*Your logic*/
});
});
});
View
<form action="#if(isset($teacher)) {{route('teachers.update', $teacher->id)}} #else {{route('teachers.store')}} #endif" method="post" id="update-form" autocomplete="off" enctype="multipart/form-data" >
{{method_field('PUT')}}
{{ csrf_field() }}
<button type="submit" name="id" value="{{#$teacher->id}}" id="update-data" > UPDATE</button>
</form>
Try this..
ajax post caused the webpage to reload before I could get a result, therefore.
i am triyng to save data but my page is reloading with json message on next page, how can i stop reloading page.
Ajax Code:
jQuery(document).ready(function($) {
$("#add-data").submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Submit Button:
<button type="submit" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
Store Controller:
after saving which is working fine:
return response()->json([
'status' => 'success',
'msg' => 'New esecond has been saved'
]);
It is because of you are trying to post the data to form .
If you use button type = "submit" it will redirect you to somewhere .
You should avoid using type = "submit" .
Instead use the type = "button"
<button type = "button" class="btn btn-secondary btn-lg shadow-lg rounded" value="ADD" id="add-data"> <span class=" fa fa-plus"> </span> ADD</button>
And achieve it by using click event of the button .
then get it in jquery .
$("#add-data").click(function (event) {
//Your code here
}
You can try this instead of prevent default. The reload happen, because you use form submit event.
$('#add-data').submit(false);
If you want to use prevent default, then use click event of the submit button to perform the action.
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
}
Remove dataType: 'json' as you're already returning JSON otherwise your button seems perfect.
Try this
jQuery(document).ready(function($) {
$("#add-data").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
},
});
});
});
Add "return false;" in the end of your submit callback..
As "add-data" is ID of your button, for your example it couldn't retrieve a submit event. That's because it submitted and didn't prevented.
So you can write something like this:
$("form").submit(function (event) {
event.preventDefault();
$.ajax({ ... });
return false; // <<< THE THING
});
Or just do that with binding an click event on button (not for submit event on button)
$("#add-data").click(function (event) {
event.preventDefault();
$.ajax({ ... });
});
With this you can leave button type, and don't need to change that to type="button".
Using Joomla:
My problem is when I submit the button, ajax send an empty data array back to my client. Debbuging in the console shows me that datas in the header but the preview and response values are empty.
Here is my code (I am using a modal form from bootstrap).
HTML in my default script:
<form action="<?php echo JRoute::_('index.php?option=com_addproduct&view=addproducts'); ?>" method="post" name="modalMessageForm" id="modalMessageForm" enctype="multipart/form-data">
<input type="file" id="message-image-upload" accept="image/*" style="display:none;" name="message-image-upload">
<textarea class="form-control message-textarea" id="message-textarea" placeholder="Nachricht..." name="new-message" rows="4"></textarea>
<button type="button" id="button-close-message" class="btn btn-default btn-block btn-message-close" style="display:none; margin-top:5px;"><?=JText::_( 'COM_ADDPRODUCT_MODAL_MESSAGES_CLOSE')?></button>
</form>
JQuery / Ajax:
$(document).on("submit", "#modalMessageForm", function(e)
{
var form = $('#modalMessageForm').get(0);
e.preventDefault();
var formData = new FormData(form);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
$.ajax({
crossDomain: true,
type: "POST",
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
data: formData,
dataType: "json",
processData: false
})
.done(function(data, textStatus, jqXHR){
console.log('Message: '+data.new-message+' PicName: '+data.img);
})
});
Here my controller.php:
public function sendMessages()
{
JResponse::setHeader('Content-Type', 'application/json', true);
$app = JFactory::getApplication();
$input = $app->input;
$new-message = $input->getString('new-message', '', 'RAW');
$img = $_FILES['message-image-upload']["name"];
$img = JFile::makeSafe($img);
$results=array(
'new-message' => 'new-message',
'img' => $img
);
echo json_encode($results);
$app->close();
}
I got the datas / variables in the console log.
it is:
new-message: null,
img: null
trying to set contentType: false will give me an 500 error.
Thank you very much
That´s the info from my network
enter image description here
I figure something out.
It´s the URL in my ajax command.
When I am using a normal url like
url: 'upload.php'
that will work and then I can set the
contentType: false,
But this is not safety enought.
I just want to use this url
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
But then I got the error message that the view is not found. That´s very strange.
I'm still using Laravel 4.2 and I'm trying to post a form with AJAX, but it gives me error 404 for a post page. Here is my code:
routes.php:
Route::post('/', array(
'as' => 'postFora',
'uses' => 'HomeController#postFora'
));
HomeController.php:
public function postFora() {
$form = Input::all();
$f = New Fora;
$f->content = Input::get('contant');
$f->user_id = Input::get('user_id');
$f->save();
return Response::json(array('success' => true));
}
main.js:
$('.dodaj-foro').submit(function(e) {
var form = $(this);
$.ajax({
url : "http://localhost/belezka/",
type: "POST",
dataType: "JSON",
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
e.preventDefault();
});
index:
<form class="dodaj-foro" action="/" method="post" accept-charset="utf-8">
<input type="hidden" name="user_id" value="{{$user[0]->id}}">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<input type="text" name="contant" placeholder="Fora tuki">
</form>
I think you have to enter the route in present in Route file instead of http://localhost/belezka/
Try to replace :
$.ajax({
url : "http://localhost/belezka/",
type: "POST",
dataType: "JSON",
.....
By :
$.ajax({
url : "postFora",
type: "POST",
dataType: "JSON",
.....
Hope this will help.
In case you did not change the defaults Laravel comes with, add public to the AJAX request URL. By default, the route '/' corresponds to http://localhost/belezka/public/ due to URL rewriting.
Problem: I'm trying to send ajax reguest, and then submit the form.
Aproaches:
1. I solved the problem by putting
success: function() {
document.myform.submit();
}
But i think it's not the most elegant solution. Can you explain me why it works only if i put document.myform.submit(); in success? Is there any other way to solve this problem?
<div class="buttons">
<div class="right">
<form name="myform" onsubmit="javascript: startAjax(); return false;" action="https://example.com/payment.php" method="get">
<input type="hidden" name="merchantId" value="<?php echo $merchantIdKZM; ?>">
<input type="submit" value="<?php echo $button_confirm; ?>" id="button-confirm2" class="button" name="PayKZM" />
</form>
</div>
</div>
<script type="text/javascript">
function startAjax() {
console.log("dafaaaa");
$.ajax({
type: 'get',
url: 'index.php?route=payment/bank_transfer/confirm',
async: 'false',
success: function() {
// location = '<?php echo $continue; ?>';
}
});
} // Calls ajaxComplete() when finished
function ajaxComplete()
{
console.log("dafa");
document.myform.submit();
}
</script>
success's function is called upon the get request receiving a valid response as #harsh pointed out. Thus it will occur after the get request. I believe something similar to the following would do as you request though I haven't tested it:
<script type="text/javascript">
$(function () {
$("#form").on('submit', function () {
var $form = $(this);
$.ajax({
type: 'GET',
url: 'index.php?route=payment/bank_transfer/confirm',
data: $form.serialize(),
async: 'false',
success: function () {
$.ajax({
type: 'GET',
url: 'https://example.com/payment.php',
data: $form.serialize(),
});
}
});
});
});
</script>