Yii2: call javascript function with a button - javascript

I want to call a javascript function from a button in php
this is the php code:
//the view
<?php
$form = yii\widgets\ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>
<?=
$form->field($msubs, 'id_subespecifica', ['options' => ['class' => 'col-md-12']])
->widget(Select2::classname(),[
'data' => ArrayHelper::map($vectorConsul,'sesp', 'sesp'),
'options' => ['id' => 'prueba'],
])
->label(false);
?>
<button class="btn btn-primary" onclick="myFunction()">Add New</button>
<?php
yii\widgets\ActiveForm::end();
?>
And this is the Javascript code:
//Javascript
function myFunction() {
$.ajax({
url:'partidaasociada/get-linea',
type:'POST',
dataType:'json',
data:{pruebaId:$('#prueba').val()}
// alert(pruebaId);
});
In the javascript function, i need to send the $('#prueba').val() to a php function in the controller:
//Controller
public function actionGetLinea($pruebaId)
{
$model = new PartidaAsociada();
log($pruebaId);
}
But i am getting some errors, i think the button is reloading the whole form and don't recognize the previous data y sent to the form.
Note: The 'alert()' in the javascript function is on commentary because it wont let me use, the form stay loading when i put the alert. thanks beforehand.

I think part of the problem is you aren't preventing the default action of a button click.
We can clean things up a bit too. Hit control+shift+i and choose the console tab to see console.log output.
HTML:
<button class="btn btn-primary _addNew">Add New</button>
Javascript:
$('._addNew').on('click', function(event){
event.preventDefault();
var data = {};
data.pruebaId = $('#prueba').val();
var success = function(data){
console.log("Success!", data);
}
var error = function(data){
console.log("Error!", data);
}
$.ajax({
url:'partidaasociada/get-linea',
type:'POST',
dataType:'json',
data:data
}, success, error);
});

Related

Delete Field in Datatable with ajax in Codeiginiter without refreshing page

I want to delete some field in datatable using 'a' tag as a button. If that button is pressed, it will delete field in my database using ajax without refreshing page but if i click the button, it doesn't do anything. I am weak in JS or jQuery, I hope you guys will help me, thanks.
This is my JS
$('#delete-agenda').click(function(e) {
e.preventDefault();
var data = {};
data['id_itenerary'] = $(this).attr('value');
$.ajax({
url: 'http://localhost/pandansari/admin/single_trip/delete_agenda',
type: 'post',
data: data
});
});
This is my 'a' tag
<a id="delete-agenda" class="btn btn-sm btn-danger" value="<?php echo $agenda['id_itenerary'] ?>">Delete</a>
This is my controller function
public function delete_agenda() {
$id_itenerary = $this->input->post('id_itenerary');
$this->agenda_model->delete_agenda($id_itenerary);
}
This is my model function
public function delete_agenda($id_itenerary) {
$this->db->where('id_itenerary', $id_itenerary);
$this->db->delete('tb_itenerary');
}
Try this
HTML:
<a id="delete-agenda" href="#" class="btn btn-sm btn-danger" data-id="<?php echo $agenda['id_itenerary'] ?>">Delete</a>
JS:
$(document).ready(function() {
$('#delete-agenda').click(function(e){
e.preventDefault();
var id = $(this).attr('data-id');
$.ajax({
url: 'http://localhost/pandansari/admin/single_trip/delete_agenda',
type: 'post',
data: { 'id_itenerary' : id }
});
});
});
You will still have to remove the datatable entry from the table; otherwise the change will only be apparent on refresh/reload.
$('#delete-agenda').on('submit',function(e){
e.preventDefault();
//write your remaining code here
});

Ajax function call not working

I am trying to learn Ajax function calls in jquery. But I could not get the expected output. My code is below
The HTML and Script File is stored in the file 'addevent.php'
HTML Code:
<form id="addinfo">
Year: <div class="styled-select">
<select id="year">
<option>2017</option><option>2018</option>
<option>2019</option><option>2020</option>
</select>
</div>
Team:<div class="styled-select">
<select id="team">
<option>UG</option><option>PG</option>
</select>
</div>
<button class=btn name="add_event" id="add_event" />Add Event
<span id="result"></span>
</form>
</body>
</html>
Script Part:
<script>
$(document).ready(function(){
$("#add_event").click(function(){
var y= $("#year option:selected").text();
var t= $("#team option:selected").text();
$.ajax({
url: 'checkevent.php',
type: 'POST',
dataType: 'json',
data: {year:y , team: t},
success: function(result) {
console.log(result);
var val=result['result'];
document.getElementById("result").innerHTML=val;
}
error: function(exception) {
alert('Exeption:'+exception);
}
});
});
});
</script>
The code in the file checkevent.php is below
header("Content-Type: application/json", true);
$db = new PDO('mysql:host=localhost;dbname=register;charset=utf8mb4', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$year =$_POST['year'];
$team =$_POST['team'];
$table=$team.$year;
try
{
if ($db->query("SHOW TABLES LIKE '" . $table . "'")->rowCount() > 0)
{
$r=array("result"=>"already stored");
echo json_encode($r);
}
else
{
$r=array("result"=>"continue");
echo json_encode($r);
}
}//end of try
catch(PDOException $e)
{
$r=array("result"=>"error");
echo json_encode($r);
}//end of catch
?>
Please Note: I have stored the file 'addevent.php' (HTML+Script) in the location 'registration/view/'
The checkevent.php file is stored in the location 'registration'
I tried to check if the button click function for add_event button is working by placing an alert inside it. But it doesn't work.
My expected output is if the table exist the span should display 'already stored' else it should say 'continue'
P.S: I am new to using these ajax call,so sorry if this seems silly. Please help to understand these concepts clearly.
Thanks in advance
You change this line :
url: 'checkevent.php',
By this :
url: '../checkevent.php',
Type F12 and inspect your ajax Call in the console to see if everything is OK
EDIT
OK got it. You missed a comma between success and error callbacks, which broke your Javascript...
Please change script to this and it should work:
<script>
$(document).ready(function(){
$("#add_event").click(function(){
var y= $("#year option:selected").text();
var t= $("#team option:selected").text();
$.ajax({
url: '/registration/checkevent.php',
type: 'POST',
dataType: 'json',
data: {year:y , team: t},
success: function(result) {
console.log(result);
var val=result['result'];
document.getElementById("result").innerHTML=val;
},
error: function(exception) {
alert('Exeption:'+exception);
}
});
});
});
</script>
You have a <button> element inside a form. The default type of a button is type="submit" and therefore the form is submitted before the button onclick listener works. Also you need to close a button element with </button>
Try to change it from
<button class=btn name="add_event" id="add_event" />Add Event
to
<button type="button" class=btn name="add_event" id="add_event" >Add Event</button>
As for the ajax URL, if you are running it from a page located in 'registration/view' and you're calling a page located in 'registration', you need to change the url to something like: url: '/registration/checkevent.php'
because the php file isn't located in the same place as the script that's calling it.
Good luck

codeigniter sending a variable from ajax to controller

I'm currently doing an ajax add,update and delete. And I think I'll just start with the delete since it is the easiest and hope that it might help me in the others.
In jquery (this is inside $doc.ready and the event is triggered properly)
if ($a == "Delete")
{
var postid = $(this).next('.postid').val();
$(this).closest(".todo-content").fadeOut();
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?=base_url()?>.index.php/classes/deletepost",
data: {postid: postid},
async: false,
});
}
in html
<form method="post">
<button class="btn" onclick="return confirm('Are you sure to delete this item?')">Delete</button>
<input type="hidden" value="<?php echo $id; ?>" name="postid">
</form>
In controller
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
This is already working but then I am planning on making the crud to ajax. I'm trying to pass the postid from ajax to controller to delete this post. The fadeout already works but only the ajax does not. I'm very new to ajax so I do not know where I am going wrong and I might also ask questions again regarding the other parts of crud.
Fixed!
The problem was the url inside the $.ajax. It returns a garbage.
So I added a script in the header
<script type="text/javascript">
var BASE_URL = "<?php echo base_url();?>";
</script>
And just use BASE_URL in the url: like so url: BASE_URL+'classes/deletepost',
Please Try to follow this:
In Codeigniters View:
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- reading jquery file .. -->
<script type="text/javascript" src="http://localhost/jquery/js_search/jquery.js"></script>
<!--you can write file in extra js file .. it depends on you -->
<script type="text/javascript">
$('#button').click(function(){
// ask for confirmation
var result = confirm("Want to delete?");
// if it is confirmed
if (result) {
// get baseURL and ID using attributes
var base_url = $('#button').attr('baseUrl');
var postid = $('#button').attr('postId');
// make a ajax request
$.ajax({
url: base_url,
type: "POST",
dataType: 'json',
success: function (data) {
if(data){
// Fade out the content id
$('#content_id').closest(".todo-content").fadeOut();
}
}
});
}
});
</script>
in controller:
// You just need to delete the post and return a status code of "200"
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}

