How to print JavaScript based on Ajax request? - javascript

Allow me to elaborate.
I have this Ajax script which is fetching for one thing. The refresh_on.
What does it do? It either returns 0 OR 1.
function startRefresh() {
setTimeout(startRefresh, 60000);
$.ajax({
url: 'refresh.php',
type: 'POST',
dataType: 'JSON',
data: {task: "reload"},
success: function(data) {
$.each(data, function(i, attr){
if (attr.refresh_on == 0) {
//this doesn't work
/*Write/return this in JavaScript:*/ line[1]="Offline.";
} else {
//this doesn't work
/*Write/return this in JavaScript:*/ line[1]="Online.";
};
})
}
});
}
If the ajax returns with refresh_on == 0 OR refresh_on == 1 - I want it to print its respective array item. It must be an array item.
</head>
<body>
<script type="text/javascript">
var line=new Array()
startRefresh();
//output either "line[1]=\"Offline.\""; or "line[1]=\"Online.\"";
</script>
</body>
This is the PHP file:
if (isset($_POST['task']) && $_POST['task'] == "reload") {
$stmt = $connection->prepare("SELECT refresh_on FROM refresh");
$stmt->execute();
$result = $stmt->get_result();
$encode = Array();
while ($row = $result->fetch_assoc()) {
$encode[] = $row;
}
echo json_encode($encode);
}
If it matters - this is the JSON response:
[{"refresh_on":1}]
Is there a way to insert/output/print the array item using the function?
Any help would be appreciated.

So there's a couple things that might be going on here, but to begin, you're wrapping your variable in a quote, so all that is happening is a string is being made and immediately being dropped to the floor. Let's start off by doing something like the following:
function startRefresh() {
setTimeout(startRefresh, 60000);
$.ajax({
url: 'refresh.php',
type: 'POST',
dataType: 'JSON',
data: {task: "reload"},
success: function(data) {
$.each(data, function(i, attr){
if (attr.refresh_on == 0) {
//this doesn't work
line[1] = "Offline.";
} else {
//this doesn't work
line[1]= "Online.";
};
})
}
});
}
Now, if I recall correctly, the ajax function is going to be calling your success callback, which is going to take over your local scope. I don't believe line is going to be accessible to that callback, so we should/could actually move that callback to its own function within a closure:
<script type="text/javascript">
(function() {
var line = [];
startRefresh();
function startRefresh() {
setTimeout(startRefresh, 60000);
$.ajax({
url: 'refresh.php',
type: 'POST',
dataType: 'JSON',
data: { task: "reload" },
success: refreshResponse
});
}
function refreshResponse(data) {
$.each(data, function(i, attr) {
if (attr.refresh_on == 0) {
line[1] = "Offline.";
} else {
line[1] = "Online.";
}
});
}
})();
</script>
We've wrapped that in a self executing function to give us some nice encapsulation to work with, and because line is in a function which refreshResponse is found, that variable should be accessible to it.
But we're not done yet!
For one, we could easily make that variable assignment a little easier, like so:
line[1] = (attr.refresh_on == 0) ? "Offline." : "Online.";
...and we're also going to want to triple up on that equality statement, just to avoid variable coercion:
line[1] = (attr.refresh_on === 0) ? "Offline." : "Online.";
Give that a shot and let's see where we're at.

Not sure what you are expecting "line[1]=\"Offline.\""; to do, but it's not going to do anything. Perhaps you mean: line[1]= "Offline";? Try putting this line of code there instead to test that it's working: console.log('Offline');
If the line is getting executed and you see the output in your console, you would just have to target some HTML element that you want to put the "Offline" string into, for instance:
<div id="status"></div>
<script>
....
var status = document.getElementById("status");
if (attr.refresh_on == 0) {
status.textContent = "Offline";
} else {
status.textContent = "Online";
};
....
</script>

Related

AJAX returns only last array item

