I have a problem retrieving the posted data from an ajax call, not sure what is wrong. The console output from the script below shows everything as expectred before the ajax call, but the data is not available in the connector
function updateOptions(data){
console.log(data);
console.log(data.id);
console.log(data.action);
var data = {id: data.id, action : data.action};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.connector.php?action=updateOptions',
data: JSON.stringify(data),
cache: false,
dataType : "json",
success: function(data, status) {
if(data.status == 'success'){
console.log('success');
console.log(data);
}else if(data.status == 'error'){
console.log('selects not updated');
}
},
error: function(data){
console.log('an error has occurred');
},
});
}
So the first 4 console.log entries show the data correctly, the first console.log in the success condition shows correctly. The second, shows:
Object {status: "success", msg: "Category added successfully", id: null, action: null, post: Array[0]}
the connector [more like a director]
case 'updateOptions':
error_log('Running updateOptions function ' . print_r($_POST, TRUE), 0);
$output = $sbb->updateOptions($_POST);
break;
Logs this:
Running updateOptions function Array\n(\n)\n,
if I try to echo $_POST['action'] or $_POST['data'] or something to the log I get an undefined index.
I am forcing the ajax call to return success in the class that the php case function is calling:
public function updateOptions($data){
$output = array(
'status' => 'success',
'msg' => 'Category added successfully',
'id' => $data['id'],
'action' => $data['action'],
'post' => $data,
);
return $output;
}
So the ajax call itself does work, it's the data that's not being passed.
Somehow I am not getting [or correctly retrieving] the data from the ajax post.
What is the problem here?
You're posting JSON, $_POST is populated with key=value pairs, don't mix up JSON with application/x-www-form-urlencoded or multipart/form-data (which is what php uses to populate $_POST.
To send application/x-www-form-urlencoded data with jQuery.ajax pass an object with the data as the data parameter
data: data, // removed JSON.stringify
Related
i have problem with ajax post submit
here is my script
function postad(actionurl) {
if (requestRunning) return false ;
if (! $("#editadform").valid()) {
validator.focusInvalid();
return false ;
}
$('#ajxsave').show() ;
requestRunning = true ;
var postData = $('#editadform').serializeArray();
$.ajax(
{
url : actionurl,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$('#diverrors').html(data.errors) ;
$('#divalerts').html(data.alerts) ;
if (data.status=='success') { alert(data.status);
$('#siteid').val(data.siteid) ;
if ($('#adimager').val())
$('#divlmsg').html(data.alertimage) ;
$('#editadform').submit() ;
} else {
$('#ajxsave').hide() ;
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('#ajxsave').hide() ;
},
complete: function() {
requestRunning = false;
}
});
$('.btn').blur() // remove focus
return false ;
}
This works on if (textStatus=='success') {
but when the action fails, alert(data.status) shows Undefined.
Using FireBug, I can see that the data is correctly returned. Why is data.status "Undefined" then?
If you don't specify the dataType field of an $.ajax() call in jQuery, it formats the response as plain text. A workaround to your code would be to either include dataType: "JSON" into your $.ajax() parameters, or alternatively, in your success function, parse the plain text response as a JSON object, by using the folllowing:
data = JSON.parse(data); // You can now access the different fields of your JSON object
UPDATE:
yes i have not status field in action url, how to add data status field in php code?
When creating your PHP script that is intended to return the JSON data, you first need to build an array and then encode it as JSON.
So, suppose you have a PHP script that either succeeds and produces some data that you put into a $data variable, or fails, then the following style could be adopted:
<?php
// ^^ Do your PHP processing here
if($success) { // Your PHP script was successful?
$response = array("status" => "success!", "response" => $data);
echo json_encode($response);
}
else {
$reponse = array("status" => "fail", "message" => "something went wrong...");
echo json_encode($response);
}
?>
I have added a property to a JSON data but I cannot access the data on JS it does not show. I am not new to Ajax and JSON but it is a apparent that I still have gaps in my knowledge when it comes to Ajax. Please help me understand how i can append data to my Ajax response.
I have this in a PHP controller class:
$x = '5';
if($request->ajax()){
return response()->json([
'total_questions' => $x,
'responseText' => $e->getMessage(),
], 500);
}
I want to access the total_questions property with JS/JQuery..
My JS AJAX callback is here:
console.log('errors -> ', data.total_questions); - returns undefined
$.ajax({
type:"POST",
url: APP_URL+"selfEvaluation/save",
data:$(this).serialize(),
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(data){
var errors = data.responseJSON;
console.log('data -> ', data);
console.log('errors -> ', data.total_questions);
if(data.status == 422){
// alert('422');
}
}
});
This is my console result
error: function(data){
is an incorrect method signature. See the definition at http://api.jquery.com/jquery.ajax/.
It should be
error: function(jqXHR, errorThrown, textStatus){.
You'll need to access the jqXHR.responseJSON property. So:
console.log('errors -> ', jqXHR.responseJSON.total_questions);
But I would question why you're returning a "500" status code for this request, when it appears to be a valid response. "500" means "Internal Server Error", which implies the server crashed, when it appears that it did not. If you return a "200" ("OK") status, your ajax code will go into the "success" callback and you can directly reference the "data" object in the callback to read your data.
try this if you will get a json response from your browser.
if($request->ajax()){
$result = array(
'total_questions' => $x,
'responseText' => $e->getMessage(),
], 500);
}
echo json_encode($result);
From my database i fetched some data as json string.But unfortunately i can't access the data which is returned as response. Following is my php page to fetch data:
require_once '../core/init.php';
$answer=$_POST['answer_body'];
$post_id=$_POST['userpost_post_id'];
$answerer=$_POST['users_user_id'];
if(isset($answer,$post_id,$answerer)){
if(!empty($answer) && !empty($post_id) && !empty($answerer)){
$db=DB::getInstance();
if($result=$db->post_and_fetch("CALL login.post_and_fetch_ans(?,?,?)",array($answer,$post_id,$answerer))->result()){
echo json_encode($result);
}else{
echo 'there was a problem';
}
}
}
It returned as following:
and in the receiving part is following:(it currently prints undefined)
$.ajax('../includes/verifyanswer.php',{
data:data,
type:"POST",
datatype:'json',
success:function(response){
alert(response['answer_body']); // prints undefined
},
error:function(response){
alert(response);
}
})
Your response is a string, not an array. You should use getJSON() to make sure the response is parsed into an object :
$.getJSON(
'../includes/verifyanswer.php',
data,
function(response) {
alert(response.answer_body);
}
);
I'm trying to send JSON data from a web page using JQuery, like this:
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: '{username: "wiiNinja", password: "isAnub"}',
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
In cake2.2, I have a controller named Ajax that has a method named "login", like this:
public function login($id = null)
{
if ($this->RequestHandler->isAjax())
{
$this->layout = 'ajax'; // Or $this->RequestHandler->ajaxLayout, Only use for HTML
$this->autoLayout = false;
$this->autoRender = false;
$response = array('success' => false);
$data = $this->request->input(); // MY QUESTION IS WITH THIS LINE
debug($data, $showHTML = false, $showFrom = true);
}
return;
}
I just want to see if I'm passing in the correct data to the controller. If I use this line:
$data = $this->request->input();
I can see the debug printout:
{username: "wiiNinja", password: "isCool"}
I read in the CakePHP manual 2.x, under "Accessing XML or JSON data", it suggests this call to decode the data:
$data = $this->request->input('json_decode');
When I debug print $data, I get "null". What am I doing wrong? Is my data passed in from the Javascript incorrect? Or am I not calling the decode correctly?
Thanks for any suggestion.
============= My own Edit ========
Found my own mistake through experiments:
When posting through Javascript, instead of this line:
data: '{username: "wiiNinja", password: "isAnub"}',
Change it to:
data: '{"username": "wiiNinja", "password": "isAnub"}',
AND
In the controller code, change this line:
$data = $this->request->input('json_decode');
To:
$data = $this->request->input('json_decode', 'true');
It works.
Dunhamzzz,
When I followed your suggestions, and examine the "$this->request->params" array in my controller code, it contains the following:
array(
'plugin' => null,
'controller' => 'ajax',
'action' => 'login',
'named' => array(),
'pass' => array(),
'isAjax' => true
)
As you can see, the data that I'm looking for is not there. I've already got the the proper routes code. This is consistent with what the documentation for 2.x says here:
http://book.cakephp.org/2.0/en/controllers/request-response.html
So far, the only way that I found to make it work, is as stated above in "My own Edit". But if sending a JSon string to the server is not the right thing to do, I would like to fix this, because eventually, I will have to handle third party code that will send JSon objects.
The reason you are struggling wit the data is because you are sending a string with jQuery, not a proper javascript object (JSON).
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: {username: "wiiNinja", password: "isAnub"}, // outer quotes removed
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
Now the data will be available as a PHP array in $this->request->params.
Also for sending a JSON response, please see this manual page. Most of your code there can be reduced to just 2 lines...
//routes.php
Router::parseExtensions('json');
//Controller that sends JSON
$this->set('_serialize', array('data'));
i have this little code to post to my server
$.ajax({
type: 'POST',
url: 'post.php',
data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: '' },
success: function(data){
alert (data)
}
});
Wondering how i can "catch" the different errors for ajax request:
for eg, post.php return 'token error' when invalid token has been posted, or 'invalid title' for missing title.
Thanks in advance
If the server sends something else than 200 status code you could use the error handler:
$.ajax({
type: 'POST',
url: 'post.php',
data: {
token: '123456',
title: 'some title',
url: 'http://somedomain.com',
data: ''
},
success: function(data){
alert(data);
},
error: function() {
alert('some error occurred');
}
});
If your server performs some validation on the request arguments maybe it could return a JSON object containing the error information (and set the proper Content-Type: application/json):
{ error: 'some error message' }
In this case you could handle this in the success callback:
success: function(data) {
if (data.error != null && data.error != '') {
// TODO: the server returned an error message
alert(data.error);
} else {
// TODO: handle the success case as normally
}
}
// build the initial response object with no error specified
$response = array(
'error' => null
);
// the data checks went fine, process as normal
if (data is ok) {
$response['some_object'] = value;
// something is bad with the token
} else if (bad token) {
$response['error'] = 'token error';
// something is bad with the title
} else if (bad title) {
$response['error'] = 'bad title';
// some other error occured
} else {
$response['error'] = 'unspecified error';
}
// output, specifying that it's JSON data being returned
header('Content-Type: application/json');
echo json_encode($response);
and....
// $.ajax({ ...
success: function(data){
if (!data.error){
alert('OK!');
}else{
alert('Error: '+data.error);
}
}
// });
Something like that perhaps? (Unless you're talking legitimate AJAX errors, in which case supply the error: function(x,t,e){} ajax option or use .ajaxError)
What I like to do is set the dataType for the $.ajax() to 'json' and then in the PHP page you can just echo a json_encode()ed associative array. This will let you reference the values via your function parameter data (i.e. data.success, data.message). Let me know if you need some examples.
You probably want to set the 'error' handler function, which would treat the error you received.
Take a look at http://api.jquery.com/jQuery.ajax/ in the error setting.