javascript ajax and post value is working all together why

I am having a some problem in my java script and to get the request.
This is the HTML
<form method="post" id="searchform">
<div align="center" class="col-md-10">
<input type="text" id= "contentSearch" name="contentSearch" >
</div>
<div class="form-group"><button type="submit" class="btn btn-default" id="submitSearch">
<i class="fa fa-search"></i> Search
</button></div>
</form>
<----Scenario 1 ---->
This script works fine and post the value and as ajax it never reload the page
<script>
$(document).ready(function () {
$("#submitSearch").on('click', function (e) {
e.preventDefault();
e.stopPropagation();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
// Submit data via AJAX§
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
// do i need to do something here !!
}
});
});
});
</script>
When i check the POST value i can see the value is been POST.
The Problem is when i try to get the request data from controller like ---
$post_value = $request->request->get('contentSearch');
print_r($post_value);
OUTPUT : empty
<----Scenario 2 ---->
This script have a problem i think, because it reload the page for returning the result and displaying the value ---
<script>
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
e.preventDefault();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}),
return false;
});
});
</script>
than i am able to get the post value like so--
$post_value = $request->request->get('contentSearch');
But the problem is in the second script the page is always loading when return the request which is not a ajax behave.
And in the first script i think because of the **e.preventDefault();** i am not getting the POST value in my controller.
Expected result ---
Option 1 : Do something so i can get the POST value in my controller
Option 2 : Fix this script so the page do not load to return the result and display
I am working on symfony framework .
Can someone please help me to fix this problem, i am really getting sick of to solve this problem.
Thanks a lot on advanced.
Like I mentioned in the comments, you need to be targeting the submit on the form. Not a click event. When targeting the click you are firing both the click and submit events, hence the reload.
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}
});
return false;
});
});

