Search a post in Wordpress and load via AJAX - ajax

I have this structure in wordpress.
<input type="text" id="search_subject">
<button id="btn_search_subject">Send</button>
<div id="results_search"></div>
<button id="back">Previous</button>
<button id="next">Next</button>
I wanna search a word and via AJAX load the first result in the div #results_search
I lookup some tutorials, but, I didn´t quite understand, some tutorials include all the coode in the functions.php file, and others divide the coding in the ajax.js file.
It could be a search just in the titles of the posts

Here is HTML code
<input class="form-control" placeholder="Search" id="search_posts" name="_posts" type="text" autocomplete="off" value="">
<input type="hidden" value="<?php echo admin_url('admin-ajax.php');?>" id="ajax_url_input">
Here is Jquery Code
jQuery( "#search_posts" ).keyup( function() {
var search_posts = jQuery(this).val();
var ajax_url = jQuery('#ajax_url_input').val();
jQuery.ajax({
type:'POST',
url: ajax_url,
data: {
action: 'search_data',
search_posts: search_posts,
},
beforeSend: function(){
},
success:function(data){
}
});
});
Here is PHP Function for Ajax
function search_data() {
$search = '';
if(isset($_POST['search_posts'])){
$args = array(
'posts_per_page' => -1,
'post_type'=> 'posts',
'post_status'=> 'publish',
's' => $_POST['search_posts']
);
}
$services_data = get_posts( $args );
}
add_action('wp_ajax_search_data', 'search_data');
add_action('wp_ajax_nopriv_search_data', 'search_data');
This code will search text in post title and in post content.

Related

Success function not being called after making AJAX request codeigniter

