ajax setTimeout not working on json_encode - javascript

AJAX function
var stopTime = 0;
var checkRequApprove = function ()
{
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/checkApproveReq',
success:function(output){
jsn=JSON.parse(output);
if(output==false){
stopTime = setTimeout(checkRequApprove, 3000);
}
else {
bootbox.dialog({
message: "Battle",
title: "Request Accepted",
buttons:
{
success: {
label: "Approve",
className: "btn-success",
callback: function() {
$.ajax({
"type" : "POST",
"url" : "finalBattleApprove",
"data" : {'username' : jsn.user_name},
success: function(data){
$('#example').html(data);
$('#loadingmessage').show();
}
});
}
},
}
}
});
}
stopTime = setTimeout(checkRequApprove,3000);
Controller
public function checkApproveReq(){
$id = $this->session->userdata('userID');
$requApprove = '1';
$check = $this->lawmodel->checkRequApprove($id,$requApprove);
foreach($check as $row){
if($row->requApprove == '1')
{
$reqID = $this->lawmodel->getID($row->requestedID);
foreach($reqID as $row){
echo json_encode(
array(
'user_name' =>$row->username,
)
);
}
}
else
echo false;
}
}
I have this code wherein there is a realtime check to the database and if the condition has meet..custom dialog will pop up.
Im having this problem on my checkRequApprove function..The bootbox.dialog will not showup if the condition is meet in the controller...
i believe that my problem is because in the controller which echo json_encode. I cant find any solution .im still a newbie in ajax..
EDITED
the custom dialog will only show after i refresh the page.

output is a string - the comparison output == false will always yield false, because a non-empty string is always true (not considering the edgecase "0" in which case "0" == false yields true).
Instead of
if(output==false){
...
}
it should be:
if (!jsn){ // or jsn == false if you like that better
...
}
Also you should consider not returning a simple value in your controller, but always a proper json-object like:
else{ // consider always using brackets, for more robustness
echo
array(
'error' => true
);
}
Now, in your js you just check for
if (jsn.error){
...
}
In any case, you should include an error callback for your json to handle possible errors with the json request.

Related

cancel ajax success function from inside ajaxSuccess event

I have a global ajaxSuccess event and a local success function attached to an ajax request.
I want to cancel the success function if the global find status = false in the response.
like this
$(document).ajaxSuccess(function (event, xhr) {
let result = xhr.responseJSON;
if (result.status === false) {
//here the ajax should be stopped, I don't want to call the local functio
}
}
$.ajax(url, {
'method': method,
'success': function () {
//success function to call if the global ajaxSuccess is ok
}
})
can this be achieved ?
This will give you an insight into what you may be looking for. You will need to return the backend data in json.
why don't you set status to certain values
Eg. false= 0 and true = 1. You can then print success or failure based on values returned from the backend in this sample from PHP backend.
Here am sending a post variable with value of test_ok. If the value is test_ok then alert success else alert fail and
stop further action
<script>
$(document).ready(function(){
var test ='test_ok';
var datasend = "test="+ test;
$.ajax({
type:'POST',
url:'test.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(result){
$('#result').fadeIn('slow').prepend(msg);
if (result.status ==0) {
alert('failed');
return false;
}
if (result.status == 1) {
alert('success');
}
}
});
});
</script>
test.php
<?php
$test = $_POST['test'];
$output = array();
if($test == "test_ok"){
$output[] = array(
"status" => '1'
);
}
if($test != "test_ok"){
$output[] = array(
"status" => '0'
);
}
echo json_encode($output);

Return php variable?

I have made a little AJAX-script for my site, which executes a php-script in another file on submission. I managed to echo out the result in the original file with the AJAX-function, but I have not managed to transfer a variable from the php file to the original one.
I need this variable in order to add an event listener which will look for changes in that particular variable (not sure how to do that either).
Here's are what you are looking for it's working:-
Put this in your forsok.php
<div id="input">
<input type="text" id="number" name="value">
<b id="show_result"></b>
</div>`
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('#number').on('keyup',function(e){
if(e.which == 13){
var get_var_name = $(this).val();
$.get('result.php',{number:get_var_name},function(data,status){
if(status == 'success'){
alert(data['show']);
$('#show_result').text(data['show']);
}else{
alert('Nothing');
}
});
}
});
</script>
For hej.php:-
<?php
$one=$_GET['number'];
if(empty($one)) {
echo "Can't be blank";
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$show=$one*2;
$arr = array(
'show'=>$show
);
header('Content-Type:application/json');
echo json_encode($arr);
exit();
// echo $show;
} else {
echo "NaN";
$a['result']='null';
$a['error']='nan';
}
}
?>
First create an array of what should be the output. JSON encode that array and then you can parse the output in your ajax success handler. Like in your php file output like:
echo json_encode(array(
'result' => 'null',
'error' => 'nan'
));
Then in you ajax success turn the json into an object and parse data as you want:
success: function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data);
$('#utmatning').html(obj.result); // result value from your json return
$('#utmatning').append(obj.error); // error value from your json return
}
At last of your php file, add,
json_encode($a);
In ajax success,
success: function(html) {
$.each(html, function(index, element) {
alert(element.result);
alert(element.error);
//append to which ever div you want.
});
}
Now with this, you can get n number of array indexes from php
Instead of echoing strings here and there in in hej.php it might better to return JSON data to your ajax call. so you can evaluate if an error occured, which error it is or which valid result has been returned.
hej.php:
<?php
$one=$_GET['value'];
if(empty($one)) {
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$a['result']=$one*2;
$a['error']='ok';
} else {
$a['result']='null';
$a['error']='nan';
}
}
die(json_encode ($a));
?>
if $value was 1 that would return
{"result":"2","error":"ok"}
In forsok.php you could check the reults and act accordingly
...
$.ajax({
type: "GET",
dataType: "json",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(response)
{
if (response.error=='ok'){
$('#utmatning').html(response.result); // show response from the php script.
}
else{
console.log(response.result); // handle the error
}
}
});
...
Regards,
Stefan

If condition not working in model of codeigniter

I am trying to implement a "like" button for my website. I am using Codigniter, Ajax and Jquery. When the like button is clicked data should be entered to database and if unlike button is pressed data should delete from database. But I am facing a problem in model, data is not added to database when I click like button. Please help me to find a solution.
This is my Jquery file "likeitem.js"
function likeItem(postId)
{
if ($("#likeItem_"+postId).text() == "Like")
{
$("#likeItem_"+postId).html('Unlike');
var purpose = "Like";
}
else
{
$("#likeItem_"+postId).html('Like');
var purpose = "UnLike";
}
$.ajax({
type : "POST",
url : "http://localhost/codeig_smarty/index.php/user/likeItem",
data : "postId=" + postId + "purpose=" + purpose,
success : function()
{
}
});
return false;
}
This is my model "usermodel.php"
public function itemLike()
{
$id = $this->session->userdata('userID');
$postId = $this->input->post('postId');
$purpose = $this->input->post('purpose');
if($purpose=="Like")
{
// echo 'test';
// exit();
$data = array(
"userID" => $id,
"postTextID" => $postId,
);
$this->db->insert('like', $data);
}
else
{
echo 'hai';
}
}
This is my view file "home.tpl"
<li><a class="like-unlike" href="#" id="likeItem_{$item['postID']}" onclick="likeItem({$item['postID']})">Like</a></li>
This is my Controller "user.php"
public function likeItem()
{
$this->usermodel->itemLike();
}
You mistake here. You forgot to put & symbol. Try this code.
data : "postId=" + postId + "&purpose=" + purpose,
Full code:
If you want to manipulate result returned from ajax, you can do something on success block as following code :
$.ajax({
type : "POST",
url : "http://localhost/codeig_smarty/index.php/user/likeItem",
data : "postId=" + postId + "&purpose=" + purpose,
success : function(data)
{
// do seomthing here with data
// console.log(data) --> to see data return or not
}
});

Ajax not making function call to php function

I have ajax function in script as:
$.ajax({
url: 'http://www.somesitename.com/admin/exportToCSVAction',
type: 'GET',
data:{},
cache: false,
success: function() {
alert("sucess");
},
error: function () {
alert("error");
}
});
exportToCSVAction function in php as:
public function exportToCSVAction()
{
$exportBatch = 10;
$order = $this->getTableGateway('order');
$select = new Select();
$select->from('order');
$data = $order->selectWith($select)->toArray();
$batchDir = __DIR__ . '/../../../../../data/export/batch/' . $exportBatch;
mkdir($batchDir);
$fileNameWithFilePath=$batchDir . '/order2.csv';
if (file_exists($fileNameWithFilePath))
{
$this->downloadOrderCSVAction($fileNameWithFilePath);
}
else
{
$csvFile = fopen($batchDir . '/order2.csv', 'w');
$i = 0;
foreach($data as $record) {
if($i==0) fputcsv($csvFile, $this->getCsvHeader($record));
fputcsv($csvFile, $this->updateCsvLine($record));
$i++;
}
fclose($csvFile);
}
}
But every time its returning me error as alert.
When i run it directly through link:
http://www.somesite.com/admin/exportToCSVAction
It returns me result correctly. (downloads the file as expected)
But through ajax it gives me Error as a alert.
Through inspect element network tab i get following:
Please help me.
Where i am making mistake?
Note:
I also tried by removing data from ajax, but no effect
Edit :
$.ajax({
url: 'http://www.somesitename.com/admin/exportToCSV',
type: 'GET',
data:{},
cache: false,
success: function() {
alert("sucess");
},
error: function () {
alert("error");
}
});
exportToCSVAction function in php as:
public function exportToCSVAction()
{
$exportBatch = 10;
$order = $this->getTableGateway('order');
$select = new Select();
$select->from('order');
$data = $order->selectWith($select)->toArray();
$batchDir = __DIR__ . '/../../../../../data/export/batch/' . $exportBatch;
mkdir($batchDir);
$fileNameWithFilePath=$batchDir . '/order2.csv';
if (file_exists($fileNameWithFilePath))
{
//Code to download file
}
else
{
$csvFile = fopen($batchDir . '/order2.csv', 'w');
$i = 0;
foreach($data as $record) {
if($i==0) fputcsv($csvFile, $this->getCsvHeader($record));
fputcsv($csvFile, $this->updateCsvLine($record));
$i++;
}
fclose($csvFile);
}
}
Now with this code i am getting the alet sucess. But not downloading the file
You're getting a 404, so either there's a routing issue with your controller, or there's a fatal error somewhere in your controller action. One way to debug the controller action is try putting an error_log at the beginning of the exportToCSVAction function, something like:
error_log("BEGINNING OF FUNCTION");
Then check your apache error log and see if it logged the error. If it does log the error, then try putting another error_log statement after other statements inside the function and see if those are logged. You'll know which statement is causing the script to die if an error is not logged.

jquery ajax always results in 'error' even when it works

I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}

Categories