Submitting Form in AJAX in Laravel 5

<p style="padding:10px">Add your Facebook Account</p>
{!! Form::open(['route'=>array('agencyNewPlatform',$influencer->getUser()->user_type_id, '1')]) !!}
<input type="text" name="handle" placeholder="Profile Name" />
<p style="padding-top:25px;padding-bottom:5px">
<button type="submit" class="btn btn-success plat_add">Save</button>
</p>
{!! Form::close() !!}
I am trying to submit this form through AJAX, but I don't know how to define myurl. The following source code may contain other errors, too. Please help me.
$('.plat_add').click(function(event) {
event.preventDefault();
var myurl = ?????????????;
var date = new Date();
myurl = myurl+"?noche="+date.getTime();
mydata = $(this).closest('form').serialize();
var jqxhr = $.ajax({
url: myurl,
type:'GET',
dataType:'json',
data: mydata,
}).done(function() {
var response = JSON.parse(jqxhr.responseText);
$("#table3").append("<tr id=" + response.platform_id + "plat><td>" + response.plat_name + "</td><td>" + response.handle + "</td><td><a class='plat_remove' href=" + response.link + ">Remove</a></td></tr>");
}).fail(function() {
alert("Add platform fail!" + jqxhr.responseText);
});
});
This are my route and controller functions:
Route:
Route::get('influencer/update/{user_type_id}/add_plat/{platform_id}', ['as'=>'agencyNewPlatform','uses'=>'AgentController#postPlatform']);
and Controller:
public function postPlatform(InfluencerAddPlatformRequest $request, $user_type_id, $platform_id)
{
$user = Auth::user();
$agent = $user->getTypeModel();
$influencer = $this->influencer->findById($user_type_id);
$handle = $request->input('handle');
$result = DB::table('influencers_platforms')->insert(['influencer_id'=>$user_type_id, 'platform_id'=>$platform_id, 'platform_handle'=>$handle]);
$plat_name = DB::table('platforms')->where('id', $platform_id)->first()->name;
if($request->ajax())
{
return response()->json(array('responsecode'=>'1','action'=>'add', 'plat_name'=>$plat_name, 'handle'=>$handle, 'link'=>route('agencyDeletePlatform',[$influencer->getUser()->user_type_id, $platform->id]), 'result'=>$result,'platform_id'=>$platform_id));
}
}
I am really stuck at here; thank you all in advance!
First put an id to your form, thas better than try to catch the event from the submit button, remember, press enter on any field will gonna submit your form without press the submit button.
view
{!! Form::open(['route'=>array('agencyNewPlatform',$influencer->getUser()->user_type_id, '1'), 'method' => 'get' 'id' => 'form']) !!}
<input type="text" name="handle" placeholder="Profile Name" />
<p style="padding-top:25px;padding-bottom:5px">
<button type="submit" class="btn btn-success plat_add">Save</button>
</p>
{!! Form::close() !!}
After here the script i often use to send an ajax request:
javascript
$("#form").submit( function (event) {
event.preventdefault();
var url = $(this).attr('action'); //here you have to options
//get the url from the action on the form
//or declare an <a href="{{route(your.route)}}"> and get it from the href
var data = $(this).serialize();
$.get(url, data, function(result) {
//do if result is ok
}).fail(function (){
//do if fails
});;
});
Edit:
i se you have a var date = new Date(); and you want to put it on your vars, first, the url even if is a get request dont contain your data info.
You need to pass it into your data var.
lets learn
a default get url:
myurl.com?var=value&var2=value2
When you do an ajax request this url is divided in two pieces
the url and the data
var url = "myurl.com";
var data = "var=value&var2=value2";
the jquery will gonna merge that two variables after.
So, lets learn how .serialize() works, when you call this method, the result will be in the data format.
so if you want to add another variable its simple:
data+="&newvar="+var;
now data contain:
data = "var=value&var2=value2&newvar=valuefromvar"
so your code will be like:
$("#form").submit( function (event) {
event.preventdefault();
var date = new Date();
var url = $(this).attr('action'); //here you have to options
//get the url from the action on the form
//or declare an <a href="{{route(your.route)}}"> and get it from the href
var data = $(this).serialize();
data+="&noche="+date.getTime(); //here the change
$.get(url, data, function(result) {
//do if result is ok
}).fail(function (){
//do if fails
});;
});
Another recomendation if you work with route names, the correct form to put it is separating words with . not in camelcase format, and build with a subject after and action (if its necesary) like:
user.show
user.update
agency.create.platform
In the controller, I know maybe its too late to make big changes on your application, but in another projects why you dont try to use eloquent and orm relationships instead of fluent DB, this will gonna make your code more flexible, and your controller logic maybe will not take more than 10 lines.
I may have not fully understood your question so please make a comment if I didn't address something properly.
As a side note, formatting your code (indentation) and using consistency throughout your code (such as declaring an array, i.e. use array() or [] not both) will go a long way in making your code readable when you or someone else returns to it, see the changes I made in terms of formatting.
view
I have added an id myForm to the form here, see second argument of form open() function. Your route is get so I changed the form method to get also. Default for forms is post you can of course change that depending on your needs.
<p style="padding:10px">Add your Facebook Account</p>
{!! Form::open(['route' => ['agencyNewPlatform', $influencer->getUser()->user_type_id, '1'], 'method' => 'get', 'id' => 'myForm']) !!}
<input type="text" name="handle" placeholder="Profile Name" />
<!-- this looks much easier to read on three lines -->
<p style="padding-top:25px;padding-bottom:5px">
<button type="submit" class="btn btn-success plat_add">Save</button>
</p>
{!! Form::close() !!}
javascript
This listens for the form submit event and then you can get the url from the form action attribute
$('#myForm').submit(function(event) {
event.preventDefault();
var $myForm = $(this);
$.get($myForm.attr('action'),
$myForm.serialize,
function(data) {
// your success code
}
).fail(function(data) {
var errors = data.responseJSON;
// show the errors to user
});
});
routes.php
This looks much easier to read on four lines, with indentation. See controller function is getPlatform I changed that because route type is get - it doesn't HAVE to be but you should make them the same so your code is easy to understand.
Route::get('influencer/update/{user_type_id}/add_plat/{platform_id}', [
'as' =>'agencyNewPlatform',
'uses' =>'AgentController#getPlatform'
]);
controller
public function getPlatform(InfluencerAddPlatformRequest $request, $user_type_id, $platform_id)
{
$user = Auth::user();
$agent = $user->getTypeModel();
$influencer = $this->influencer->findById($user_type_id);
$handle = $request->input('handle');
$result = DB::table('influencers_platforms')
->insert([
'influencer_id'=>$user_type_id,
'platform_id'=>$platform_id,
'platform_handle'=>$handle
]);
$plat_name = DB::table('platforms')
->where('id', $platform_id)
->first()
->name;
if($request->ajax()) {
return response()
->json([
'responsecode' => '1',
'action' => 'add',
'plat_name' => $plat_name,
'handle' => $handle,
'link' => route('agencyDeletePlatform', [$influencer->getUser()->user_type_id, $platform->id]),
'result' => $result,
'platform_id' => $platform_id
]);
}
}

Categories

Resources