insert Using ajax But page refreshing on submit why? - codeigniter

Controller code I have :
<?php
class Ajax_cntrl extends CI_controller{
public function index(){
$this->load->view('ajax_view');
$insert = array(
'name' => $this->input->post('name'),//<-- also not able to get this id from ajax post request
'pass' => $this->input->post('pass'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'address' => $this->input->post('address'),
);
$this->db->insert('form',$insert);//<--insert item into cart
$query;// to insert into database
//redirect('shop');
}
}
?>
view code I have ::
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<form action="" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Pass</td>
<td><input type="password" name="pass" id="pass"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile" id="mobile"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" id="address"></td>
</tr>
<tr>
<td><input type="submit" name="submit" id="submit"></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var form_data = { //repair
id: id,
name: $('#name_' + id).val(),
pass: $('#pass' + id).val(),
email: $('#email' + id).val(),
mobile: $('#email' + id).val(),
address: $('#email' + id).val()
};
$.ajax({
type:'post',
url:"<?php echo site_url('ajax_cntrl/index'); ?>",
data: form_data, // $(this).serialize(); you can use this too
success: function(msg) {
alert("success..!! ");
}
});
return false;
});
</script>
problem is that when i am submitting the form it refreshing the browser ajax not working where is the fault m not able to understand please help me related in this why ajax call is not working there and is that a gud way to implement ajax with codeigniter ?? if yes then y its not working

Use below code, this will fix your issue.
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var form_data = {//repair
name: $('#name').val(),
pass: $('#pass').val(),
email: $('#email').val(),
mobile: $('#mobile').val(),
address: $('#address').val()
};
$.ajax({
type: 'post',
url: "<?php echo site_url('ajax_cntrl/index'); ?>",
data: form_data,
dataType: 'json',
success: function(msg) {
alert("success..!! ");
}
});
return false;
});
});
</script>
Let me know if it not works for you.

Related

Unable to send ajax data to Laravel controller

I'm just trying to send the editable table row data to the controller onClick of the Save button, update that data in the database, and return success.
But I cannot display the data inside the controller function of laravel. Data inside saveMe function is coming as desired as shown in below screenshot but it is not going to the controller
<table id="customersTable" class="table table-bordered table-responsive-md table-striped text-center" style="border-style: solid; border-color:red">
#php
$customersData = Session::get('data');
$issues = Session::get('issues');
#endphp
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
<th>Address</th>
<th>Name</th>
</tr>
</thead>
<tbody id="bodyData">
#foreach ($customersData as $key => $data)
<form action="ajaxform">
<!-- This is our clonable table line -->
<tr>
<td>{{$key}}</td>
<td name="name" class="pt-3-half name" contenteditable="true"
value={{$data['name']}} data-id={{$key}}>
{{$data['name']}}
</td>
<td name="email" class="pt-3-half email" contenteditable="true"
value={{$data['name']}} data-id={{$key}}>
{{$data['email']}}
</td>
<td>
<div class="test">
<span class="table-save">
<button type="button" onclick="saveMe(this)" class=" btn btn-secondary btn-rounded btn-sm my-0 saveBtn">
Save
</button>
</span>
</div>
</td>
</tr>
</form>
#endforeach
</tbody>
</table>
JavaScript function
<script>
function saveMe(params) {
var tr = $(this).closest("tr"); //get the parent tr
var name = $(params).closest("tr").find(".name").text();
var email = $(params).closest("tr").find(".email").text();
console.log(name);
console.log(email);
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
_token:'{{ csrf_token() }}',
value: {
'name' : name,
'email' : email,
'contact' : contact,
'address' : address,
},
},
success: function(data){
alert("success");
}
});
}
Function inside the controller
class CustomersController extends Controller
{
public function saveSingleRecord(Request $request)
{
// $name = $_GET['name'];
$name = $request->name;
dd($name); // <------------------ Not showing anything
// return response()->json($name);
}
}
Route inside web.php
Route::post('/customers/saveSingleRecord/', [CustomersController::class, 'saveSingleRecord']);
In your ajax request you are passing your data inside value attribute so it's not showing. If you try $request->value['name'] then it will show you the name. If you want to get name directly in request object then pass as like below.
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
_token:'{{ csrf_token() }}',
'name' : name,
'email' : email,
'contact' : contact,
'address' : address,
},
success: function(data){
alert("success");
}
});
The correct way to send ajax is below
$.ajax({
url: '/customers/saveSingleRecord',
type: 'GET',
data: {
name : name,
email : email,
contact : contact,
address : address,
_token :'{{ csrf_token() }}',
},
success: function(data){
alert("success");
}
});
Basically you set key value pair within data.

How to prevent ajax request before clicking on OK button of onclick="confirm(' ')" message?

