AJAX response doesn't run any script - ajax

My page gets a response from response_ajax.php with this code:
<input class="btn" name="send_button" type="button" value="check"
onClick=
"xmlhttpPost('/response_ajax.php',
'MyForm',
'MyResult',
'<img src=/busy.gif>')";
return false;"
>
I get a response; however, jQuery scripts don't work with an arrived code. I'm trying to add script inside response_ajax.php, but nothing happens:
<?php
// ... //
echo '
<div id="whois-response">
<pre>' .$str. '</pre>
</div>
<script>
(function($){
$(function(){
alert("loaded");
});
})(jQuery);
</script>
';
?>
xmlhttpPost function:
function xmlhttpPost(strURL,formname,responsediv,responsemsg) {
var xmlHttpReq = false;
var self = this;
// Xhr per Mozilla/Safari/Ie7
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// per tutte le altre versioni di IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
// Quando pronta, visualizzo la risposta del form
updatepage(self.xmlHttpReq.responseText,responsediv);
}
else{
// In attesa della risposta del form visualizzo il msg di attesa
updatepage(responsemsg,responsediv);
}
}
self.xmlHttpReq.send(getquerystring(formname));
}
function getquerystring(formname) {
var form = document.forms[formname];
var qstr = "";
function GetElemValue(name, value) {
qstr += (qstr.length > 0 ? "&" : "")
+ escape(name).replace(/\+/g, "%2B") + "="
+ escape(value ? value : "").replace(/\+/g, "%2B");
//+ escape(value ? value : "").replace(/\n/g, "%0D");
}
var elemArray = form.elements;
for (var i = 0; i < elemArray.length; i++) {
var element = elemArray[i];
var elemType = element.type.toUpperCase();
var elemName = element.name;
if (elemName) {
if (elemType == "TEXT"
|| elemType == "TEXTAREA"
|| elemType == "PASSWORD"
|| elemType == "BUTTON"
|| elemType == "RESET"
|| elemType == "SUBMIT"
|| elemType == "FILE"
|| elemType == "IMAGE"
|| elemType == "HIDDEN")
GetElemValue(elemName, element.value);
else if (elemType == "CHECKBOX" && element.checked)
GetElemValue(elemName,
element.value ? element.value : "On");
else if (elemType == "RADIO" && element.checked)
GetElemValue(elemName, element.value);
else if (elemType.indexOf("SELECT") != -1)
for (var j = 0; j < element.options.length; j++) {
var option = element.options[j];
if (option.selected)
GetElemValue(elemName,
option.value ? option.value : option.text);
}
}
}
return qstr;
}
function updatepage(str,responsediv){
document.getElementById(responsediv).innerHTML = str;
}

I may be wrong, but I'm pretty sure you can't do multiline strings unless it is configured to do so (and running a newer version of PHP):
echo '
<div id="whois-response">
<pre>' .$str. '</pre>
</div>
<script>
(function($){
$(function(){
alert("loaded");
});
})(jQuery);
</script>
';
Try changing that to:
echo <<<EOD
<div id="whois-response">
<pre> $str </pre>
</div>
<script>
(function($){
$(function(){
alert("loaded");
});
})(jQuery);
</script>
EOD;
I think your AJAX response is a PHP error instead of the script you think it is returning.

Got it to work by adding jQuery staff as a function
function updatepage(str,responsediv){
document.getElementById(responsediv).innerHTML = str;
(function($){
$(function(){
$('html').my_jQuery_staff();
});
})(jQuery);
}
Main JavaScript file with jQuery:
// ~~ jQuery ~~
$(document).ready(function () {
$.fn.my_jQuery_staff= function() {
return this.each(function() {
// Include jQuery staff here.
});
};
$('html').my_jQuery_staff();
});

Related

how to get the value of textarea from innerhtml in javascript and insert into the database using the controller in laravel....?