I want to create async AJAX query to check server status when web page finish loading. Unfortunately when it comes to data display from processed PHP, I receive only single value.
JS:
<script>
window.onload = function() {
test();
};
function test()
{
var h = [];
$(".hash td").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('.result').replaceWith(data);
}
});
}
});
}
</script>
PHP:
<?php
require_once ('inc/config.php');
require_once ('inc/libs/functions.php');
if (isset($_POST['hs'])) {
$hash = json_decode($_POST['hs']);
serverstatus($hash);
}
function serverstatus($hash) {
$address = DB::queryFirstRow("SELECT address,hash FROM servers WHERE hash=%s", $hash);
$address_exploded = explode(":", $address['address']);
$ip = $address_exploded[0];
$port = $address_exploded[1];
$status = isServerOnline($ip,$port);
if ($status) {
$s = "Online $ip";
} else {
$s = "Offline";
}
echo $s;
}
?>
I embed result from PHP to a table row. I see that AJAX iterating over the array, but all rows receive same value (last checked element in array).
$('.result') matches all elements with the class result. replaceWith will then replace each of them with the content you provide.
If you want to only affect the .result element within some structure (perhaps the same row?), you need to use find or similar:
function test()
{
var h = [];
$(".hash td").each(function(){
var td = $(this); // <====
var hash = td.closest('#h').text();
var result = td.closest("tr").find(".result"); // <====
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
result.replaceWith(data); // <====
}
});
}
});
}
Obviously the
var result = td.closest("tr").find(".result"); // <====
...will need to be tweaked to be what you really want it to be, but that's the idea.
This line in your question suggests an anti-pattern:
var hash = $(this).closest('#h').text();
id values must be unique in the document, so you should never need to find the one "closest" to any given element. If you have more than one id="h" element in the DOM, change it to use a class or data-* attribute instead.
Thank you all for help. My final, obviously very dirty but working code:
function testServerPage()
{
var h = [];
$(".hash li").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
//async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('#' + hash).replaceWith(data);
}
});
}
});
return false;
}
I just added dynamic variable to element:
success: function(data) {
$('#' + hash).replaceWith(data);
}

JQuery Ajax returns Source code

I'm using JQuery Ajax on my website. I've tested it on our test server it worked perfectly, but when I tried to put it on our productive server the Ajax just returns the source code of the website itself.
JS File:
$(document).ready(function () {
$('#sshin').keyup(function () {
var query = $(this).val();
console.log(query);
if (query != '') {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function (data) {
console.log(data);
}
});
}
});
$(document).on('click', 'article', function () {
var text = $('#sshin').val();
text = text.substring(0, text.lastIndexOf(',') + 1);
text += $(this).text();
var uniq = text.match(/\b\w+\b/g).filter(function (el, idx, a) {
return idx === a.lastIndexOf(el);
});
text = uniq.join(',');
$('#sshin').val(text);
$('#sshout').fadeOut();
});
});
PHP File:
<?php
if(isset($_POST["query"])){
$query = $_POST["query"];
return '<ul><li>1</li><li>2</li></ul>';
}
?>
Any idea why it returns something different than it should?
This method once worked for me, hope it might help. Let me know.
this->output->set_content_type('application/json');
return $this->output->set_output(json_encode('<ul><li>1</li><li>2</li></ul>'));

Unexpected characters in image url in ajax response Javascript

