How do I alert a json_encode() message and reload the page? The function below only displays an undefined alert message
if($result1 == false)
$response['msg'] = "Transfer failed due to a technical problem. Sorry.";
else
$response['msg'] = "Successfully transferred";
echo json_encode($response);
$("#transfer").click(function() {
$.ajax({
type : "POST",
url : "transferProduct.php",
data : {},
success : function(data) {
data = $.parseJSON(data);
alert(data.response);
location.reload();
}
});
});
You're trying to get a undefined index response
Provided that your PHP script returns:
{
"msg": "<your-message-here>"
}
In your javascript you can do it:
$.ajax({
type : "POST",
url: "transferProduct.php",
dataType: 'json',
success : function(response) {
alert(response.msg);
location.reload();
}
});
Use code in this way
transferProduct.php
if($result1 == false)
$response['msg'] = "Transfer failed due to a technical problem. Sorry.";
else
$response['msg'] = "Successfully transferred";
echo json_encode($response);
code page
$("#transfer").click(function() {
$.ajax({
type : "POST",
url : "transferProduct.php",
data : {},
success : function(data) {
datas = $.parseJSON(data);
alert(datas.msg);
location.reload();
}
});
});
or you can use $.getJSON in place of $.ajax
$("#transfer").click(function() {
$.getJSON("transferProduct.php",function (data){
alert(data.msg);
location.reload();
});
});
I think you should format the return to correctly identify in the background:
{"success":true,"message":"---------"}
then in JavaScript: data.message
Related
In my Web Application, I want to get an error message on every ajax call.
I m using CodeIgniter using I preferred to use flashdata for this purpose I came to know that flashdata don't update until the refresh
here is my ajax code
$.ajax({
url: '<?php echo base_url();?>Auth/userlogin',
type: 'POST',
data: {
email: email,
password:password
},
dataType: 'text',
success: function(data) {
var error="<?php echo $this->session->flashdata('signup'); ?>"
if(data=='no'){
$('#loginerror').html('<div class="alert alert-danger">'+error+'</div>');
}else{
$('#loginerror').html(' ');
$('#login').hide();
location.reload();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
And here is my Controller Where I m setting Flashdata
$this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run()==FALSE) {
$this->session->set_flashdata('signup',$this->form_validation->first_error());
echo 'no';
}
I don't see any reason whatsoever of using flash data in ajax cause you already can return any data you need in your response, in your example you can just do this:
if ($this->form_validation->run() == FALSE)
{
$this->json['signup'] = $this->form_validation->first_error();
$this->json['status'] = false;
echo json_encode($this->json);
}
else
{
$this->json['status'] = true;
// your code ....
}
and in your success:
dataType: 'JSON',
success: function(data) {
if(data.status == false) {
$('#loginerror').html('<div class="alert alert-danger">'+data.signup+'</div>');
} else {
$('#loginerror').html(' ');
$('#login').hide();
location.reload();
}
...
Below I have a JSON array in my main PHP file. As you can see $firstname_error and $lastname_error are variables which I intend to pass to AJAX in order to have it displayed in two separate divs. At the moment nothing shows up and am unsure why. Any insight is greatly appreciated.
PHP & JSON
if (empty($_POST["City"])) {
$city_error = "A city required";
}
if (empty($_POST["E-mail"])) {
$email_error = "E-mail is required";
}
echo json_encode(array("city" => $city_error, "email" => $email_error));
AJAX
$(document).ready(function () {
$(".form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "destination.php",
data: $(this).serialize(),
dataType: 'json',
cache: false,
success: function (data) {
if (data.trim() != '') {
$('.error4').html(data.city);
$('.error5').html(data.email);
}
},
error: function () {
}
});
});
});
.error4 and .error5 currently displays nothing.
Since you have dataType: 'json', the data variable passed to your success function is going to be an object so you can't use trim().
To check if the value exists in the response you can use hasOwnProperty on data:
success: function (data) {
$('.error4').text(data.hasOwnProperty('city') ? data.city : '');
$('.error5').text(data.hasOwnProperty('email') ? data.email : '');
},
Hope this helps!
I believe your if condition is not true, So try changing your success function like this:
success: function (data) {
if (data.city.trim() != '') {
$('.error4').html(data.city);
}
if (data.email.trim() != '') {
$('.error5').html(data.email);
}
}
Ok, I figured it out. Use if(data !== null) instead of if (data.trim() != '')
I'd like to display file upload error on an ajax alert error message.
This is my ajax:
$.ajax({
url : url,
type : 'POST',
cache : false,
contentType : false,
processData : false,
data : all_data,
dataType : 'JSON',
success : function(data)
{
if (data.result != 0) {
toastr.options = {
closeButton : false,
progressBar : false,
showMethod : 'slideDown',
timeOut : 3000
};
toastr.success('UPLOAD SUCCESS', 'Attention...');
if(activeid != 0){
if($("#tl_responder").val() != "" && $("#tl_dept").val() != "" && $("#tl_jawab").val() != ""){
toastr.success('MAIL IS SENT', 'ATTENTION...');
}
}
} else { window.location.href = "<?php print base_url(); ?>complaint/detail?id=" + data.result + "#reloadafteradd"; }
},
error: function (jqXHR, textStatus, errorThrown, data)
{
toastr.options = {
closeButton : false,
progressBar : false,
showMethod : 'slideDown',
timeOut : 3000
};
toastr.error(errorThrown, 'Error...'); //THIS IS THE AJAX ERROR ALERT
if(!errorThrown){ toastr.error(data.upl_error, 'Error...'); }//This is not working
}
});
The AJAX error alert only shows alert when AJAX is not working. I'd like to display the file upload error here.
This is my controller that handle file upload when not uploading:
if ( ! $this->upload->do_upload('file')){
$response_array = array ('upl_error' => $this->upload->display_errors());
echo json_encode($response_array);
//return false;
}
You need to send a flag to specify if file uploaded successfully or not to do this send a success flag from your php code like this:
PHP CODE
if ( ! $this->upload->do_upload('file')){
// file not uploaded
$response_array = array ('success'=0,'upl_error' => $this->upload->display_errors('', ''));
echo json_encode($response_array);
}
else
{
// file uploaded
echo json_encode(array("success"=>1));
}
And then in your ajax success callback function you need to check that success flag like this
jQuery CODE
$.ajax({
url : url,
type : 'POST',
cache : false,
contentType : false,
processData : false,
data : all_data,
dataType : 'JSON',
success : function(data)
{
// if file upload success
if (data.success == 1) {
alert("File uploaed success");
}
// file not uploaded
else {
alert(data.upl_error);
}
}
});
I hope it will help you.
In success function to check response content, or use http_response_code(500) in php script to trigger ajax error function.
The AJAX error alert only shows alert when AJAX is not working. This is working fine because, the case your file is not uploading is not an ajax error, its a normal code flow.
To handle it, you have to return some status to manage it in success of ajax like:
success: function(response)
{
if(response == 1)
{
// do some thing
}
else
{
// do some thing
}
}
PHP:
if( check here file uploads or not )
{
echo 1;
}
else
{
echo 0;
}
I am trying to write a script that will add the video currently being viewed to a database of favourites. However every time it runs, an error is returned, and nothing is stored in the database.
Here is the JQuery
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"localhost/stumble/site/add_to_fav.php",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
The add_to_fav.php is this...
public function add_to_fav(){
$this->load->model('model_users');
$this->model_users->add_favs();
}
And the add_favs function is below
public function add_favs(){
if($this->session->userdata('username')){
$data = array(
'username' => $this->session->userdata('username'),
'title' => $this->input->post('heading'),
'embed' => $this->input->post('embed')
);
$query = $this->db->insert('fav_videos',$data);
if($query){
$response_array['status'] = 'success';
echo json_encode($response_array);
}}else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
}
Thank you for the input, this has me stuck but I am aware it may be something relatively simple, my hunch is that it is something to do with returning success or error.
Try
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"http://localhost/stumble/Site/add_to_fav",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
Also to use base_url in javascript. In your template view :-
<script>
window.base_url = "<?php echo base_url(); ?>";
</script>
Now you can use base_url in all your ajax scripts.
All of this worked before, I haven't changed anything and now it doesn't. I have two elements named with id="live_title" and id="live_game". AJAX purpose is to update them.
My jQuery:
var tytul = function getTitle(){
$.ajax({
type : 'GET',
dataType: 'json',
url : 'ajax/getTitle.php',
success : function(data) {
for (var prop in data) {
$('#live_'+prop).html(data[prop]);
}
}
});
}
setInterval( tytul, 10000 );
AJAX response as seen in Firebug:
{"title":"Some title title...","game":"Name of the game"}
PHP Code sending stuff:
header('Content-Type: application/json');
// creating assoc array here
echo json_encode(array( 'title' => $title, 'game' => $game));
JavaScript console is empty.
When I visit ajax/getTitle.php in my browser, there is no error and displayed is the same thing as normally in Firebug. Response gives correct header (it's "Content-Type: application/json").
I've added
error : function(data) {
alert(data);
}
To my .ajax() function. It pops [object Object]. for alert(data.title) or alert(data['title']) it's undefined
Try to console your ajax response first and then step forward to further operations
var tytul = function getTitle(){
$.ajax({
type : 'GET',
dataType: 'json',
url : 'ajax/getTitle.php',
success : function(data) {
//if successfull
console.log(data);
},
error:function(data){
//if error
console.log(data);
}
});
}
setInterval( tytul, 10000 );