When I make an AJAX call from view and pass form data to the controller. I get a couple of problems. First, the code inside success is never executed, and second, the page is being refreshed even though it is an AJAX call. Can anyone tell me where am I doing wrong?
I have seen a lot of questions since yesterday but none of them were able to solve my problem.
Model code
public function insert_user($name, $email) {
$data = array();
$data['name'] = $name;
$data['email'] = $email;
$data['created_at'] = date('y-m-d');
$this->db->insert('all_users', $data);
return true;
}
Controller code
public function insert_user () {
$data = $this->input->post();
$name = $data['name'];
$email = $data['email'];
$this->User_model->insert_user($name, $email);
$this->load->view('view');
}
Ajax request code
const insertBtn = $(".insert-btn");
insertBtn.on("click", function () {
const name = $(".insert-form input[type=name]");
const email = $(".insert-form input[type=email]");
$.ajax({
url: "<?php echo base_url() ?>index.php/Users/insert_user",
type: "post",
data: {name, email},
dataType: "json",
success: function () {
$("body").append("Request made successfully");
}
})
});
My form looks something like this:
<form class="insert-form" action="<?php echo base_url() ?>index.php/Users/insert_user" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button class="insert-btn">Insert Data</button>
</form>
NOTE: I am able to successfully insert data into the database.
The browser is submitting the form before your AJAX code gets a chance to run/finish.
Instead of binding an event to the click event of the button, you want to bind to the submit event of the form. Then you want to cancel the browser's default action. This is done via the e.preventDefault(); method.
Also, dataType: "json" is not needed here. dataType tells jQuery what kind of data your AJAX call is returning. You generally don't need it as jQuery can automatically detect it. Plus, if you are not returning a JSON document, then this may cause a problem.
const insertForm = $(".insert-form");
insertForm.on("submit", function (e) {
const name = insertForm.find("input[type=name]");
const email = insertForm.find("input[type=email]");
e.preventDefault();
$.ajax({
url: "<?php echo base_url() ?>index.php/Users/insert_user",
type: "post",
data: {name, email},
success: function () {
$("body").append("Request made successfully");
}
})
});
Controller code
public function insert_user () {
$data = $this->input->post();
$name = $data['name'];
$email = $data['email'];
$data = $this->User_model->insert_user($name, $email);
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
Ajax request code
const insertBtn = $(".insert-btn");
insertBtn.on("click", function () {
const name = $(".insert-form input[type=name]");
const email = $(".insert-form input[type=email]");
$.ajax({
url: "<?php echo base_url() ?>Users/insert_user", // <?php echo base_url() ?>controller_name/function_name
type: "post",
data: {name, email},
dataType: "json",
success: function () {
$("body").append("Request made successfully");
}
})
});
form looks something like this:
<form class="insert-form" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button class="insert-btn">Insert Data</button>
</form>
The page was being refreshed because I had a button that was acting as submit button on changing it to the input of the type button it does not submits the form and we don't see the page being refreshed. And also the AJAX request made also runs successfully.
<form class="insert-form" action="<?php echo base_url() ?>index.php/Users/insert_user" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<input type="button" class="insert-btn" value="Insert Data">
</form>

Laravel 5.5 Multilanguage validation

Please tell me, I ran into a problem. There is a site based on Laravel 5.5. The site has a multilanguage (two languages en/ru). For multilanguage I'm using:
dimsav/laravel-translatable
mcamara/laravel-localization
Added language files to the directory resources/lang/ru. The problem is the validation of the form. The site has a feedback form in the modal window, working with ajax (sending and validating), error messages are displayed only in the default language, the default language is en. I tried to send data from the form without the help of ajax, everything works well, messages are displayed in both Russian and English.
reoutes/web.php
Route::group(['prefix' => LaravelLocalization::setLocale()], function(){
Route::get('/', 'PagesController#getProfile')->name('profile');
Route::get('/skills', 'PagesController#getSkills')->name('skills');
Route::get('/portfolio', 'PagesController#getPortfolio')->name('portfolio');
Route::get('/resume', 'PagesController#getResume')->name('resume');
Route::post('/contact', 'PagesController#contact');
});
controller
public function contact(Request $request){
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
if ($validator->passes()) {
Mail::to('mycontactform#mail.ru')->send(new Contact($request));
return response()->json(['success'=>'Message sent successfully!']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
js
$(document).ready(function() {
$(".btn-send-message").click(function(e){
e.preventDefault();
$.ajax({
url: "/contact",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
});
var $success_msg = $(".print-success-msg");
var $error_msg = $(".print-error-msg");
function printSuccessMsg() {
$success_msg.html('Message sent successfully!');
$success_msg.css('display','block');
$success_msg.delay(5000).fadeOut(350);
$('#contact-form')[0].reset();
}
function printErrorMsg (msg) {
$error_msg.find("ul").html('');
$error_msg.css('display','block');
$.each( msg, function( key, value ) {
$error_msg.find("ul").append('<li>'+value+'</li>');
});
$error_msg.delay(5000).fadeOut(350);
}
});
form
<div class="modal-body col-md-8 offset-md-2">
<div class="alert alert-danger print-error-msg" style="display:none">
<strong>Errors:</strong>
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display:none"></div>
{!! Form::open(['id'=>'contact-form']) !!}
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Your Name">
</div>
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Your Email">
</div>
<div class="form-group">
<textarea class="form-control" name="message" id="message" rows="3"></textarea>
</div>
<button type="button" class="btn btn-success btn-send-message"><i class="fas fa-paper-plane"></i>
Send Message <span id="loading" style="display: none;"><img class="loader"
src="{{ asset('images/loading.gif') }}"></span>
</button>
{!! Form::close() !!}
</div>
Use LaravelLocalization::getLocalizedURL() which returns an URL adapted to $locale.
So your ajax code will be.
$.ajax({
url: "{{ LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(),'/contact') }}",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
When you return your response try to use this helper __('translated_string')
To use this helper, you have to create some translate.php file in those folders resources/lang/en and resources/lang/en
For example:
File resources/lang/en/translate.php should contain this array
return [
'success_message' => 'Message sent successfully!',
];
File:
resources/lang/ru/translate.php should contain this array
return [
'success_message' => 'Сообщение успешно отправлено!',
];
For example:
return response()->json(['success'=> __('translate.success_message') ]);
To get some translated string, use dot notation for this helper;
Laravel localization helper

Autocomplete dropdown in codeigniter doesn't works

I'm still new using jquery in codeigniter so i hope you can gladly help me.
I want to create autocomplete dropdown where when one option of autocomplete is selected, it will show other related fields.
The output become like this, there's no value to display
And this is my codes :
Model
function search_mtk($kode_mtk){
$this->db->like('kode_mtk', $kode_mtk , 'both');
$this->db->order_by('kode_mtk', 'ASC');
$this->db->limit(5);
return $this->db->get('m_mata_kuliah')->result();
}
Controller
public function get_mtk(){
if (isset($_GET['term'])) {
$result = $this->kit_model->search_mtk($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row)
$arr_result[] = array(
'kode' => $row->kode_mtk,
'nama' => $row->nama_mtk,
);
echo json_encode($arr_result);
}
}
}
<script type="text/javascript">
$( "#kode_mtk" ).autocomplete({
source: "<?php echo base_url('fak/kit/get_mtk/?');?>",
select: function (event, ui) {
$('[name="kode_mtk"]').val(ui.item.kode);
$('[name="nama_mtk"]').val(ui.item.nama);
}
});
});
</script>
<?php echo form_open_multipart('fak/kit/file_data');?>
<div class="form-group">
<label for="program">Kode Matakuliah <span style="color:#FF0000">*</span>:</label>
<input type="text" class="form-control" id="kode_mtk" name="kode_mtk" placeholder="Type course code" />
</div>
<div class="form-group">
<label for="program">Nama Matakuliah<span style="color:#FF0000">*</span>:</label>
<input type="text" class="form-control" name="nama_mtk" placeholder="Type course name" />
</div>
<button type="submit" class="btn btn-success">Submit</button>
I hope anyone can help me with this.
Your code seems working fine but the label value not showing in the drop-down. just add value and label key value in the array to check its working or not.
Your code should be like below
$arr_result[] = array(
'kode' => $row->kode_mtk,
'nama' => $row->nama_mtk,
'value' => $row->nama_mtk,
'label' => $row->nama_mtk,
);
also, add the following call back function inside autocomplete jquery function
$( "#kode_mtk" ).autocomplete({
source: "<?php echo base_url('fak/kit/get_mtk/?');?>",
select: function (event, ui) {
$('[name="kode_mtk"]').val(ui.item.kode);
$('[name="nama_mtk"]').val(ui.item.nama);
},
response: function(event, ui){
if(ui.content.length === 0){
console.log('No results loaded!');
}else{
console.log('success!');
}
},
});
});

ajax alert is not working using codeigniter

I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.

jquery ajax form validation not working in chrome

I have the simple task of validating a user has entered the first name. This is working in most browsers but chrome doesn't seem to be getting a response from ajaxfirstname.php. Here is the script:
jQuery(document).ready(function () {
var validatefirst_name = jQuery('#validatefirst_name');
jQuery('#first_name').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validatefirst_name.removeClass('error').html('<span style="margin-left: 5px;"><img src="images/loader.gif" height="16" width="16" /></span>');
this.timer = setTimeout(function () {
jQuery.ajax({
url: "ajaxfirstname.php",
data: "action=check_first_name&first_name=" + t.value,
dataType: "json",
async: false,
type: "post",
success: function (j) {
validatefirst_name.html(j.msg);
}
});
}, 200);
this.lastValue = this.value;
}
});
});
and my html
<label for="first_name">First Name</label>
<input id="first_name" name="first_name" type="text" id="first_name" value="<?php
$name = explode(' ',$this->my->name);
echo $name[0];
?>">
<span id="validatefirst_name"></span>
I opened up the developer tool but I don't see any error on this particular script. Does anyone have suggestions on this? Does the above code look correct? Would Chrome have any issues with it? Thanks in advance.
May be its because you have used id in textbox twice ["id="first_name"].Please change this and let me know..
id="first_name" name="first_name" type="text" id="first_name" value="my->name);

Resources