In My Codeigniter web application I'm using an ajax function to get some data from the database inorder to show it in the view.The data from database contains an image url and other fields.
My problem is that when I get the data in ajax success function, the image url looks like this:
<button id='product-1301' type='button' value=1301 class='blue' ><i><img src='assets\/uploads\/thumbs\/default.png'></button>
Since the url contains these characters \ my view is not rendering properly. I tried using stripslash function to remove this. But didn't work. I didn't know where am going wrong.
my ajax function
$.ajax({
type: "get",
url: "index.php?module=pos&view=ajaxproducts1",
data: {category_id: cat_id, per_page: p_page},
dataType: "html",
success: function(data) {
var x= data;
alert(x);
if(data!=1)
{
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
}
else
{
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
Controller
function ajaxproducts1()
{
$mn;$data1;
$img="assets/uploads/thumbs/default.png"; //this is my image path, when this comes in ajax success,\ character adds
$img=str_replace('\"', '', $img);
if($this->input->get('category_id')) { $category_id = $this->input->get('category_id'); }
if($this->input->get('per_page')) { $per_page = $this->input->get('per_page'); }
if($item = $this->pos_model->getProductsByCategory($category_id,$per_page))
{
foreach ($item as $i)
{
$button="<button id='product-".$i->id."' type='button' value=".$i->id." class='blue' ><i><img src='".$img."'><span><span>".$i->name;
$mn=$mn.$button;
}
$data1=$mn;
}
else
{
$data1=1;
}
echo json_encode($data1);
}
Can anyone help me with this ?
Try this:
// use an array to gather up all the values
// call encodeURIComponent() on the variables before adding them
// join them all together and pass them as "data"
var tempVars=['module=pos&view=ajaxproducts1'];
tempVars.push('category_id='+encodeURIComponent( cat_id ));
tempVars.push('userInfo='+encodeURIComponent( p_page ));
var sendVars=tempVars.join('&');
$.ajax({
type: "get",
url: "index.php",
data: sendVars,
dataType: "text",
success: function(data) {
var x = data;
alert(x);
if (data != 1) {
$('#proajax').empty();
var newPrs = $('<div></div>');
newPrs.html(data);
newPrs.appendTo("#proajax");
//$('#gmail_loading').hide();
} else {
bootbox.alert('Product is Not Available in this Category!');
$('#gmail_loading').hide();
}
}
});
My issue was solved by using jQuery.parseJSON function.

jQuery post data return comparison not working

I have this bit of code:
function addEmail() {
email = $("#email").val();
atime = $("select#time").val();
tid = <?= $tid; ?>;
$.post("remindme.php", { email: email, time: atime, tid: tid },
function(data) {
if (data == "x") {
alert(data);
$('#remindme').modal('hide');
$('#quota').show();
}
else {
alert(data);
$('#remindme').modal('hide');
$('#remindersuccess').show();
}
});
}
remindme.php echo's "x" if something is wrong.
I'm trying to compare the output from remindme.php but even though it echo's the x, the condition data == "x" does not work.
I added alert(data) and I can see it properly displaying the x when needed..
If the server echoes the x string then the if (data == 'x') test inside the success callback should work. Your problem is somewhere else.
maybe is late. I faced same problem and I solved by very stupid workaround (applied to your code):
function(data) {
var server_info = data;
if (server_info == "x") {
$('#remindme').modal('hide');
$('#quota').show();
} else {
$('#remindme').modal('hide');
$('#remindersuccess').show();
}
}
I have no idea why :/
Hope it helps.
I had the same problem perhaps, and I fixed it like this:
var verify = function (user,fName,fPass) {
var result = "";
$.ajaxSetup({async:false});
$.post("php_scripts/verify"+user+".php",{login:fName, pass:fPass},function (data) {
result = $.trim(data); // use $.trim when are you using "data"
});
return result;
}

my javascript code will not proceed to delete my data from jqGrid

just want to ask regarding my javascript code. I have a function that will delete and edit a data in my jqgrid. But everytime i run my code, it will not delete and edit if I dont put an alert in some portion of the code. Why is it happening? How can i make my program run without the alert?
Below is my delete function:
function woodSpeDelData(){
var selected = $("#tblWoodSpe").jqGrid('getGridParam', 'selrow');
var woodID='';
var woodDesc='';
var codeFlag = 0;
var par_ams = {
"SessionID": $.cookie("SessionID"),
"dataType": "data"
};
//this part here will get the id of the data since my id was hidden in my jqgrid
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'getData/woodSpecie',json:JSON.stringify(par_ams)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
if (fldName == 'wood_specie_id'){
woodID = rowArrayValue;
}
if (fldName == 'wood_specie_desc'){
woodDesc = rowArrayValue;
alert($('#editWoodSpeDesc').val() +' '+ woodDesc); //program will not delete without this
if(selected == woodDesc){
codeFlag =1;
alert(woodID); //program will not delete without this
};
}
});
if (codeFlag == 1){
return false;
}
});
if (codeFlag == 1){
return false;
}
}
}
});
alert('program will not proceed without this alert');
if (codeFlag == 1) {
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "delete",
"wood_specie_id": woodID
};
alert(woodID);
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'delete/woodSpecie',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblWoodSpe').trigger('reloadGrid');
}
}
});
}
}
EDIT
My main purpose of putting an alert was just to know if my code really get the right ID of the description, and if would really go the flow of my code... But then i realized that it really wont work with it.

Categories

Resources