I am using a MVC and I have a button that is using an AJAX call to remove an uploaded image on the site.
This is my Model:
public function remove_document($documentID, $documentName)
{
$objData = $this->objDB
-> setStoredProc('attritionRemoveDocument')
-> setParam('documentID', $documentID)
-> setParam('documentName', $documentName)
-> execStoredProc()
-> parseXML();
return $objData->data->response;
}
The response back from this is either true or false.
Here is my controller:
public function deleteFile()
{
// Get the documentID we are removing
$documentID = $this->input->post('documentID');
$documentName = $this->input->post('documentName');
// Check if the file is even there
if (file_exists('./uploads/'.$documentName)){
// Remove file
unlink('./uploads/'.$documentName);
$removeFile = $this->submit_model->remove_document($documentID, $documentName);
return $removeFile;
}
}
And finally, my AJAX Call:
$('[name=deleteDocument]').click(function() {
var documentID = $(this).attr('documentID'),
documentName = $(this).attr('documentName');
//Delete the image
$.ajax({
type: 'POST',
url: '../deleteFile',
dataType: 'xml',
data: {
'documentID': documentID,
'documentName': documentName
},
success: function(msg) {
// On Success, remove the current file section
console.log(msg);
}
});
});
When i echo the $removeFile value in the controller, I see the true/false value however it never makes it to the success function of the AJAX call.
Any ideas?
in Controller
if the result is true
echo "OK"
if the result is false
echo "NO"
in your View and in success part
success: function(msg) {
if(msg=="OK"){
alert("DELETED");
}else{
alert("NOT deleted");
}
Your controller should not return BOOL if you are using it with ajax , Your AJAX call , should control the result by success method .
Related
I'm making a phone app using PhoneGap with PHP on the server side. the Login function has been working fine, but AJAX returns an error [object Object] while PHP returns the correct value's in JSON.
it's for making a phone app for an existing website and using its database.
the data my PHP prints is correct yet I receive an error response from ajax.
Alert(response)
Gives an [object Object] return value on error
whenever I try
alert(response.val)
I strangely get undefined, but in the network, I can see the printed data is correct in JSON.
{{"user_id":"390","response":"Success"}}
but when I look in the console on my browser I see an unexpected error.
Unexpected parameter ':'
my ajax function is as follows
$(document).ready(function () {
$("#btnLogin").click(function () {
var gebr = $("#login_username").val().trim();
var pass = $("#login_password").val().trim();
var dataString = "username=" + gebr + "&password=" + pass + "&login=";
var msg = "";
$("#message").html("Authenticating...");
if (gebr != "" && pass != "") {
$.ajax({
type: "POST",
data: dataString,
dataType: "json",
//contentType: "application/javascript",
crossDomain: true,
url: "http://url/page/app/index.php?&jsoncallback=?",
headers: "application/json",
success: function (response) {
var user_id = response.user_id;
var success = response.response;
localStorage.setItem("user_id", user_id);
window.location = "home.html";
alert("login successfull");
},
error: function (response) {
$("#message").html("error..");
alert(response);
}
});
} else {
msg = "Please fill all fields!";
$("#message").html(msg);
}
return false;
});
PHP
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$gebruikersnaam = $_REQUEST['username'];
$wachtwoord = md5($_REQUEST['password']);
$user = [];
//if user and password are filled
if (!empty($gebruikersnaam) && isset($wachtwoord)) {
//checks if user_id has been found
if (!$found_user_id) {
$msg = "user not found!";
print json_encode($msg);
} else {
if (($gebruikersnaam == $user['gebruikersnaam'] && $wachtwoord == $user['wachtwoord']) && ((!empty($user['single_allowed_ip_address_for_login']) && $user['single_allowed_ip_address_for_login'] == $_SERVER['REMOTE_ADDR'])|| empty($user['single_allowed_ip_address_for_login']))) {
//responds with this data
$user_id = $user['user_id'];
$response[] = array(
'user_id' => $user_id,
'response' => 'Success'
);
print json_encode($response);
} else {
$msg = "user is incorrect";
print json_encode($msg);
}
}
}
I have been wanting to get a successful response and saving the user_id in local storage so it can be used on a different page.
Edit:
after using console.log on the response i got an odd object.
abort: function abort()
always: function always()
catch: function catch()
done: function add()
fail: function add()
getAllResponseHeaders: function getAllResponseHeaders()
getResponseHeader: function getResponseHeader()
overrideMimeType: function overrideMimeType()
pipe: function pipe()
progress: function add()
promise: function promise()
readyState: 4
setRequestHeader: function setRequestHeader()
state: function state()
status: 200
statusCode: function statusCode()
statusText: "load"
then: function then()
<prototype>: {…
which is strange because none of these functions are made and the only thing which i can recognize is the statuscode.
You need to correct your JSON. {{"user_id":"390","response":"Success"}} is not valid JSON. It needs to be {"user_id":"390","response":"Success"}.
You're getting a strange object in your console.log because your response in the error: function (response)... is actually the jqXHR jQuery object and will not return your response directly in its arguments. Stick with success: function(response)... and output whatever your server sends back.
I'm working on a project where I have some jQuery code that is supposed to check if a certain row in the database exists. If the row does exist, The code within the success stage gets executed. But the problem I have with this script is when the 'checkdb' function gets executed the code within success happens even though the row doesn't exist in the database. What is causing this?
jQuery code
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
The jQuery above gets executed every minute, To check if the row is present.
The PHP code below is supposed to check if the row in the database exists. If it does, it should return a response which then ends up in the succeeding stage in jQUery. If it does not already exist, Do something else
PHP code
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing');
}
}
Why is it executing the succeeding stage even though the row does not already exist? Thanks in advance
response('content', 200, $headers) and `json()` helper also takes three param `json($data, status, $headers)`
methods take three parameters replace the content of the else
like
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing',404);
}
}
In jQuery, success block gets executed when response status code is 200. If you send status code as 404 which is in else block when DB is not exist, then error block will get executed instead of success. Laravel by default will send 200 as status code for AJAX requests in response.
Add dataType:"JSON"
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
datatype:'JSON',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
i have written this script in View. In onblur event i have check whether the mail id is already exits r not.for that i have to pass mailId id to the controller action and i want to get the return result.
$.ajax({
type: "POST",
url: "<?php Yii::app()->createAbsoluteUrl("Approval/checkMailid"); ?>",
data: mailId,
success: function() {
return data;
},
error: function() {
alert('Error occured');
}
});
public function actionCheckMailid($mailId)
{
$model = YourModel::model()->findAll('id = :mid', array(':mid'=>$mailId));
echo json_encdoe($model);
}
Just need to throw a 404 page and ajax error handle can catch it.
public function actionCheckMailid($mailId){
$exist = Yii::app()->db->createCommand('select count(*) from your_email_table where id_email = :id_email')
->queryScalar(array(
'id_email' => $mailId
));
if($exist > 0){
echo json_encode(array(
'success'=>true
));
}else{
throw new CHttpException('Email can not be found');
}
}
I am using codeigniter, i have written a function to check if a user password exists which it does. This is my model
The model: user
public function get_some_password($username,$password) {
$this->db->where('user_password', $password);
$this->db->where('user_username',$username);
$query=$this->db->get('some_users_table');
if($query->num_rows()==1){
return true;
}else{
return false;
}
the controller
public function check_password() {
$username=$this->uri->segment(3);
$temp_pass= $this->input->post('current_password');
$password=md5($temp_pass);
$this->user->get_some_password($username,$password);
}
The ajax on the view
//done on page load
var success1 = $(".success"); //a div on the view that appears if success
var error1 = $(".error"); //a div on the view that appears if error
success1.hide();
error1.hide();
$('#change_password').click(function() {
var username = $('#username').val();
dataString2 = $('#changpassword').serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>controller_name/check_password/' + username,
data: dataString2,
success: function() {
$('.success').html('password successfully updated!'),
success1.slideDown('slow');
},
error: function() {
$('.error').html('Wrong current password!'),
error1.slideDown('slow');
}
});
The problem: Ajax loads the success div even when the username or password returned is false, where am i missing something
This is a correct behavior as jquery error is executed when response code is not 200:
1) You can parse returned value in success method.
e.g.
success: function(data) {
if (data == 'true') {
// Success
} else {
// Error
}
}
2) You can return error code from server 404, 500, 503 ... To trigger execution of error function.
e.g.
header("Status: 404 Not Found");
note: Header should executed before any output is done.
Try in your controller:
public function check_password() {
$username=$this->uri->segment(3);
$temp_pass= $this->input->post('current_password');
$password=md5($temp_pass);
if(!$this->user->get_some_password($username,$password)) {
$this->output->set_status_header('500');
return;
}
...
}
I am a bit stuck with my website, currently on the new section of my site(among others) the user rolls over a thumbnail and gets the articles abstract displayed below it, and then when they click on said thumbnail the article appears on the left of the page,
The ajax works by pulling the href from the link that surronds the thumbnail image and using that as the url for the method call, the problem is that the click version will also be using the same function call, I cannot work out how to show the different content depening on what even happends, currently I have this as my code,
<?php
if(isset($content)) {
foreach($category_name as $k => $v) {
echo "<h2 class='$v[category_name]'><a href='#'>$v[category_name]</a></h2>";
echo "<div class='$v[category_name]'>";
}
$replace = array(".", "png", "gif", "jpg");
$count = 0;
foreach($content as $k=>$v) {
$count ++;
$image_name = str_replace($replace, "", $v['image_name']);
echo "<a class='contentlink' href='index.php/home/get_content_abstract/$v[content_id]'>";
echo "<img src='/media/uploads/".strtolower($v['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
echo "</a>";
}
echo "</div>";
//die(var_dump($content));
}
?>
<script>
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
});
</script>
The method that gets called is,
public function get_content_abstract() {
$this->load->model('content_model');
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
This is called by the ajax following the link /get_content_abstract/3, where 3 or any other number is the articles ID.
How can I sort so that I can use this function again, but only show that body content of the article instead of the abstract if the link is clicked and mouseovered?
You can pass a call type variable and check for it in your php code. Notice I added data to your ajax calls.
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
data: "calltype=abstract",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
data: "calltype=full",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
pass a GET variable in the url of the ajax call.
You just pass an variable to the handler via GET or POST that tells the handler which content to show. As your AJAX calls are simple, you can simplify the calls and use load(). If you can't use $_GET or $_POST, just append the data in the URL:
$("a.contentlink").mouseover(function() {
// URL becomes index.php/home/get_content_abstract/3/abstract
$('#abstract').load($(this).attr("href")+'/abstract');
});
$("a.contentlink").click(function(ev) {
$('#main_menu').hide();
// URL becomes index.php/home/get_content_abstract/3/full
$('#left-content').load($(this).attr("href")+'/full');
return false;
});
And in PHP, you can use something like this:
public function get_content_abstract() {
$this->load->model('content_model');
if($this->uri->segment(4) == 'full') {
// Load full content
} else {
// Load abstract
}
$this->load->view('template/abstract', $data);
}