$(document).ready(function(){
$(document).on('click', '.dlt', function () {
var id = $(this).attr('data-id');
var token= '{{ csrf_token() }}';
$.ajax({
method: 'post',
url: '{{route('product.delete')}}',
data: {id:id, _token:token},
success: function (response) {
location.reload();
}
});
});
});
<tbody>
#if($products->count()>0)
#foreach($products as $product)
<tr>
<td class="p_name">{{$product->name}}</td>
<td class="p_details">{{$product->details}}</td>
<td class="p_price">{{$product->price}}</td>
<td><a class="add" data-id="{{$product->id}}" title="Add" data-toggle="tooltip" style="display: none"><i class="fa fa-book"></i></a>
<a class="edit" title="Edit" data-toggle="tooltip"><i class="fa fa-edit"></i></a>
<a class="dlt" onclick="confirm('Are you sure to delete it?')" title="Delete" data-toggle="tooltip" data-id="{{$product->id}}"><i class="fa fa-trash"></i></a>
</td>
</tr>
#endforeach
#else
<tr>
<td colspan="4" class="text-center bg-danger">No Product Data Found</td>
</tr>
#endif
</tbody>
Although I click on Cancel button of Confirm() message, but onclick ajax request already done. How to prevent it until I click on OK button of confirm() message?
Inside a function, you have to use this script -
var result = confirm("Want to delete?");
if (result) {
//Logic to Ajax
}
In your code
$(document).ready(function() {
$(document).on('click', '.dlt', function() {
var result = confirm("Want to delete?");
if (result) {
//logic to AJAX
var id = $(this).attr('data-id');
var token = '{{ csrf_token() }}';
$.ajax({
method: 'post',
url: '{{route('
product.delete ')}}',
data: {
id: id,
_token: token
},
success: function(response) {
location.reload();
}
});
}
});
});

Get database record using AJAX, Knockout and JSON

I am fairly new to Knockout and Entity Framework and I have a problem where I cannot seem to output any JSON from an MVC 4 controller action via an AJAX call using Knockout onto an html page.
The table includes fields Email and RegsitrationNumber, these are used to validate the user.
If the user exists in the table then their country is displayed on the screen.
The profiler states a Status Code of 200 i.e OK. Can anyone help?
HTML ------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="./Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div>
<div>
<h2 id="title">Login</h2>
</div>
<div>
<label for="email">Email</label>
<input data-bind="value: $root.Email" type="text" title="Email" />
</div>
<div>
<label for="registrationnumber">Registration Number</label>
<input data-bind="value: $root.RegistrationNumber" type="text" title="RegistrationNumber" />
</div>
<div>
<button data-bind="click: $root.login">Login</button>
</div>
</div>
<table id="products1" data-bind="visible: User().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
<script src="./Scripts/knockout-2.2.0.js"></script>
<script src="./Scripts/knockout-2.2.0.debug.js"></script>
<script src="./Scripts/functions.js"></script>
</body>
</html>
JAVASCRIPT -----
function UserViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Name = ko.observable("Robbie");
self.Email = ko.observable("rob#test.com");
self.Occupation = ko.observable("Designer");
self.Country = ko.observable("UK");
self.RegistrationNumber = ko.observable("R009");
self.UserDate = ko.observable("06-04-2014");
var User = {
Name: self.Name,
Email: self.Email,
Occupation: self.Occupation,
Country: self.Country,
RegistrationNumber: self.RegistrationNumber,
UserDate: self.UserDate
};
self.User = ko.observable(); //user
self.Users = ko.observableArray(); // list of users
//Login
self.login = function ()
{
alert("login");
if (User.Email() != "" && User.RegistrationNumber() != "") {
$.ajax({
url: '/Admin/Login',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(User),
success: function (data) {
self.Users.push(data);
$('#title').html(data.Email);
}
}).fail(
function (xhr, textStatus, err) {
console.log('fail');
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
} else {
alert('Please enter an email and registration number');
}
};
}
var viewModel = new UserViewModel();
ko.applyBindings(viewModel);
ACTION -----
public ActionResult Login(string Email, string RegistrationNumber)
{
var user = from s in db.Users
select s;
user = user.Where(s => s.Email.ToUpper().Equals(Email.ToUpper())
&& s.RegistrationNumber.ToUpper().Equals(RegistrationNumber.ToUpper())
);
if (user == null)
{
return HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}
Looks like your binding is incorrect...
<table id="products1" data-bind="visible: Users().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
User().length should be Users().length.

How to submit form using ajax inside wordpress plugin

I am creating small plugin where i want to submit form data using ajax but it giving response zero.
Here is my call i have added all code in a single file for the time being
file name :index.php
<?php wp_enqueue_script("jquery");?>
<?php
function myaddgallery(){
global $wpdb;
echo "abac";
}
add_action('wp_ajax_myaddgallery' , 'myaddgallery');
add_action('wp_ajax_nopriv_myaddgallery' , 'myaddgallery');
?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#shaGalleryForm').submit(function(e){
// prevent normal submit behaviour
e.preventDefault();
var name = jQuery("#shaGalleryName").val();
alert(name);
//var postData = jQuery("#shaGalleryForm").serialize();
//console.log(postData);
var name = "shalu";
jQuery.ajax({
type: "POST",
url: "http://localhost/plugindevelop/wp-admin/admin-ajax.php",
data : {action: "myaddgallery", name : name},
success: function(response){
//console.log(postData);
console.log("added success");
alert(response);
},
error: function(data){
console.log("fail");
}
});
});
}) ;
</script>
<div class='wrap'>
<h2>Add Gallery</h2>
<p>This is where from you can create new gallery</p>
<form name="shaGalleryForm" id="shaGalleryForm" method="post">
<table class="form-table">
<tr>
<th>Gallery Name</th>
<td>
<input type="text" id="shaGalleryName" name="shaGalleryName">
<p class="description">Add gallery name also please avoid special character</p>
</td>
</tr>
</table>
<p class="submit">
<input type="submit" value="Save" id="shaSaveGallery" name="shaSaveGallery" class="button button-primary">
</p>
</form>
</div>
Try to add die() after you echo the data
function myaddgallery(){
global $wpdb;
echo "abac";
die();
}