javascript
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text() ;
if ($.inArray(userID, arr) != -1)
{
arr.splice($.inArray(userID, arr), 1);
}
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="'+ userID+'">'+
'<div class="msg_head">'+username +
'<div class="close">x</div> </div>'+
'<div class="msg_wrap"><div class="msg_body" id="msg_body" ><div class="msg_push"></div></div>'+
'<div class="msg_footer"><textarea class="msg_input" id="msg_input" rows="4" style="resize:none;"></textarea></div></div></div>' ;
$("body").append( chatPopup );
displayChatBox();
});
$(document).on('keypress', 'textarea' , function(e) {
if (e.keyCode == 13 ) {
var msg = $(this).val();
$(this).val('');
if(msg.trim().length != 0){
var chatbox = $(this).parents().parents().parents().attr("rel") ;
$('<div class="msg-right">'+msg+'</div>').insertBefore('[rel="'+chatbox+'"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
var url= " /sendchatmessage ";
$.ajax({
headers:{'X-CSRF-token':$('meta[name=csrf-token]').attr('content')},
async:true,
type:"post",
contentType:false,
url:url,
data:msg,
processData:false,
success:function(){
console.log("success");
}
});
}
} // revision
});
controller
public function send_chat_message(Request $req){
$name = $req->input('msg_input'); //
$newchat = new ChatMessage;
$newchat->frsender_userId = Auth::user()->user_id;
$newchat->frchat_msg = $name;
$newchat->save();
}
web.php
Route::post('/sendchatmessage', 'MessengerController#send_chat_message')->name('sent-chat');

How to change 'active/inactive status of user' through ajax?

I am display list of users in datatable based on 2 parameters through AJAX in codeigniter. I want to change the status of user in database and display in table. I have 3 status 0-> inactive, 1->active, -1->left. I want to change the status and display in datatable without reloading the page.
I have tried changing the status but the status is changing only once. After first AJAX call there is no change when i again change the status.
//view
<script>
$(document).ready(function()
{
$('#academicTable_wrapper').hide();
$('#studentTable').DataTable();
showStudents();
function showStudents()
{
$('#submitBtn').on('click',function(){
var courseId = $('#courseId').val();
var classId = $('#classId').val();
$.ajax({
type : 'POST',
url : "<?php echo base_url();?>Student/getStudentsList",
// async : true,
data : {courseId:courseId,classId:classId},
dataType : 'json',
success : function(data){
//alert(data);
var html = '';
var i;
for(i=0; i<data.length; i++){
var studentId = data[i].studentId;
if(data[i].status == 1)
var status = "Approved";
else if(data[i].status == 0)
var status = "Pending";
else
var status = "Left";
html += '<tr>'+
'<td>'+data[i].studentId+'</td>'+
'<td>'+data[i].studentName+'</td>'+
'<td>'+data[i].studentPhoneNum+'</td>'+
'<td>'+data[i].created_on+'</td>'+
'<td id="changeStatus">'+status+'</td>'+
'<td>'+
'View'+
' '+
'<a id="activateBtn" data-id="'+data[i].id+'" data-status="'+data[i].status+'" class="btn btn-primary btn-sm text-white">Activate/Deactivate</a>'+
' '+
'Delete'+
'</td>'+
'</tr>';
}
$('#studentTable').DataTable().destroy();
$('#showData').html(html);
$('#studentTable').DataTable();
$('#academicTable_wrapper').show();
}
});
});
}
$(document).on('click','#activateBtn',function()
{
var id = $(this).data('id');
var status = $(this).data('status');
$.ajax({
method: 'POST',
url: "<?php echo base_url();?>Student/approveStudent",
data:{id:id,status:status},
success : function(data)
{
alert(data);
$('#changeStatus').text('');
if(data == 0)
{
showStudents();
$('#changeStatus').html('Inactive');
}
else{
showStudents();
$('#changeStatus').html('Approv');
}
},
error:function(data)
{
console.log(data);
}
},1000);
});
});
</script>
//controller
function approveStudent()
{
$id = $this->input->post('id');
$status = $this->input->post('status');
$col = 'id';
$query = $this->Admin_model->activate($col,$id,$status,$this->studentDetail);
if($query){
$result = $this->Admin_model->getData($col,$id,$this->studentDetail);
}
$status = 1;
if ($result[0]->status == 0)
{
$status = 0;
}
echo $status;
}
I expect whenever I click activateBtn the status should change in database and also in datatable.

For every new ajax call it takes a little more time than the previous call

I am trying to change some data with an ajax call, but the problem is that every new call takes a little more time than the previous one.
So after 10-15 calls, the time from when the ajax request starts and when ajax returns data is like 20 seconds per request.
I also tried to debug, and it seems that the problem is that when I trigger an ajax call, it takes all that time till the controller detects the call, and after controller detects it, it gets executed and returns data immediately.
P.S. When i comment out these 2 intervals, it works perfectly. So i guess these intervals are blocking this request form happening immediately.
Also can it be a problem with Google Chrome? Because i guess in Microsoft Edge works perfectly (as far i made a test 2 times).
html:
<div class="table-responsive">
<table class="table table-condensed table-hover usersTable">
<thead>
<tr>
<th style="width: 20%">Benutzer</th>
<th></th>
<th></th>
#foreach (var item in Model.Skills)
{
<th title="#item.Name">#item.ShortName</th>
}
<th class="text-center">Extension</th>
<th class="text-center">Total Calls</th>
<th class="text-center">Calls per hour</th>
<th class="text-center">Average Call Duration</th>
</tr>
</thead>
<tbody class="usersTableBody"></tbody>
</table>
<div class="col-md-12 text-center noSignedInUser" style="display: none;">
<h4 style="color: lightgrey">There is no signed in user</h4>
</div>
js:
$(function () {
$('.usersTableBody').on('click', '.hasSkill', function () {
var userId = $(this).parent().data('id');
var skillId = $(this).data('id');
if ($(this).hasClass('skillIsActive')) {
addRemoveSkill(userId, skillId, false, $(this))
}
else {
addRemoveSkill(userId, skillId, true, $(this))
}
});
//add or remove a skill to a user with ajax
function addRemoveSkill(userId, skillId, add, element) {
$.ajax({
url: '#Url.Action("AddRemoveSkill","Home")',
data: { userId: userId, skillId: skillId, add: add },
success: function (data) {
if(data == true) {
if (add == false)
{
$(element).addClass('skillIsInactive')
$(element).removeClass('skillIsActive')
}
else {
$(element).addClass('skillIsActive')
$(element).removeClass('skillIsInactive')
}
$(element).addClass('recentlyUpdated');
hasAllSkillsDisabled($(element));
}
}
});
}
function hasAllSkillsDisabled(element) {
parent = $(element).parent();
var hasAllDisabled = true;
$.each(parent.children('td'), function (i, item) {
if ($(item).hasClass('skillIsActive'))
{
hasAllDisabled = false;
}
});
if (hasAllDisabled == true)
{
$(parent).addClass('hasAllSkillsDisabled');
}
else {
$(parent).removeClass('hasAllSkillsDisabled');
}
}
})
two other functions that gets data every 1000ms
getUserDatas();
getSkillHeader();
var detectClass = 0;
function getUserDatas() {
var type = $('#Type').val();
var skill = $('#Skill').val();
$.ajax({
url: '#Url.Action("GetUsersDataWithAjax", "Home")',
data: { type: type, skill: skill },
success: function (data) {
if (data.length == 0) {
$('.noSignedInUser').show();
}
else {
$('.noSignedInUser').hide();
}
if (data != false) {
$.each(data, function (i, item) {
var tr = $('tr[data-id="' + item.Id + '"].agentTr');
//if that row already exists or its new
if (!tr.length)
{
//if new create html and append to table body
var dontHaveSkills = "dontHaveSkills";
if (item.hasSkills) {
dontHaveSkills = "";
}
var hasAllSkillsDisabled = "";
if (item.hasSkills && item.HasAllSkillsDisabled) {
hasAllSkillsDisabled = "hasAllSkillsDisabled";
}
var html = '';
html += '<tr data-id="' + item.Id + '" class="agentTr ' + dontHaveSkills + ' ' + hasAllSkillsDisabled + ' time' + detectClass + '">';
html += '<td>' + item.Name + '</td>';
html += '<td class="stateName"><div class="text-right ' + item.State.NameClass + '">' + item.State.Name + '</div></td>';
html += '<td class="stateCircle"><div class="statusCircle ' + item.State.CircleClass + '"</div></td>';
$.each(item.Skills, function (j, skill) {
var klasa = "";
if (skill.IsActive == true) {
klasa = "hasSkill skillIsActive";
}
else if (skill.IsActive == false) {
klasa = "hasSkill skillIsInactive";
}
else {
klasa = "unableSkill";
}
html += '<td data-id="' + skill.Id + '" class="' + klasa + '" title="' + skill.Name + '">' + skill.ShortName + '</td>';
if (j == 25) {
return false;
}
});
html += '<td class="text-center extension">' + item.Extension + '</td>';
html += '<td class="text-center totalCalls">' + item.AvgCalls.TotalCalls + '</td>';
html += '<td class="text-center callsPerHour">' + item.AvgCalls.CallsPerHour + '</td>';
html += '<td class="text-center avgCallDuration">' + item.AvgCalls.AvgCallDuration + '</td>';
html += '</tr>';
$('.usersTableBody').append(html);
}
else {
//else if its existing update datas
tr.removeClass('dontHaveSkills hasAllSkillsDisabled');
var detect = 'time' + (detectClass - 1);
tr.removeClass(detect);
if (!item.hasSkills) {
tr.addClass('dontHaveSkills');
}
if (item.hasSkills && item.HasAllSkillsDisabled) {
tr.addClass('hasAllSkillsDisabled');
}
var stateName = tr.children('.stateName');
stateName.children('div').text(item.State.Name);
stateName.children('div').removeClass('bereitName besetzName nbzName pauseName abgemeldetName');
stateName.children('div').addClass(item.State.NameClass);
var stateCircle = tr.children('.stateCircle');
stateCircle.children('div').removeClass('Online OnCall AfterTime Pause LoggedOff');
stateCircle.children('div').addClass(item.State.CircleClass);
$.each(item.Skills, function (j, skill) {
var skillElement = tr.children('td[data-id="' + skill.Id + '"]');
if (!skillElement.hasClass('recentlyUpdated')) {
skillElement.removeClass('hasSkill skillIsActive skillIsInactive unableSkill');
if (skill.IsActive == true) {
skillElement.addClass('hasSkill skillIsActive');
}
else if (skill.IsActive == false) {
skillElement.addClass('hasSkill skillIsInactive');
}
else {
skillElement.addClass('unableSkill');
}
}
else {
skillElement.removeClass('recentlyUpdated');
}
if (j == 25) {
return false;
}
});
var extension = tr.children('.extension');
var totalCalls = tr.children('.totalCalls');
var callsPerHour = tr.children('.callsPerHour');
var avgCallDuration = tr.children('.avgCallDuration');
extension.text(item.Extension);
totalCalls.text(item.AvgCalls.TotalCalls);
callsPerHour.text(item.AvgCalls.CallsPerHour);
avgCallDuration.text(item.AvgCalls.AvgCallDuration);
tr.addClass('time' + detectClass);
}
var allTr = $('tr.agentTr');
});
}
$('tr.agentTr').each(function (i, item) {
if (!$(item).hasClass('time' + detectClass)) {
item.remove();
}
});
detectClass++;
$('.usersTable').waitMe('hide');
}
});
}
function getSkillHeader() {
$.ajax({
url: '#Url.Action("GetSkillHeaderWithAjax", "Home")',
success: function (data) {
if (data.length == 0) {
$('.allSkillsHidden').show();
}
else {
$('.allSkillsHidden').hide();
}
if (data != false) {
$.each(data, function (i, item) {
var tr = $('tr[data-id="' + item.Id + '"].skillTr');
if (!tr.length) {
var html = '';
html += '<tr data-id="' + item.Id + '" class="skillTr">';
html += '<th class="name">' + item.Name + '</th>';
html += '<th class="text-center waitingQueue">~</th>';
html += '<th class="text-center activeCalls">~</th>';
html += '<th class="text-center totalFreeAgents">' + item.TotalFreeAgents + '</th>';
html += '<th class="text-center totalSignedInAgents">' + item.TotalSignedInAgents + '</th>';
html += '</tr>';
$('.skillsHeaderTableBody').append(html);
}
else {
var name = tr.children('.name');
name.text(item.Name);
var totalFreeAgents = tr.children('.totalFreeAgents');
totalFreeAgents.text(item.TotalFreeAgents);
var totalSignedInAgents = tr.children('.totalSignedInAgents');
totalSignedInAgents.text(item.TotalSignedInAgents);
}
});
}
$('.skillHeaderTable').waitMe('hide');
}
});
}
//call getUserDatas method every 1 seconds
setInterval(function () {
getUserDatas();
},1000);
setInterval(function () {
getSkillHeader();
}, 1000);
C#:
public ActionResult AddRemoveSkill(string userId, string skillId, bool add)
{
try
{
var skill = _sysCfgContext.GetUserSkill(Guid.Parse(userId), Guid.Parse(skillId));
if (add)
skill.IsActive = true;
else
skill.IsActive = false;
_sysCfgContext.EditUserSkill(skill);
_sysCfgContext.SaveChanges();
return Json(true, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
I'm using the assumption that those two functions aren't dependent upon one another.
function getUserDatas() {
var type = $('#Type').val();
var skill = $('#Skill').val();
return $.ajax(function() {
//Code omitted for brevity
});
}
function getSkillHeader() {
return $.ajax(function() {
//Code omitted for brevity
});
}
getUserDatas();
getSkillHeader();
var interval = setInterval(function(){
$.when(getUserDatas(), getSkillHeader())
.then(function(resultUserDatas,resultSkillHeader)
},1000);
I have to add that this is the untested code.

How to use “response” from any XMLHTTPREQUEST in CakePHP (2.5)

I got the action "pega" in controller Posts:
public function pega($id = null)
{
$posts = $this->Post->findById($id);
foreach($posts as $pok)
{
$foda = $pok['love'];
}
$this->set('foda', $foda);
$this->set('_serialize', array('foda'));
}
In my layout I try to do a requestto catch the data from function "pega" and put inside tag html:
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:81/booklandia/posts/pega/<?php echo $post['Post']['id'];? >.json";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var out = JSON.parse(xmlhttp.responseText);
function loap (){
var arr = out[0];
document.getElementById("id01").innerHTML = arr;
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

Need help in clearTImeout

Ajax
<script type="text/javascript">
var stopTime =0;
var scoreCheck = function ()
{
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/checkScoreRoundOne',
success:function(output){
if(output !='Instruction'){
console.log(output);
clearTimeout(scoreCheck);
}
else
console.log(output);
stopTime = setTimeout(scoreCheck, 1000);
}
});
}
stopTime = setTimeout(scoreCheck,1000);
</script>
Controller
public function checkScoreRoundOne(){
$id = $this->session->userdata('userID');
$battleID = $this->lawmodel->getBattle($id);
foreach($battleID as $row){
$Rscore = $row->requestedScore;
$Cscore = $row->challengerScore;
if($Cscore == '1'){
$rID = $this->lawmodel->getID($row->challengerID);
foreach($rID as $row){
echo $row->username."Got the correct answer";
}
}
else if($Rscore == '1'){
$cID =$this->lawmodel->getID($row->requestedID);
foreach($cID as $row){
echo $row->username."Got the correct answer";
}
}
else
echo "Instruction";
}
}
Im confused in the code above
In ajax, why when the output !='Instruction' it will display "Instruction" and when the output == 'Instruction' it will display $row->username got the correct answer.
And how can i stop the setTimeout when the Cscore == 1 or Rscore ==1?
I think cleartimeout will not just stop the setTimeout..
Plss help...Im new in ajax..
Im using codeigniter
About the clearTimeout:
clearTimeout(stopTime);

Resources