Yes I know there is so many question like mine, I looked all questions and answers but The solutions is given didn't help me.
I tried to post log-in information to a controller. I got http-200 but ajax success function doesn't called. Instead error function is calling back but it doesn't give a specific error message.
My button code:
<button id="loginButton" type="submit" class="btn btn-success pull-right" onclick="login()">Giriş</button>
My javascript code:
function login ()
{
var Name = $("#userName").val();
var Pssword = $("#userPassword").val();
var user =
{
'userName': Name,
'userPassword': Pssword
};
jQuery.ajax
({
type:"POST",
url:"http://localhost:8080/Login/CheckUser",
dataType: 'html',
data: user,
cache: false,
success: function() {
alert("hadi ya");
},
error: function(httpRequest, textStatus, errorThrown) {
alert("status=" + textStatus + ",error=" + errorThrown);
}
});
}
And my controller code:
public function CheckUser()
{
$data = $this->input->post();
$result = $this->LoginModel->CheckUser($data); //returns 1 or nothing
echo $result;
}
And my model code:
function CheckUser($data)
{
$this->db->where('userName', $data['userName']);
$this->db->where('userPassword',$data['userPassword']);
$query = $this->db->get('users');
if($query->num_rows == 1)
return TRUE;
else
return FALSE;
}
I spent whole day for this, What I am doing false?
/* Change few of your lines: */
<button id="loginButton" type="submit" class="btn btn-success pull-right" onclick="login(event)">Giriş</button>
AND
function login (e)
{
e.preventDefault();
var Name = $("#userName").val();
var Pssword = $("#userPassword").val();
...
and further remains same.
Related
This question already has answers here:
JavaScript variables undefined within setTimeout function
(5 answers)
Closed 2 years ago.
I run a function named hookUser to query a DB every 2 seconds to check if a user is online, but it raises this error:
cannot read innerHTML of undefined
I suspect it's because the async callback is not in same scope?
The issue is that I can't pass the button object into that callback, can I do it? If not, is there another way to make this work?
Any help is appreciated.
<script>
function hookUser(user)
{
console.log('HOOKED USER: '+user);
setInterval(
function(user)
{
var ajaxurl = 'checkonline.php',
data = {'username':user};
$.post(ajaxurl, data, function (response) {
var button = document.getElementById('button_'+user);
if(response){
console.log(user+'ONLINE');
//button.innerHTML = 'ONLINE';
//button.className = 'btn btn-xs btn-success';
}else{
console.log(user+'ONLINE');
//button.innerHTML = 'OFFLINE';
//button.className = 'btn btn-xs btn-danger';
}
});
},2000);
}
</script>
...
<div class="col-md-3">
<div class="col-md-12 thumb-user " >
<div>
<button id='button_<?php echo $current_user;?>' class='btn btn-xs btn-success' >Unknown</button>
<?php echo '<script>hookUser(\''.$current_user.'\');</script>';?>
...
Try to get it before the callback
...
var button = document.getElementById('button_'+user);
$.post(ajaxurl, data, function (response) {
console.log(button);
...
My issue was that I was trying to add a parameter to a function that couldn't take one, so the parameter was undefined for user, hence the button based on user ID was undefined.
NB: to anyone trying to copy this code, do not, the hosting site will think you're DDOSing them, instead get user's items at once from DB, then load it into an array.
console.log('HOOKED USER: '+user);
setInterval(
function()
{
var ajaxurl = 'checkonline.php',
data = {'username':user};
var button = document.getElementById('button_'+user);
$.post(ajaxurl, data, function (response) {
if(response){
console.log(user+'ONLINE');
button.innerHTML = 'ONLINE';
button.className = 'btn btn-xs btn-success';
}else{
console.log(user+'ONLINE');
button.innerHTML = 'OFFLINE';
button.className = 'btn btn-xs btn-danger';
}
});
},2000);
}
I need a ajax call to post data to the database and fetch the data from database and update in live. I have the following codes
HTML Form
<div class="hover_bkgr_fricc">
<span class="helper"></span>
<div>
<div class="popupCloseButton">×</div>
<p>
<form>
<input type="hidden" name="check_num" value="123" />
<p>Please provide more details</p>
<input type="text" name="reason" />
<a id="submit">Mark Reviewed</a>
</form>
</p>
</div>
</div>
<b id="review_result"></b>
<a class="trigger_popup_fricc">
<button> Mark Reviewed</button>
</a>
Javascript Block
$(document).ready(function() {
$(".trigger_popup_fricc").click(function() {
$('.hover_bkgr_fricc').show();
});
$('.popupCloseButton').click(function() {
$('.hover_bkgr_fricc').hide();
});
$('#submit').click(function() {
var check_num = $('input[name=check_num]').val();
var reason = $('input[name=reason]').val();
var form_data =
'check_num=' + check_num +
'&reason=' + reason;
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(html) {
//if process.php returned 1/true (send mail success)
if (html == 1) {
//hide the form
$('.hover_bkgr_fricc').fadeOut('slow');
$('#review_result').html(data);
} else alert('Sorry, unexpected error. Please try again later.');
}
});
});
And the php block
$link = mysqli_connect($HOST, $USER, $PWD, $DB_NAME);
$check_num = $_POST['check_num'];
$reason = mysqli_real_escape_string($link, $_POST['reason']);
$insert = mysqli_query($link, "INSERT INTO `vloer_paylink_reason` (`id`, `check_number`, `reason`) VALUES (DEFAULT, '$check_num', '$reason')");
$update = mysqli_query($link, "UPDATE vloer_paylink SET reviewed = 1 WHERE check_number ='$check_num'");
$get_check_data = mysqli_query($link, "SELECT reviewed FROM vloer_paylink WHERE check_number = '$check_num'");
$check_data = mysqli_fetch_array($get_check_data);
if($check_data['reviewed']==1){
echo "Reviewed done";
}
else {
echo "Not Reviewed done";
}
Data is inserting and updating to the database but after that not returning to html update. Its returning false (Sorry, unexpected error. Please try again later.)
Add .error : function(e){ console.log(e)} to your ajax call, to return the error.
The function will be:
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(data) {
if(data == "Reviewed done"){
// code goes here
}
},
error : function(e) { console.log(e)} // this will print error
});
You are sending Reviewed done or Not Reviewed done in the php code as a response. Change the javascript code like below.
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(response) {
//if process.php returned 1/true (send mail success)
if (response === "Reviewed done") {
//hide the form
$(".hover_bkgr_fricc").fadeOut("slow");
$("#review_result").html(response);
} else alert("Sorry, unexpected error. Please try again later.");
},
error: function(error) {
console.log(e);
} // To catch any network errors
});
In view_candidates form in my application, I have a button with text REQUEST CONTACT INFO. When I click on the button, the text will be changed automatically to FINISH.
Now what happens: When I refresh the page the button text automatically changes to REQUEST CONTACT INFO.
To overcome this, I gave a status column in my database.
What I want:
Once user click on the button, the status should change from 0 to 1.
With status, I want to display my button text like: if status=0 button should be REQUEST CONTACT INFO, else it should be FINISH.
Button code:
<td>
<button type="button" id="button" class="btn btn-info" onclick="getConfirmation(id);">
<b>REQUEST CONTACT INFO</b>
</button>
</td>
SCRIPT:
<script>
function getConfirmation(id)
{
var retVal = confirm("your request is confiremed ?");
if(retVal)
{
$('#button').text('Finish');
$.ajax({
url: "Candidate/user_view_candidates/change_status",
type: "post",
data: id,
success: function (response)
{
//location.reload();
alert('success');
}
});
}
}
</script>
Controller code:
public function change_status()
{
$id = $this->input->post('candidate_id');
$status = $this->db->query("select status from candidates_details where id = candidate_id")->row()->status;
if($status==0)
{
$status = 1;
}
else
{
$status = 0;
}
$data=array('status'=>$status);
$this->db->where('candidate_id',$id);
$this->db->update('candidates_details',$data);
}
Can someone help me? Thanks in advance.
Check this:
View
<input type="hidden" name="candidate_id" value="<?php echo $candidate_id; ?>"/>//your candidate_id
<button type="button" id="button" class="btn btn-info" >
<b><?php $status == 0? 'REQUEST CONTACT INFO':'FINISHED';?></b>//your status value
</button>
<script src="<?php echo base_url(); ?>assets/plugins/jquery.min.js"></script>
js
$('#button').click(function() {
var candidate_id = $('input[name="candidate_id"]').val();
var url = 'your_cntroller_name/change_status/';
$.ajax({
url: your_base_url + url,
type: 'POST',
data: {'$candidate_id': $candidate_id},
dataType: 'JSON',
success: function(data) {
$('#button').text('FINISHED');
}
});
});
Controller
public function change_status() {
$candidate_id = $this->input->post('candidate_id');
$this->your_model->update_status($candidate_id);
echo true;
exit;
}
Model
public function update_status($candidate_id) {
//your query toupdate status
}
complete step by step solution is
step -1
in your view
<td><button type="button" id="button" class="btn btn-info" onclick="getConfirmation(row id);"><b>REQUEST CONTACT INFO</b></button></td>
getConfirmation(id){
$.ajax({
url: "url_to_your_controller/change_status",
type: "post",
data: id,
success: function (response) {
location.reload();
}
});
}
step -2
in your controller
change_status(){
$id = $this->input->post('id');
$status = $this->db->query("Your query")->row()->status;
if($status==1){
$status = 0;
} else {
$status = 1;
}
$data=array('status'=>$status);
$this->db->where('id','id');
$this->db->update('table_name',$data);
}
from your question I understand that you are displaying your record in a grid/ table and for each record in a row you have a button when you click on button it change the status of the record.
so the solution is simple onclick change the status using ajax call and in DB add a field status against each record which will be 0 by default and after onclick it'll be updated to 1
on page load you've to implement in your view a check
e.g
<?if(status==0){?>
<td><button type="button"><b>Working</b></button></td>
<? } else { ?>
<td><button type="button"><b>Finished</b></button></td>
<? } ?>
i have made function where i can add a row after confirming. the problem is, after submit button, the tables dont reload and show error function alert.actually data success saved and i have to refresh the page so that the table can reload. here is my ajax jquery code:
function reloadPage()
{
window.location.reload()
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('activity/save')?>";
} else {
url = "<?php echo site_url('activity/update_activity')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form-input').serialize(),
dataType: "JSON",
success: function(data)
{
$('#myModal').modal('hide');
reloadPage();
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
<button id="btnSave" onclick="save()" class="btn green">
"fa fa-save"> save</button>
my controller:
public function save() {
$actype = $this->input->post('actype');
$activity_name = $this->input->post('activity_name');
$project = $this->input->post('project');
$portion = $this->input->post('portion');
$activity = $this->input->post('actid');
$data = array(
'activity_type_id'=>$actype,
'activity_name' =>$activity_name,
'project_id' =>$project,
'portion' =>$portion,
'activity_id' => $activity
);
$this->activity->insertactivity($data);
redirect("activity/input");
}
after i've clicked button save,alert('Error adding / update data'),but actually after reload page data has saved.
where is code error in my ajax code?
Force a reload from the server.
window.location.reload(true);
When you don't specify true the reload may be from the browser cache if available.
Also, in the controller, redirect("activity/input"); is not the appropriate response to an AJAX request. Try something like this instead.
$this->activity->insertactivity($data);
echo json_encode(array('result' => TRUE));
Your controller code could also be much more concise. Consider this
public function save()
{
$data = array(
'activity_type_id' => $this->input->post('actype'),
'activity_name' => $this->input->post('activity_name'),
'project_id' => $this->input->post('project'),
'portion' => $this->input->post('portion'),
'activity_id' => $this->input->post('actid')
);
//Assuming insertactivity returns TRUE if the insert works and FALSE if not
$results['result'] = $this->activity->insertactivity($data);
echo json_encode($results);
}
You can check the "result" in success function
success: function(data)
{
if(data.result === true)
{
$('#myModal').modal('hide');
reloadPage();
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
} else {
//do something to the DOM to tell about the problem
//which probably means you should add that to your controller's response.
}
},
Form validation works, but I can't get the Ajax call to fire correctly. The submitHandler is being reached, but the Ajax call isn't. I have included a Fiddle at the bottom, but obviously you can't fire ajax calls from there.
$(".player-code, .submit").hide();
//VALIDATION
$(function () {
$("#form").validate({
rules: {
playerClass: {
required: true
}
},
submitHandler: function () {
var accountNumber = $(".accountNumber").val();
var domain = $(".domain").val();
var playerClass = $(".playerClass").val();
var dataString = accountNumber + playerClass;
//Save Form Data........
$.ajax({
type: "POST",
dataType: "json",
url: "/",
contentType: "application/json",
data: dataString,
success: function () {
$(".player-code").show();
$('.render-info').html("<div class='alert alert-success'>You've successfully built your player code</div>");
},
failure: function () {
$('.render-info').html("<div class='alert alert-failure'>Submission Error</div>");
}
});
}
});
});
jQuery.validator.addMethod("domainChk", function (value, element, params) {
if (this.optional(element)) return true;
var regExp = new RegExp("^(?!www\\.|http:\/\/www\.)(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$");
return regExp.test(value);
}, "Valid hostname required for player code");
jQuery.validator.addClassRules({
domainChk: {
domainChk: true
}
});
$('input[type="text"]').on('click keyup blur', function () {
if ($('#form').valid()) {
$(".submit").show();
} else {
$(".submit").hide();
}
});
//PREPOPULATE ACCOUNT FROM QUERY STRING
var url = window.location.href;
var regex = /=.*/; // match '=' and capture everything that follows
var accountId = url.match(regex);
$(".accountNumber").val(accountId).remove("=");
//
jsFiddle: Link
There is no failure: option for $.ajax(). If you want to see any errors that happen in the ajax call, then use error: to capture the error.
To make form submit you should use
<button class="btn btn-default submit" type="submit">Submit</button>
instead of <div class="btn btn-default submit">Submit</div>
submitHandler will be called only on native form submit.
Fiddle