how to get the dropdown selected value and send it to controller in codeigniter

am having the following code
view
<script>
$(document).ready(function()
{
$("#Login").click(function()
{
$("#message").html("");
var action = $("#loginform").attr('action');
var login_data = {
username: $("#txt_email").val(),
password: $("#txt_password").val(),
language: $("#language").val(),
is_ajax: 1
};
$.ajax(
{
type: "POST",
url: '<?php echo base_url();?>survey/login',
data: login_data,
success: function(response)
{
if(response == 'success')
{
$("#message").html("<span class='success'>You have logged in successfully!</span><p>Redirecting...</p>");
setTimeout(function() {
window.location.href = '<?php echo base_url();?>survey/communication_letter';
}, 2000);
}
else
{
$("#message").html("<span class='error'>OOPS! Authentication failed</span>");
}
}
});
return false;
});
});
</script>
</head>
<body>
<div id= "header">
<br/>
<p style="text-align:center; color:#8D0F1D;font-size:28px" >Work Environment Survey</p>
</div>
<div id= "bar" style="z-index:1">
<div id="logo" style="z-index:2">
</div>
</div>
<br/>
<br/>
<div id="homemain">
<!--div id="content-login"-->
<br/><br/><br/>
<form action="#" id="loginform" method="post">
<table border="0" align="center" cellpadding="5" cellspacing="10" >
<tr>
<td>Email Id </td>
<td><input type="text" id="txt_email" name="username" /></td>
</tr>
<tr>
<td>Password </td>
<td><input type="password" id="txt_password" name="password" /></td>
</tr>
<tr>
<td>Select Language</td>
<td><select style="width:215px" name="language" id = "language" ><option value="simplified">English with Simplified Chinese</option>
<option value="traditional">English with Traditional Chinese</option>
</select></td>
</tr>
</table>
<input type="image" id="Login" style="position:relative;left:120px" src="<?php echo base_url();?>images/login.png"/>
</form>
and the controller is as follows
public function login()
{
if(isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax']) {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
echo $verify = $this->user_model->user_login($username, $password);
exit;
}
$this->load->view('login');
}
here how can i get the dropdown selected value depending on the language selected i need to open the next page. please someone help me please, thanks.
you can get that by using $_POST or $_REQUEST like you did for username
if(isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax']) {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$language= $_REQUEST['language'];
echo $verify = $this->user_model->user_login($username, $password);
exit;
}
I think this what you want, when user enter correct credential, user will be redirected to the page depending on the language selected by the user. You do not need to access language in your controller because you are redirecting from you login page,
you controller has to be
public function login()
{
if(isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax']) {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$verify = $this->user_model->user_login($username, $password);
if($verify){
echo 1;
}else{
echo 0;
}
}
}
you don't need to load view, as it is an ajax response.
$.ajax(
{
type: "POST",
url: '<?php echo base_url();?>survey/login',
data: login_data,
success: function(response)
{
if(response == 1)
{
$("#message").html("<span class='success'>You have logged in successfully!</span><p>Redirecting...</p>");
setTimeout(function() {
if($("#language").val() == "simplified"){
window.location.href = '<?php echo base_url();?>survey/communication_letter';
}else{
window.location.href = '<?php echo base_url();?>survey/trad_communication_letter'; }
}
}, 2000);
}
else
{
$("#message").html("<span class='error'>OOPS! Authentication failed</span>");
}
}
});
I hope this will help you. please check you development tool (chrome) or firebug (firefox) that your request is going and what is coming in response.
The correct way to grab the selected index value from drop down is
$('#language option:selected').val();
also in your controller you can verify the ajax request using
$this->input->is_ajax_request()

Resources