Need help in clearTImeout - ajax

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);

Related

populating dropdown based in first selection

My COntroller
public function gettestRecieve() {
$test = array('recieve' => $this->input->post('recieve'));
$data = $this->test->getrecieve($test);
echo json_encode($data);
}
My Model
function getAcademic($test) {
$this->db->select('a_y');
$this->db->where($test);
$this->db->distinct();
$result = $this->db->get('table');
$return = array();
if($result->num_rows() > 0){
$return[''] = 'select';
foreach($result->result_array() as $row){
$return[$row['a_y']] = $row['a_y'];
}
}
return $return;
}
My view
$(document).ready(function () {
$('#test').change(function () {
var add = $(this).val();
//console.log(add);
$.ajax({
url: "<?php echo base_url();?>getAcademic",
method: "POST",
data: {testing: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
//alert(data[0].Ayear);
$('#good').html('<option value="'+ Ayear +'" >'+ Ayear +'</option>');
}
})
});
});
this gives me an error object HTMLSelectElement what does it mean, when i tried to look at my console it gives me a right value {"": "A & Y", 2014-2015: "2014-2015"} but in frontend gives an error, how could i fix this! can someone know this error, thanks and advanced

return undefined error in ajax response while image validation using codeigniter

Below is my code here validation working fine but while no validate at that time else part is working but its return undefined and showing in alert, how remove this undefined
<?php
public function doupload()
{
$upload_config['upload_path'] = './assets/upload/';
$upload_config['allowed_types'] = '*';
$upload_config['max_size'] = '500';
$upload_config['max_width'] = '300';
$upload_config['max_height'] = '300';
$this->upload->initialize($upload_config);
if (!$this->upload->do_upload('Filedata')) {
$upload_info = array(
'error' => strip_tags($this->upload->display_errors())
);
echo json_encode($upload_info);
}
else {
$upload_info = $this->upload->data();
echo json_encode($upload_info);
}
die;
}
?>
<script>
'onUploadComplete': function(file, data,response) {
var obj = JSON.parse(data);
alert(obj.error);
if(obj.error != '')
{
$('.msg').show();
}else{
go_next = true;
data_arr.push(obj.full_path);
}
},
</script>

Codeigniter form validation with ajax

I want to have a comments box in my website using codeigniter with Ajax. I want if the comment success show new comment. Else show validation error. How to do it?
This is my controller form validation
if ($this->form_validation->run() == TRUE) {
$this->load->model('comment_model');
$this->load->model('user_model');
if($this->comment_model->insert_comment())
{
$data['user_comment']= $this->user_model->get_user_session($this->session->userdata('user_id'));
$data['new_comment']= $this->comment_model->get_one_comment();
$this->load->view('user/insert_comment',$data);
}
} else {
echo validation_errors();
}
This is my ajax success function.
success: function (data) {
if (data)// this is what is need. How to make a if condition
{
$('ol#update').prepend(data);
$('ol#update li:first').slideDown('slow');
}
else
{
$('#myerror1').html(data);
}
}
Return answer from controller as Json and parse it in success function.
if ($this->form_validation->run() == TRUE) {
$this->load->model('comment_model');
$this->load->model('user_model');
if($this->comment_model->insert_comment()) {
$data['user_comment']=$this->user_model->get_user_session($this->session->userdata('user_id'));
$data['new_comment']= $this->comment_model->get_one_comment();
// third argument means, return template as string instead of echo.
$data = $this->load->view('user/insert_comment',$data, TRUE);
$array = array();
$array['success'] = true;
$array['data'] = $data;
} else {
$array = array();
$array['success'] = false;
$array['data'] = validation_errors();
}
echo json_encode($array);
}
And in success function:
success: function (data) {
var jsonData = JSON.parse(data);
if (jsonData.success == true) {
$('ol#update').prepend(jsonData.data);
$('ol#update li:first').slideDown('slow');
} else {
$('#myerror1').html(jsonData.data);
}
}

Check customer email is already exist in magento using ajax prototype

I want to check customer email is already exist or not using ajax prototype. I tried lots of things but it is not working. I write my code like this.
<script type="text/javascript">
//<![CDATA[
var dataForm = new VarienForm('form-validate', true);
Validation.add('validate-emaila', 'Email already exist', function(v) {
var url = '/customer/account/checkEmail/email?email=' + encodeURIComponent(v);
var ok = false;
new Ajax.Request(url, {
method: 'get',
asynchronous: false,
onSuccess: function(transport) {
alert(transport.responseText);
var obj = response = eval('(' + transport.responseText + ')');
validateTrueEmailMsg = obj.status_desc;
if (obj.ok === false) {
Validation.get('validate-email').error = validateTrueEmailMsg;
ok = false;
} else {
ok = true; /* return true or false */
}
},
onFailure: function(){ alert('something wrong') },
onComplete: function() {
if ($('advice-validate-email-email')) {
$('advice-validate-email-email').remove();
}
if ($('advice-validate-email-email_address')) {
$('advice-validate-email-email_address').remove();
}
if ($('advice-validate-email-billing:email')) {
$('advice-validate-email-billing:email').remove();
}
if ($('advice-validate-email-shipping:email')) {
$('advice-validate-email-shipping:email').remove();
}
if ($('advice-validate-email-_accountemail')) {
$('advice-validate-email-_accountemail').remove();
}
}
});
return ok;
});
//]]>
</script>
I called a function In customer/accountcontroller
public function checkEmailAction()
{
$bool = 0;
$email = $this->getRequest()->getParam('email');
$customer = Mage::getModel('customer/customer');
$customer->loadByEmail($email);
if ($customer->getId()) {
$bool = 1;
}
$jsonStatus = 200;
$info = array( "status" => $bool);
$this->getResponse()->setBody(json_encode($info))->setHttpResponseCode($jsonStatus)->setHeader('Content-type', 'application/json', true);
return $this;
}
I am getting wrong response from php function. it is returning full page html. instead of 0 or 1.
I have tried lots of thing but giving same response. Can any one tell me what is wrong in this?
it is wrong code for checking customer.You need to add website id to customer load
First need to change customer check url move from customer accountcontroller.php to checkout onepagecontroller.php. Because magento cannot easly add to accountcontroller.php
url ='<?php echo $this->getUrl('checkout/onepage/checkEmail', array('_secure'=>true)); ?>'
var request = new Ajax.Request(
url,
{
method:'get',
parameters: {email:encodeURIComponent(v)}
onSuccess: function(transport)
{
if(transport.status == 200)
{
var data = transport.responseText.evalJSON();
if(data.success==true){
}
}
}
}
);
In checkout onepagecontroller.phpadd the below code
public function forcecheckAction()
{
$response=array();
$email = $this->getRequest()->getParam('email');
try{
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email); //load customer by email i 
/* if customer has ,then login */
if($customer->getId()>0){
$response['success'] = true;
}else{
$response['success'] = false;
}
}catch(Exception $e)
{
$response['success'] = false;
$response['message'] = $e->getMessage();
}
$this->getResponse()->setBody(Zend_Json::encode($response));
}

AJAX response doesn't run any script

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();
});

Resources