This my code for send realtime message.
After send message, it is not display unless i refresh the page.
I want this chat box message to show the new message entered.
This is to show the user List In the left side of the page:
$(".user-w").click(function() {
var user_id = $(this).attr("id");
// alert(user_id);
$.ajax({
type: "POST",
url: "<?php echo base_url('Message/getMessageByLists/')?>",
data: {
'user_id': user_id
},
datatype: 'html',
success: function(data) {
$("#loadMessages").html(data);
}
}); });
This is Send function:
$("#sendMessage").click(function(e)
{e.preventDefault();// alert("test");
var msg = $("#message_text").val();
var touser = $("#touser").val();
//var reservation_id = $("#reservation_id").val();
if (!msg || msg.length == 0) {
alert("enter a message");
} else {
$.ajax({
type: "POST",
url: "<?php echo base_url('Message/addMessage')?>",
// data:{'msg' : msg, 'touser' : touser, 'reservation_id' : reservation_id},
data: {
'msg': msg,
'touser': touser
},
datatype: 'text',
// Page.Server.ScriptTimeout = 300;
success: function(data) {
if (data == 1) {
//$("#loadMessages").load();
$("#message_text").val("");
} else {
alert("noo eroor chat message");
}
},
});
//return false;
} }); // End Send Function
if I am not wrong then, their might be an element with class as "user-w", also that element have "id" attribute too. So you can just execute following line, after sending the message to user.
$(".user-w[id='"+ touser +"']").trigger("click");
above line needs to placed in "success" method, like as below:
if (data == 1) {
//$("#loadMessages").load();
$("#message_text").val("");
$(".user-w[id='"+ touser +"']").trigger("click");
} else {
alert("noo eroor chat message");
}
Related
hello guys recently I am developing a new website which have multiple filters so I use the session-based filter with laravel
it is working fine if I use only the Show filter one time but when I switch to another filter, it is sending multiple requests(as much time I repeat the filter)
when someone clicks the filter this code will run
<------- Laravel route where I am sending a request it returns me a HTML file and I am rendering in my div tag where I have all lists ------->
public function filter(Request $request){
$course = Course::query();
if (isset($request->show)) {
Session::put('show',$request->show);
$show = $request->show;
}
if(isset($request->type)){
$course->where('type',$request->type);
}
if (isset($request->ratting)) {
$course->where('ratting','>=',$request->ratting);
Session::put('ratting',$request->ratting);
}
if(isset($request->short_type))
{
$type = $request->short_type;
$course = $this->checkSort($course,$type);
Session::put('short',$type);
}
if (Session::has('search')) {
$search = Session::get('search');
$course->where(function($q) use ($search){
$q->where('title', 'LIKE', '%'.$search.'%')
->orWhere('slug', 'LIKE', '%'.$search.'%')
->orWhere('description', 'LIKE', '%'.$search.'%')
->orWhere('keyword', 'LIKE', '%'.$search.'%');
});
}
if(Session::has('show') && !isset($request->show)){
$show = Session::get('show');
}
if(Session::has('ratting') && !isset($request->ratting)){
$course->where('ratting','>=',Session::get('ratting'));
}
if(Session::has('short') && !isset($request->short)){
$type = Session::get('short');
$course = $this->checkSort($course,$type);
}
$course->select('id', 'title', 'slug', 'description', 'created_at', 'regular_price', 'sell_price', 'thumbnail','ratting','status');
return view('site.courses.ajax-listing',[
'active' => 'courses',
'type' => $request->type,
'courses' => $course->where('status',1)->paginate(isset($show) ? $show : 10),
]);
}
public function checkSort($courses,$type){
if($type == "alphabetically_a_z")
{
$courses->orderBy('title', 'ASC');
}
if($type == "alphabetically_z_a")
{
$courses->orderBy('title', 'DESC');
}
if($type == "date_new_to_old")
{
$courses->orderBy('created_at', 'ASC');
}
if($type == "date_old_to_new")
{
$courses->orderBy('created_at', 'DESC');
}
if($type == "popular")
{
$courses->where('is_popular', 1);
}
return $courses;
}
<------------------------------------------->
In the search input have route where i will send request
<input type="text" hidden id="search-url" value="{{route('ajax-search-course')}}">
<--------- Javascript Code ----->
$(document).ready(function(){
var url = "{{route('ajax-search-course')}}";
var Jobtype = "1";
var value;
$("input[name='RattingRadioDefault']:radio").change(function(){
value = $("[name=RattingRadioDefault]:checked").val();
ajaxFilter(url + "?ratting="+value+ "&type=" + Jobtype);
});
$("input[name='ShowingRadioDefault']:radio").change(function(){
value = $("[name=ShowingRadioDefault]:checked").val();
ajaxFilter(url + "?show=" + value + "&type=" + Jobtype);
});
$("input[name='ShortingRadioDefault']:radio").change(function(){
value = $("[name=ShortingRadioDefault]:checked").val();
console.log("this is value",value,$("[name=ShortingRadioDefault]:checked").val());
ajaxFilter(url + "?short_type=" + value + "&type=" + Jobtype);
});
});
function ajaxFilter(url, data = null) {
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log("this is return data",data);
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function(jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
console.log("this is error", errorMessage);
}
});
}
<------------- Javascript pagination page ----------->
//Ajax Paginatio
$(document).one('click', '#ajaxPagination ul li a', function (e) {
console.log("ajax pagination function is running",$(this).attr("href"),"and",$(e).attr("href"));
e.preventDefault();
//Add Preloader
$('#listing-data').hide();
$('#loading-area').show();
var url = $(this).attr("href")+"&"+ "type=" + $('#data_sort_filter').attr('job-type'),
data = '';
e.preventDefault();
$.ajax({
method: 'GET',
url: url,
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#listing-data').html(data);
$('#loading-area').hide();
$('#listing-data').show();
},
error: function (jqXhr, textStatus, errorMessage) {
// error callback
$('#listing-data').hide();
$('#loading-area').show();
}
});
});
i was trying to add a multiple filters system with the session. now i have this error pagination function running as much i am repeating filters i want to solve this please help me it is a very important to project for me
I need help with my ajax function. I have a form that submits data with the same input name
When I run my code without javascript, I can insert multiple input data with the same name,
Submitted structure
{"_token":"CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu","id":"7","service_name":["asfd","safd"]}
When I implement javascript, a concatenated string is sent to the controller and this makes the service_name inaccessible.
formdata:"_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=7&service_name%5B%5D=sdfg&service_name%5B%5D=gfds&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=8&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=9&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=10&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=11&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=18"
My javascript function
jQuery("form.ajax").on("submit", function (e) {
e.preventDefault();
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: $(".ajax#servicesForm").serialize()
},
dataType: "JSON",
success: function (response) {
console.log(response);
},
error: function (jqXHR, exception) {
var msg = "";
if (jqXHR.status === 0) {
msg = "Not connect.\n Verify Network.";
} else if (jqXHR.status === 404) {
msg = "Requested page not found. [404]";
} else if (jqXHR.status === 500) {
msg = "Internal Server Error [500].";
} else if (exception === "parsererror") {
msg = "function Requested JSON parse failed.";
} else if (exception === "timeout") {
msg = "Time out error.";
} else if (exception === "abort") {
msg = "Ajax request aborted.";
} else {
msg = "Uncaught Error.\n" + jqXHR.responseText;
}
}
});
});
My PHP Controller Function
public function insert(Request $request)
{
return response()->json($request);
}
use FormData Object, to send fromdata
fd = new FormData();
fd.append("input-name", value1);
fd.append("input-name2", value2 OR arry of value);
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: fd
}
I found a workaround:
First, I created an array, and pushed all instances of input[name='service_name[]'] into the array.
Then I passed the data with ajax and was able to insert the data.
var serviceArray = new Array(), id;
jQuery.map($("input[name='service_name[]']"), function(obj, index) {
serviceArray.push($(obj).val());
});
My ajax script then:
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: 'post',
data: {
'service_name': serviceArray,
'id': id
},
dataType: 'JSON',
success: function(response) {
console.log(response);
}
});
This is the method in which i manage the data send with jquery.ajax. By default is send an empty string and on each change i watch the change on the input and resend it. Through console things are good but in php $this->searchField always has the value of an empty string
function checkInfo(){
if(isset($_POST['searchField'])){
$this->searchField = json_decode($_POST['searchField']);
if ($this->searchField != ""){
$this->query = "SELECT * FROM myguests WHERE firstName like '%".$searchField."%'";
}
else if ($this->searchField == "") {
$this->query = "SELECT * FROM myguests ORDER BY id";
}
$this->tableDisplay();
exit();
}
else{
return "error";
}
}
This is my jquery ajax function :
function searchGuests(users){
var data = {
"searchField": users
};
console.log(data);
$.ajax({
type: "POST",
dataType: "text",
url: "controllers/manageTable.php",
data: data
})
.done(function(tr) {
$("#tableBody").empty();
$("#tableBody").append(tr);
})
.fail(function(error){
console.log(error);
});
};
Any idea what I am missing?
Try encoding the users to a string before sending it over.
function searchGuests(users){
var data = {
"searchField": JSON.stringify(users);
};
console.log(data);
$.ajax({
type: "POST",
dataType: "text",
url: "controllers/manageTable.php",
data: data
})
.done(function(tr) {
$("#tableBody").empty();
$("#tableBody").append(tr);
})
.fail(function(error){
console.log(error);
});
};
There was a problem connecting Google Recaptcha v2. Or rather with the form. The check works fine, the error message displays, but, the message is still sent.
How can I fix this?
This is a form of feedback:
$(document).ready(function() {
$("#fast-call_submit").bind("click", function(e) {
e.preventDefault();
var form = $('#feedback_form');
var fields = form.serialize();
$.ajax({
url: form.attr('action') + '.json',
type: 'post',
data: fields,
dataType: 'json',
complete: function() {},
success: function(response) {
var v = grecaptcha.getResponse();
if (v.length == 0) {
$('.w-form-re-fail').show();
return false;
} else {
if (response.status == 'ok') {
$('.w-form-done').show();
$('.w-form-fail').hide();
form.hide();
} else {
$('.w-form-fail').show();
}
$('.w-form-re-fail').hide();
return true;
}
}
});
});
});
I am attempting to load dynamic data based on the specific URI segment thats on the page.
Heres my Javascript:
$(document).ready(function() {
$(function() {
load_custom_topics();
});
$('#topics_form').submit(function() {
var topic = document.getElementById('topics_filter').value
$.ajax({
type: "POST",
url: 'ajax/update_session_topic',
dataType: 'json',
data: { topic: topic },
success: function(){
load_custom_topics()
}
});
return false;
});
function load_custom_topics(){
$.ajax({
type: "POST",
url: 'ajax/load_custom_topics',
dataType: 'json',
data: {},
success: function (html) {
$('div.topics_filter').html(html['content']);
get_threads();
}
});
}
function get_threads(){
var page = document.getElementById('page').value
$.ajax({
type: "POST",
url: 'ajax/get_threads',
dataType: 'json',
data: {page: page},
success: function (html) {
$('div#thread_list').html(html['content']);
}
});
}
});
So, as you can see, on page load, it kicks off load_custom_topics which runs just fine. Its then supposed to call get_threads(). This is where the thing stops, and I get no data.
Get_threads()
public function get_threads()
{
$session = $this->session->userdata('active_topic');
if ($this->input->post('page') == '1')
{
$data['list'] = $this->right_model->thread_list_all();
$data['test'] = "all";
} else {
$data['list'] = $this->right_model->thread_list_other($session);
$data['test'] = "not all";
}
if ($data['list'] == FALSE)
{
$content = "no hits";
} else {
$content = $this->load->view('right/thread_list', $data, TRUE);
}
$data['content'] = $content;
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
While I create the 'page' dynamically, the HTML outputs to this:
<div name="page" value="1"></div>
Any reason why get_threads() is not running?
This does not have an ID. It has a name.
<div name="page" value="1"></div>
This means that your request for getElementById is failing. So this line of code should be showing a TypeError in your console.
var page = document.getElementById('page').value