I'm using ajax to get the returned value from php function, the call is correct but I can't access the data properly.
The ajax call is:
$.ajax({
data: {"hotel_id" : hotel_id},
url: '/get_type_check',
type: 'get',
success: function (response) {
console.log(response);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
If I print the console log shows:
<!DOCTYPE html>
comment:
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
{"status":["CAB2"]}
And the php function:
public function get_type_check(){
$type_checks=Hotel::get_type_checks($_GET['hotel_id']);
echo json_encode(array('status' => $type_checks));
}
How can I get the response.status?
Should I use return instead of "echo"?
You have to parse the response to json to catch it as json.
Just add the line:
var data = $.parseJSON(response);
So your ajax will as follows:
$.ajax({
data: {"hotel_id": hotel_id},
url: 'ajax.php',
type: 'get',
success: function(response) {
var data = $.parseJSON(response);
console.log(data.status);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
});
Related
Hi this code is working great, i am new in javascript ,what i am trying to do , print js default error message in my div.
<script type="text/javascript">
$(document).ready(function () {
var contranumber = <?php echo json_encode($data); ?>;
debugger;
if(contranumber)
{
$.ajax({
url: ApiUrl+'ActivateUser?contraNumber='+contranumber,
type: 'get',
success: function (data, xhr) {
alert(data.ErrorMessage);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
}else
{
}
});
</script>
<div><center>javascript message</center></div>
<center><h3> Check your Email</h3></center>
A few quick things first:
Remove center tags, as it is deprecated. (Official example is "No, really, don't use it.")
Remove debugger;, unless you want your browser to stop.
Give your elements some sort of identification, be it a class or ID.
$(document).ready(function() {
var contranumber = '{ "hello": "world" }';
var message = $('.message'); // the element the message will go in
if (contranumber) {
$.ajax({
url: ApiUrl + 'ActivateUser?contraNumber=' + contranumber,
type: 'get',
success: function(data, textStatus, xhr) { // you missed the textStatus parameter
message.text('it was successful'); // why log an error on success?
},
error: function(xhr, textStatus, errorThrown) {
message.text('Error in Operation:' + errorThrown); // give the actual error text
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message"></div>
<h3>Check your Email</h3>
$('#example center').text(data.ErrorMessage);
I usually do this:
$.ajax({
type: 'POST',
url: validateAjaxURL,
success: function (data) {
var returnData = data;
if (returnData.match("^selectedUno-")) {
$('#new_caregiver_popup_div').dialog('close');
} else {
$("#new_caregiver_popup_div").html(data);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});
UPDATE :
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#DivID').text(errorThrown);
}
Here is the link for your reference :
Show Error
I have an Ajax autocomplete box on an input field of a form. In jquery, I have the following ajax settings
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
alert("do something");
},
error: function (xhr, textStatus, thrownError) {
alert(xhr.status+ " "+ thrownError+ " " + textStatus);
},
dataType: "json"
});
On the server side, I have this php code
$data = array('type' => 'error', 'message' => 'Error: '.$text);
header('HTTP/1.1 400 Bad Request');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode($data));
All works fine both in case of success and in case of error. However, I didn't figure out how do I access from jquery the text I defined in php as $text
xhr.status is 400, textStatus is "error" and thrownError is "Bad Request", but no signs of what I defined as $text
What I am missing?
if you echo the $text variable in your file you can get to it from your javascript file.
php code:
echo $text;
change to javascript:
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
//do something with the data returned from php file
alert(data);//<---change to javascript code
},
error: function (xhr, textStatus, thrownError) {
alert(xhr.status+ " "+ thrownError+ " " + textStatus);
},
dataType: "json"
});
In your ajax post you defined a json call. In your php backend you defined a array, so you can access these params by key. Your array:
<?php
$arr = array();
$arr['message'] = 'What you like?';
$arr['errorCode'] = '12345';
die(json_encode($arr));
?>
In your case you will have access the data argument by adding the key, like data.message:
success: function(data){ alert(data.message); }
So, it have to look like that:
$.ajax({
type: "POST",
url: myUrl,
data: $("#id__form").serialize(),
success: function(data){
alert(data.message+' '+data.errorCode);
$('#someDivTag').html(data.message);
},
dataType: "json"
});
Got it, thanks to this article http://wingkaiwan.com/2012/10/21/deserialize-error-in-json-for-jquery-ajax/
The problem was that the variable data in the success callback handles automatically json, but I had to parse it in the error callback. This works:
error: function (xhr, ajaxOptions, thrownError) {
var error = JSON.parse(xhr.responseText);
alert(error.message);
}
I'm trying to get JSON data from another domain.
It returns status 200 but invokes an error in the callback function.
Is it possible to get the raw data or html or even just text when I get into the error callback?
Why is xhr.responseText undefined?
Here is part of my code:
$.ajax({
type: 'POST',
url: 'http://timetable.nctu.edu.tw/?r=main/get_cos_list',
dataType: 'jsonp',
crossDomain: true,
async: false,
data:{m_acy:'**',m_sem:'**',m_degree:'**',m_dep_id:'**',m_group:'**',
m_grade:'**',m_class:'**',m_option:'cos_code',m_crsname:'**',m_teaname:'**',
m_cos_id:'**',m_cos_code:'DAM1346',m_crstime:'**'},
jsonp: true,
success: function(json) {
$('#jjjj').html(json);
},
error: function(xhr, textStatus, errorThrown) {
$('#content').append("readyState: "+xhr.readyState+"<br>status: "+xhr.status+"<br>responseText: "+xhr.responseText+"<br><hr>");
alert('Ajax request error.' + xhr.responseText + xhr.responseData + errorThrown);
},
complete: function(xhr, textStatus)
{
alert(xhr.responseText + xhr.responseHtml);
alert(h.responseHtml);
}
});
I am doing an Ajax post to a specific page where I either can get an ID as response if everything went as expected or I could get a random html page and a http 400 as response if something went wrong. In the error case I want to open up the entire html page in a new window. I have tried the following but it is not working - it sets the variable data to [object Object] instead of the intended html page.
$.ajax({
type: "POST",
url: postUrl,
data:'message=' + message + '&' + 'title=' + title,
statusCode: {
400:function(data) {
var newWin = open('','windowName','height=300,width=300');
newWin.document.write(data);
},
},
success: function(json) {
alert("Post success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error connecting to page.");
}
});
Specify dataType : 'html' and change the success function variable. Example:
$.ajax({
type: "POST",
dataType: 'html',
url: postUrl,
data:'message=' + message + '&' + 'title=' + title,
statusCode: {
400:function(data) {
var newWin = open('','windowName','height=300,width=300');
newWin.document.write(data);
},
},
success: function(html) {
alert("Post success");
$("#myDiv").html(html);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error connecting to page.");
}
});
I have the following Coffeescript:
$(document).ready ->`
$.ajax 'http://www.omdbapi.com/?i=tt1285016',
type: 'GET'
dataType: 'json'
error: (jqXHR, textStatus, errorThrown) -> $('body').append "AJAX Error: #{textStatus}"
success: (data, textStatus, jqXHR) -> $('body').append "Successful AJAX call: #{data}"
However this genrates the following Javascript which doesn't look right to me:
(function() {
$(document).ready(function() {
return $.ajax('http://www.omdbapi.com/?i=tt1285016');
});
({
type: 'GET',
dataType: 'html',
error: function(jqXHR, textStatus, errorThrown) {
return $('body').append("AJAX Error: " + textStatus);
},
success: function(data, textStatus, jqXHR) {
return $('body').append("Successful AJAX call: " + data);
}
});
}).call(this);
Can anyone tell me where this is going wrong?
Thanks,
Adam
I couldn't compile your current code (CoffeeScript version 1.6.1), but if you remove the ` symbol after $(document).ready -> it compiles to
(function() {
$(document).ready(function() {
return $.ajax('http://www.omdbapi.com/?i=tt1285016', {
type: 'GET',
dataType: 'json',
error: function(jqXHR, textStatus, errorThrown) {
return $('body').append("AJAX Error: " + textStatus);
},
success: function(data, textStatus, jqXHR) {
return $('body').append("Successful AJAX call: " + data);
}
});
});
}).call(this);
I'm not sure how CoffeeScript handles line breaks, but I guess you're compiling a file with Windows end-of-lines (CRLF) on a *nix system and that causes the problem.
I'm saying that because something like the following code:
$(document).ready ->
$.ajax 'http://www.omdbapi.com/?i=tt1285016',
type: 'GET'
dataType: 'html'
error: (jqXHR, textStatus, errorThrown) -> $('body').append "AJAX Error: #{textStatus}"
success: (data, textStatus, jqXHR) -> $('body').append "Successful AJAX call: #{data}"
compiles to the one you've posted. (note that there is a line-break on line 3 after ,)