My Ajax script keeps returning a result of unsuccessful. The console doesn't appear to show any errors. It just keeps throwing the alert window saying "error" instead of showing the result.
Ajax
$.ajax
({
url: 'query.php',
type: 'POST',
dataType:'json',
data: {Category: 'test'},
success: function(result)
{
if(result)
{
console.log(result);
alert(result);
}
},
error: function()
{
alert("error");
}
}); // end ajax call
php
$cat = $_POST['Category'];
echo $cat;
please check your query.php page. and make sure this page return some response either data or error massage like statusText="Error".
Do ajax function like below
$.ajax({ url: 'query.php',
type: 'POST',
dataType:'json',
data: {Category: 'test'},
success: function(result)
{
if(result.success=="TRUE")
{
console.log(result);
alert(result.cat);
}
},
error: function()
{
alert("error");
}
});
In query.php
$cat=$_POST['category'];
if(!empty($cat)){
$data['success']="TRUE";
$data['message'] = "Category Found.";
$data['cat']='$cat';
}
else{
$data['success'] = "False";
$data['message'] = "Category not found.";
}
die(json_encode($data));
jquery ajax document
option 1
response a json from php
example: echo "{}";
option 2
remove dataType: 'json'
Related
I'm learning PHP and JS, and while doing a Get with Ajax, the PH return is coming in white. I'm turning the net but not finding anything, I'd like some help.
$idEvent = $_REQUEST["idEvent"];
$event = $this->model->getById($idEvent);
header('Content-type: application/json');
echo json_encode($event, JSON_PRETTY_PRINT);
exit;
$('#ShowEvent').click(function() {
var idEvent = document.getElementById("ShowEvent").getAttribute("idEvent");
$.ajax({
url: 'http://localhost/salgadar/public_html/Event/GetEventById',
type: 'get',
data: {
idEvent: idEvent
},
dataType: 'JSON',
success: function(data) {
alert('AJAX call was successful!');
$("#AjaxReturn").html(data)
},
error: function() {
alert('There was some error performing the AJAX call!');
}
});
console.log(data);
});
ReferenceError: data is not defined
First place the console.log() inside your ajax call, like this:
$.ajax({
url: 'http://localhost/salgadar/public_html/Event/GetEventById',
type: 'get',
data: {
idEvent: idEvent
},
dataType: 'JSON',
success: function(data) {
alert('AJAX call was successful!');
console.log(data); //HERE CODE
$("#AjaxReturn").html(data);
},
error: function() {
alert('There was some error performing the AJAX call!');
}
});
Then tell me what appears and we will continue to solve the problems.
Ajax success does not work without alert message.
there is no error in the console.
$.ajax({
url: "<?php echo base_url(); ?>Sensor/ConnectionTypeList",
type: "POST",
data: {'model_id': model_id},
dataType: 'json',
success: function (data) {
console.log(data); //not runnig
//alert(''running);
if (document.getElementById("offset")) {
document.getElementById("offset").value = data[0].offset;
}
if (document.getElementById("multiplier")) {
document.getElementById("multiplier").value = data[0].multiplier;
}
if (document.getElementById("func")) {
document.getElementById("func").value = data[0].func;
}
if (document.getElementById("meas_command")) {
document.getElementById("meas_command").value = data[0].meas_command;
}
if (document.getElementById("read_command")) {
document.getElementById("read_command").value = data[0].read_command;
}
},
error: function () {
alert('Error.');
}
});
Is the result type JSON? In that case you need to parse the returned result in order to use it, like this:
$.ajax({
url: "<?php echo base_url(); ?>Sensor/ConnectionTypeList",
type: "POST",
data: {'model_id': model_id},
dataType: 'json',
success: function (data) {
data = JSON.parse(data);
console.log('>>', data);
...
I always use '>>' (or something like that) inside a console.log to make sure you always see a console message, even if the result is empty. Check the console log to see if the result and its type.
I am trying to figure out how to just display a particular response from php using ajax for example. I have a php which gives the following response -
echo 'Success'; //Display only this
//Some other process
echo 'Something else for other process';
JS
$.ajax({
type: "POST",
url: "some.php",
data: {action: 'test'},
dataType:'JSON',
success: function(response){
$( '#name_status' ).html(response);
}
});
Use if else.
And while sending AJAX request, send conditional parameters.
For example, flag: set it to either yes or no.
Get these parameters $_POST ed in PHP back end.
Depending upon the value of AJAX sent parameter, print the response.
JS:
$.ajax({
type: "POST",
url: "some.php",
data: {action: 'test', 'flag' : 'yes'},
dataType:'JSON',
success: function(response){
$( '#name_status' ).html(response);
}
});
Set flag to yes or no // This is just sample.
In PHP,
if (isset($_POST['flag'] && $_POST['flag'] == 'yes') {
echo 'Success'; //Display only this
}
else {
echo 'Something else for other process';
}
You will have send json_encode to receive a JSON response and will have to accordingly change the PHP too. Below is the updated code that you can try:
PHP:
if($_POST['action'] == 'test') {
$returnArray = array('message' => 'Success');
} else {
$returnArray = array('message' => 'Something else for other process');
}
echo json_encode($returnArray);
JS
$.ajax({
type: "POST",
url: "some.php",
data: {
action: 'test'
},
dataType: 'JSON',
success: function(response) {
var responseObj = jQuery.parseJSON(response);
$('#name_status').html(responseObj.message);
}
});
here I have jQuery ajax calling a .php file that SOMETIMES executes let's say the following
echo "hello"
Here it is:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function () {
}
});
I would like to know: is it possible to make the ajax return ERROR and not SUCCESS when something like the previous echo is executed in the PHP file? I mean, checking inside this $.ajax if the php file is executed as I would or not.
EXPLAINING BETTER:
I get error when the request could not be completed and success when it could. But I would like to get like a return value from this PHP file. If it returns 1, I wanna do something. If it returns 2, instead, I wanna do something else. Hope I explained it better..
Thanks in advance.
I recommend using json_encode() within your PHP file. For example:
echo json_encode(array('success' => 'do_foo'));
exit();
Then you can add a conditional within the success callback:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
dataType: "JSON", //tell jQuery to expect JSON encoded response
timeout: 6000,
success: function (response) {
if (response.success === 'hello'){
console.log(response);
} else {
console.log('else');
}
}
});
Based on your question make php return 1 or return 2. You can make it return 1 on failure and 0 (which is null) on success. Then you can do this for your ajax return.
$.ajax({
type: "POST",
url: "YOUR URL",
data: dataString,
success: function(server_response)
{
if(server_response == 1)
{
alert("You have made a mistake");
return true;
}
HERE YOU WILL PUT WHAT HAPPENS ON SUCCESS
}
});
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function (msg) {
if (msg != "Hi")
{
//TODO
} else
{
//TODO
}
}
});
You can use error callback for this:
$.ajax({
type: "POST",
url: myurl.php
data: data_string,
timeout: 6000,
success: function () {
},
error: function() {
/* Code reacting to error here */
}
});
Also, there are other callback opportunities which you can check out at $.ajax documentation page.
If you are going to "say" fron PHP that there is an error, this can be done with 2 ways:
You can print in PHP a keyword meaning an error and then check it in you success function:
success: function (data) {
if (data == 'error') {
} else {
}
}
Or, the other way, you can provide with PHP right headers to cause "error". Then you can use the error callback as usual. I would choose this way.
JavaScript
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
success:function (data) {
if (data==null) { alert("darnit!!!!");}
//$("#response").append(data);
alert(dataString);
}
});
});
in PHP file just a simple
print_r($_REQUEST);
Also tried
echo "got iT!";
But nothing, been looking of over tried differant things but no luck
first //alert (dataString); works
but after the success:function (data) I don't get any alerts - no response within the page!
What am I doing wrong?
There's a SyntaxError in your snippet. I'm not sure if that's also in your real code.
Be sure to use json_encode in your PHP file and dataType: 'json' in jQuery.ajax. And always use an error callback as well. You don't want your application to become indefinitely frozen if something fails.
Something like this:
$.ajax({
url: 'api.php',
data: {
action: 'greet',
foo: 'bar',
baz: 'quux'
},
type: 'POST',
dataType: 'json',
}).then(function (response) {
console.log(response); // DEBUG
if (response.error) {
alert('Greet Error: ' + response.error);
} else {
alert(response.greet);
}
}).catch(function (jqXHR) {
console.log('AJAX Error', jqXHR); // DEBUG
alert('AJAX Error: Request failed');
});
PHP:
<?php
$input = $_POST;
$response = array();
if (!isset($input['action'])) {
$response['error'] = 'Action parameter required';
} else {
if ($input['action'] === 'greet') {
if (!isset($input['foo']) || !isset($input['bar'])) {
$response['error'] = 'Invalid greet request';
} else {
$response['greet'] = 'Welcome home, David!';
}
} else {
$response['error'] = 'Unknown action';
}
}
header('Content-Type: application/json; charset=utf8');
echo json_encode($response);
First: you missed dataType property from ajax function, next, you need to pass json type data, and you had a syntax error in code, try this:
$.ajax({
type : 'POST',
url : 'post.php',
dataType: 'text',
data: {
data_to_pass: dataString
},
success:function (data) {
if (data==null) {
alert("darnit!!!!");
} else {
//$("#response").append(data);
alert(dataString);
}
});
});
in PHP:
$dataString = $_POST['data_to_pass'];
if($dataString) {
echo "got IT!";
}
JQuery ignoring your data return usually means it doesn't understand the format that's being returned, or doesn't know what to expect. Set the dataType to an acceptable format and also double check that your PHP script is actually sending something back to the page in Firebug's console.
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
dataType: 'text',
success:function (data) {
if (data==null) { alert("darnit!!!!");}
//$("#response").append(data);
alert(dataString);
}
});
});
I would like share the following, and I think I've solved the problem.
Besides the fact that I did made a mistake, retrieving the values from the form a bit wrong.
so the first alert gave me name=[Object name], now that was stupid.
The problem of not getting results seemed to be a problem with jquery itself, in my case.
I do not know if it is the same problem other people are having. I replaced the included file of jquery 1.7 with 1.4.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
than with the following code (only from $.ajax).
var dataString = $("#contactForm").serialize();
$.ajax({
type: 'POST',
url: './php/mail.php',
data: dataString,
success: function(msg){
if (msg === 'sent'){
$('#success').text('Message sent!');
} else{
$('#success').text('Mail Error. Please Try Again.!');
}
}
});
Now i have it working - and gonna tweak it a bit to my needs!
Thx all for all help!
Try this:
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
success:function (data) {
if (data===undefined) { alert("darnit!!!!");}
//$("#response").append(data);
alert(data);
}
});
});
Also I would look into using json_encode on an array in your php file and returning a json object.