I am trying to make a button which can load more posts with ajax, but I'm having a problem.
this is my php code:
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
"post_type" => "portfolio",
"posts_per_page" => 2,
"paged" => $paged
);
$query = new WP_Query($args);
if($query->have_posts()) :
?>
<div class="row" id="portfolio-posts">
<?php
$page_layout = get_field("page_layout");
$page_class = "";
if($page_layout == "1") {
$page_class = "col-md-4";
} else {
$page_class = "col-md-3";
}
while($query->have_posts()) : $query->the_post(); ?>
<div class="<?php echo $page_class; ?> single-post">
<div class="project-con project2-con">
<div class="overlay">
<div class="overlay-inner">
<h3><?php the_title(); ?></h3>
<hr>
<span><?php echo get_the_term_list( $post->ID, 'masonry-categories', '', ', '); ?></span>
</div>
</div>
<?php
if(has_post_thumbnail()) {
the_post_thumbnail("portfolio");
}
else {
echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/assets/images/default.png" />';
}
?>
</div>
</div>
<?php endwhile; ?>
</div>
<div class="button">
load more
</div>
<?php endif; ?>
and this is my javascript code:
var page = 1;
var loadMorePosts = jQuery('#load-more-posts').text();
function loadMore() {
page++;
$.ajax({
type: "GET",
url: './page/' + page,
beforeSend: function () {
jQuery('#load-more-posts').html("<i class='fa fa-spinner fa-spin'></i>");
},
complete: function () {
},
success: function (data) {
var $data = jQuery(data).find('.single-post,.single-blog');
if ($data.length > 0) {
jQuery('#load-more-posts').html(loadMorePosts);
jQuery('#portfolio-posts,#blog-posts').append($data);
$data.css("display", "none");
$data.fadeIn("slow");
}
else {
jQuery('#load-more-posts').html('No More Posts');
}
},
error: function () {
jQuery('#load-more-posts').html('No More Posts');
}
});
}
The error message I'm getting is:
Failed to load resource: the server responded with a status of 404
(Not found)
Instead of using the rewritten URL in Ajax:
url: './page/' + page
Use the URL with paged parameter, like so:
url: '.?paged=' + page
This problem happens a lot, because of .htaccess redirects. I've managed to solve the exact problem using these kinds of URLs.
Related
Framework - Codeigniter
I need to populate multiple drop down lists on view onload function. Currently I use five Ajax requests to populate five dropdowns. I think this is inefficient and will reduce my application performance and increase the bandwidth usage. Is there any efficient alternative way to do this? (like populate them all in single Ajax call)
In my View
$(document).ready(function() {
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/Pharmacy_elements/fetch_main_catagories",
method:'get',
headers: XMLHttpRequest + new Date().getTime(),
success:function(data){
$('#main_catagory').html(data);
}
})
}
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/Pharmacy_elements/fetch_sub_catagories",
method:'get',
headers: XMLHttpRequest + new Date().getTime(),
success:function(data){
$('#sub_catagory').html(data);
}
})
}
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/Pharmacy_elements/fetch_serving_types",
method:'get',
headers: XMLHttpRequest + new Date().getTime(),
success:function(data){
$('#common_serving_type').html(data);
}
})
}
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/Pharmacy_elements/fetch_approved_suppliers",
method:'get',
headers: XMLHttpRequest + new Date().getTime(),
success:function(data){
$('#supplier_name').html(data);
}
})
}
})
My Controller
public function fetch_mother_companies()
{
$output = '';
$this->load->model('Pharmacy_model');
$data = $this->Pharmacy_model->fetch_mother_companies();
// $output .='<option value=0>All</option>';
if($data->num_rows()>0){
foreach($data->result() as $row){
$output .='
<option value='.$row->id.'>'.$row->company_name.'</option>';
}
}
else {
}
echo $output;
}
public function fetch_main_catagories()
{
$output = '';
$this->load->model('Pharmacy_model');
$data = $this->Pharmacy_model->fetch_main_catagories();
// $output .='<option value=0>All</option>';
if($data->num_rows()>0){
foreach($data->result() as $row){
$output .='
<option value='.$row->id.'>'.$row->category_name.'</option>';
}
}
else {
}
echo $output;
}
public function fetch_sub_catagories()
{
$output = '';
$this->load->model('Pharmacy_model');
$data = $this->Pharmacy_model->fetch_sub_catagories();
// $output .='<option value=0>All</option>';
if($data->num_rows()>0){
foreach($data->result() as $row){
$output .='
<option value='.$row->category_id.'>'.$row->category_name.'</option>';
}
}
else {
}
echo $output;
}
I used following script in my rout file.
Route::get('/tasks', 'appointmentController#exportCsv')
I used the following Js script Html Clickable button in blade template
<script>
function exportTasks(_this) {
let _url = $(_this).data('href');
window.location.href = _url;
}
</script>
<span data-href="./tasks" id="export" class="btn btn-success btn-sm" onclick="exportTasks(event.target);">Export Client Email</span>
I used the following script in my controller. I cant find where is the script problem. CSV file are not download include with the data.
public function exportCsv(Request $request)
{
$fileName = 'tasks.csv';
$tasks = Clientinformation::all();
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$columns = array('customerName', 'email', 'cell1', 'cell2', 'landNumber');
$callback = function() use($tasks, $columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach ($tasks as $task) {
$row['customerName'] = $task->customerName;
$row['email'] = $task->assign->email;
$row['cell1'] = $task->cell1;
$row['cell2'] = $task->cell2;
$row['landNumber'] = $task->landNumber;
fputcsv($file, array($row['customerName'], $row['email'], $row['cell1'], $row['cell2'], $row['cell2'], $row['landNumber'] ));
}
fclose($file);
};
return response()->stream($callback, 200, $headers);
}
here using ajax i am click the forget button and sending mail to particular email ,but i am getting the error Fail what is the problem i am not getting please any one help me below i shown form and controller
Form
<div class="field-wrap">
<label class="view-label">Email Address</label>
<input type="email" placeholder="Email Address" name="email" id="email" class="input-control inputstyle" value="<?php echo set_value('email'); ?>"/>
<span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<!--<div id='errorDiv' class='col-xs-12 pull-right'> </div>-->
<div class="field-wrap">
<input type="password" placeholder="Password" class="inputstyle" name="password" id="password" value="<?php echo set_value('password'); ?>"/>
<span class="text-danger"><?php echo form_error('password'); ?></span>
<a href="javascript:void(0)" class="btn btn-link btn-nobg" id="btn-show-forgot" >Forgot ?</a>
</div>
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn-show-forgot").click(function () {
//e.preventDefault();
var email = $("#email").val();
// var password= $("#password").val();
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>" + "index.php/Login_cntrl/sendmail",
data: {email: email},
success: function (data)
{
alert('Successfully send a mail');
},
error: function ()
{
alert('fail');
}
});
});
});
</script>
Controller
public function sendmail() {
$this->form_validation->set_rules('email', 'Email or number', 'required|min_length[10]|max_length[30]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
} else {
$data['email'] = $this->input->post('email');
$findemaill = $this->Login_model->getUserInfoByEmail($data['email']);
if (!empty($findemaill)) {
// $this->Login_model->getUserInfo('$id');
// $this->session->set_userdata('forgot_password_flag', 'yes');
$emailTo = $this->input->post('email');
$this->session->set_userdata('findemaill', $emailTo);
// $this->session->userdata('findemaill');
$data['result'] = $this->Login_model->forgot_pass_retrive($emailTo);
$id = $data['result']->id;
$this->session->set_userdata('idd', $id);
$six_digit_random_number = mt_rand(100000, 999999);
$this->session->set_userdata('otp', $six_digit_random_number);
$this->load->model('Login_model');
$pass['pass'] = $this->Login_model->forgot_pass_retrive($emailTo);
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_port'] = '465';
$config['smtp_timeout'] = '7';
$config['smtp_user'] = 'tworkreport#gmail.com';
$config['smtp_pass'] = '8722248936';
$config['charset'] = 'utf-8';
$config['newline'] = "\r\n";
$config['mailtype'] = 'html'; // or html
$config['validation'] = TRUE; // bool whether to validate email or not
$this->email->initialize($config);
$this->email->from('tworkreport#gmail.com', 'Terasukhintrade');
$this->email->to($emailTo);
$this->email->subject('Reset your password');
$body=$this->load->view('forgotmailer',$data,TRUE);
$this->email->message('Use the following OTP to reset password '.$body );
$this->email->send();
echo $this->email->print_debugger();
$this->load->view('login',$data);
} else {
$this->session->set_flashdata('message', ' Email address not found!');
$this->load->view('login',$data);
}
}
}
While using ajax you always needs to return value. You can not use $this->load->view('login');
also in ajax function needs to be altered given below.
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>" + "index.php/Login_cntrl/sendmail",
data: {'email': email},
dataType: 'json',
success: function(data) {
alert('Successfully send a mail');
},
error: function() {
alert('fail');
}
});
public function sendmail() {
$this->form_validation->set_rules('email', 'Email or number', 'required|min_length[10]|max_length[30]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
} else {
$data['email'] = $this->input->post('email');
$findemaill = $this->Login_model->getUserInfoByEmail($data['email']);
if (!empty($findemaill)) {
// $this->Login_model->getUserInfo('$id');
// $this->session->set_userdata('forgot_password_flag', 'yes');
$emailTo = $this->input->post('email');
$this->session->set_userdata('findemaill', $emailTo);
// $this->session->userdata('findemaill');
$data['result'] = $this->Login_model->forgot_pass_retrive($emailTo);
$id = $data['result']->id;
$this->session->set_userdata('idd', $id);
$six_digit_random_number = mt_rand(100000, 999999);
$this->session->set_userdata('otp', $six_digit_random_number);
$this->load->model('Login_model');
$pass['pass'] = $this->Login_model->forgot_pass_retrive($emailTo);
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_port'] = '465';
$config['smtp_timeout'] = '7';
$config['smtp_user'] = 'tworkreport#gmail.com';
$config['smtp_pass'] = '8722248936';
$config['charset'] = 'utf-8';
$config['newline'] = "\r\n";
$config['mailtype'] = 'html'; // or html
$config['validation'] = TRUE; // bool whether to validate email or not
$this->email->initialize($config);
$this->email->from('tworkreport#gmail.com', 'Terasukhintrade');
$this->email->to($emailTo);
$this->email->subject('Reset your password');
$body=$this->load->view('forgotmailer',$data,TRUE);
$this->email->message('Use the following OTP to reset password '.$body );
$this->email->send();
echo $this->email->print_debugger();
$data['is_data'] = '1';
$data['msg'] = 'Successfully send a mail';
echo json_encode($data);
} else {
$data['is_data'] = '0';
$data['msg'] = 'Email address not found!';
echo json_encode($data);
}
}
}
Is it possible to get data from file then add it in my database in mysql. I'm using codeigniter. My code only asks inputs from the user. Please help please. It is required by my professor so that if the user wants to input for example 100 data he/she doesn't manually input the data thus get the data from another database.
my view page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Students</title>
</head>
<body>
<div id="container">
<h1>Student's Page</h1>
<div id="body">
<div id="div2">
<?php
echo form_open('main/addToRegistrar');
?>
<br>
<?php
echo "<p>ID: ";
echo form_input('id');
echo "</p>";
echo "<p>First Name: ";
echo form_input('first_name');
echo "</p>";
echo "<p>Middle Name: ";
echo form_input('middle_name');
echo "</p>";
echo "<p>Last Name: ";
echo form_input('last_name');
echo "</p>";
echo "<p>";
echo form_submit('ADD', 'ADD');
echo "<p>";
echo form_close();
?>
<a href='<?php echo base_url()."main/admin"; ?>'>Home!</a>
</div>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds </p>
</div>
</body>
</html>
my controller
public function addToRegistrar(){
if($this->session->userdata('is_logged_in')){
$this->load->model('model_users');
$this->model_users->addToRegistrar();
$this->load->view('view_addAteneoStudents');
} else{
redirect('main/restricted');
}
}
my model
public function addToRegistrar(){
$fname = $this->input->post('first_name');
$mname = $this->input->post('middle_name');
$lname = $this->input->post('last_name');
$id = $this->input->post('id');
$data = array(
'id' => $id,
'first_name' => $fname ,
'middle_name' => $mname ,
'last_name' => $lname
);
if($this->db->insert('registrar', $data)){
echo "Successfully added";
}
}
You must have an option to upload files (csv recommended) and upload it to your server. Here is a quick how:
view:
<html>
<body>
<form action="<?php echo base_url();?>" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
controller:
public function addToRegistrar()
{
if($this->session->userdata('is_logged_in')){
$this->load->model('model_users');
$this->model_users->addToRegistrar();
$this->load->view('view_addAteneoStudents');
} else{
redirect('main/restricted');
}
}
model:
function addToRegistrar()
{
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
$filename = "upload/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $filename);
//parse the uploaded file and insert to database
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = $row;
}
$this->db->insert_batch('registrar', $data);
fclose($handle);
}
}
}
}
NOTE: Your csv file should have the same column count as your database table 'registrar'.
More about reading csv files here.
I have the following jquery ajax request
$(document).ready(function(){
var friendrequest = $(".friendrequest").val();
$(".afriendreq").click(function(){
$(".afriendreq").hide();
$.ajax({ type: "POST", url:"functions/ajaxfriends.php", data:"friendrequest" ,success:function(result){
$(".cfriendreq").show();
}});
});
});
And it gets the input from here
while ($row = mysql_fetch_array($search)) {
d
?>
<div id="search_container">
<div id="search_image"><img src="<?php echo $row['picture'] ?>"></img></div>
<input type="hidden" value="<?php echo $row['id'] ?>" id="friendrequest" ></input>
<div id="search_name"> <?php echo $row['first_name'] . " " . $row['last_name']; ?> </div>
<div id="search_friend"><a class="afriendreq">Send Friend Request</a><a class="cfriendreq" style="display:none;">Cancel Friend Request</div>
</div><?php
echo "<br />";
}
?>
Unfortunately it's not working though. Can anyone find the problem because it's bugging me?
Also the functions/ajaxfriends.php is
<?php
include 'functions.php';
if (isset($_POST['friendrequest'])){
$friendrequest= $_POST['friendrequest'];
$friendrequest= filter ($_POST['friendrequest']);
$sql_connectfriend = " INSERT INTO friends (`useridone` ,`useridtwo` ,`request`) VALUES ('$_SESSION[user_id]', '$friendrequest', '1' ";
$search = mysql_query($sql_connectfriend, $link) or die("Insertion Failed:" . mysql_error());
}
?>
Can anyone see why?
Thanks in advance.
Try:
$.ajax({
url: 'functions/ajaxfriends.php',
type: 'POST',
data: { friendrequest: friendrequest },
success: function(result) {
$('.cfriendreq').show();
}
});