Using the return json code - ajax

I'me trying to use ajax with php, I have the follogin script in php :
<?php
// this file get the POST infor sent by a AJAX request and will return the value is succesful.
$price['name'] = "Called";
$price['Wheel'] = 75.25;
$price['Tire'] = 50.00;
echo json_encode($price);
?>
and I'm calling this code from my main page in the following way :
$.post("ajax/profileMod.php", {
'lname':lname,
'fname':fname,
'mname':mname,
'language':language,
'title':title,
'ptype':ptype,
'vip':vip,
'vreason':vreason
})
// Retreive the data from the php script
.done(function(data) {
// php code : echo json_encode(array("name"=>"Called!"));
alert(data);
}, "json");
// Stop original behavior
return false;
});
The returniong result from the alert is the following test :
{"name":"Called",Wheel":75.25,"Tire":50}
How can I change this result so I may use it in the following way in javascript EX:
alert(myresult['Name']) ; Would give me "Called".
So I basicly would like a associative array in javascript, but I read somewhere on this forum that you can't have associative array in Javascript, only object...
Please help!

Pass "json" as the last parameter to .post() to tell jQuery to parse the response as JSON.
(or, fix your server to return the correct Content-Type of application/json, and jQuery should do that automatically)
You will then get a Javascript object, allowing you to write
alert(result.name);

Related

Laravel & Ajax return array response no parsing

Currently I'm trying to pull some data via ajax and I'm not getting the data to appear properly.
In my ajax call I have this:
$.ajax({
url:"{{ route('pricing.fetch') }}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent, productId:productId},
success:function(result)
{
$("ul[data-dependent='quantity']").html(result);
This works as expected. The problem is I'm trying to return data from different tables in my db. So I'm trying to do it by changing my result in ajax to this.
$("ul[data-dependent='quantity']").html(result.productQuantities);
The reason for me wanting to do this is because I have multiple drop downs I need. So I would also like to do another one like this:
$("ul[data-dependent='quantity']").html(result.productPaperStock);
my controller code is like this:
$data = Product::with(['productQuantity', 'productPaperstock'])->where('ID', $productId)->first();
// pull the quantity for this product
$productQuanties = $data->productQuantity;
$productPaperStock = 'hello';
$output = '';
foreach($productQuanties as $productQuantity)
{
$output .= "<li><span>" . $productQuantity->quantity_name . "</span></li>";
}
return response()->json["productQuanties" => $productQuanties, "productPaperStock" => $productPaperStock]);
I'm not sure what I'm doing wrong but using this example above I get a 500 error.
You need to set dataType: json option in your ajax request, and then in your controller, you can return json response.
Also, you are missing the starting brace in your controller code. The correct code is
return response()->json(["productQuanties" => $productQuanties, "productPaperStock" => $productPaperStock])
(Note that ...storage/logs/laravel.log is an awesome place to get insights into what's screwing your app:))

POST variables not getting through AngularJS

module2.factory('Ajax', function($http) {
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
return {
get : function(url, params){
return $http.post(url, {
params : params
});
}
}
});
Made a factory to do some easy AJAX calls, but for security reasons I had to change the method to POST instead of GET ($http.post instead of $http.get), and now I dont get my data in my php files. Using $_GET[] did work when using $http.get, but now using $_POST[] when using $http.post I get an empty array. The $http.defaults.headers.post[] line was a solution in other stackoverflow topics, but it doesnt work for me.
What could be the problem?

simple json response with cakephp

I trying to pass some json to a controller in cakePHP 2.5 and returning it again just to make sure it is all going through fine.
However I getting no response content back. Just a 200 success. From reading the docs I am under the impression that if I pass some json then the responseHandler will the return json as the response.
Not sure what I am missing.
Data being passed
var neworderSer = $(this).sortable("serialize");
which gives
item[]=4&item[]=3&item[]=6&item[]=5&item[]=7
appController.php
public $components = array(
'DebugKit.Toolbar',
'Search.Prg',
'Session',
'Auth',
'Session',
'RequestHandler'
);
index.ctp
$.ajax({
url: "/btstadmin/pages/reorder",
type: "post",
dataType:"json",
data: neworderSer,
success: function(feedback) {
notify('Reordered pages');
},
error: function(e) {
notify('Reordered pages failed', {
status: 'error'
});
}
});
PagesController.php
public function reorder() {
$this->request->onlyAllow('ajax');
$data = $this->request->data;
$this->autoRender = false;
$this->set('_serialize', 'data');
}
UPDATE:
I have now added the following to the routes.php
Router::parseExtensions('json', 'xml');
and I have updated my controller to
$data = $this->request->data;
$this->set("status", "OK");
$this->set("message", "You are good");
$this->set("content", $data);
$this->set("_serialize", array("status", "message", "content"));
All now works perfectly.
A proper Accept header or an extension should to be supplied
In order for the request handler to be able to pick the correct view, you need to either send the appropriate Accept header (application/json), or supply an extension, in your case .json. And in order for extensions to be recognized at all, extension parsing needs to be enabled.
See http://book.cakephp.org/...views.html#enabling-data-views-in-your-application
The view only serializes view vars
The JSON view only auto-serializes view variables, and from the code you are showing it doesn't look like you'd ever set a view variable named data.
See http://book.cakephp.org/...views.html#using-data-views-with-the-serialize-key
The view needs to be rendered
You shouldn't disable auto rendering unless you have a good reason, and in your case also finally invoke Controller:render() manually. Currently your action will not even try to render anything at all.
CakeRequest::onlyAllow() is for HTTP methods
CakeRequest::onlyAllow() (which btw is deprecated as of CakePHP 2.5) is for specifying the allowed HTTP methods, ie GET, POST, PUT, etc. While using any of the available detectors like for example ajax will work, you probably shouldn't rely on it.
Long story short
Your reorder() method should look more like this:
public function reorder() {
if(!$this->request->is('ajax')) {
throw new BadRequestException();
}
$this->set('data', $this->request->data);
$this->set('_serialize', 'data');
}
And finally, in case you don't want/can't use the Accept header, you need to append the .json extension to the URL of the AJAX request:
url: "/btstadmin/pages/reorder.json"
and consequently enable extension parsing in your routes.php like:
Router::parseExtensions('json');
ps
See Cakephp REST API remove the necessity of .format for ways to use the JSON view without using extensions.
Output your json data
public function reorder() {
$this->request->onlyAllow('ajax');
$data = $this->request->data;
$this->autoRender = false;
$this->set('_serialize', 'data');
echo json_encode($data);
}

Debugging Ajax requests in a Symfony environment

Not sure if SFDebug is any help in this situation. I am making an ajax post using jQuery. Which retrieves JSON data in my action URL and then makes a call to the Model method that executes the action. The part until my action URL, and the jQuery call to it work fine. With the data transmitted from the client to the server well received and no errors being made.
It is the part where it calls the method on the Model that is failing. My jQuery method looks like this:
$.post(url, jsonData, function(servermsg) { console.log(servermsg); }) ;
My server action is like this
public function executeMyAjaxRequest(sfWebRequest $request)
{
if($request->isXmlHttpRequest())
{
// process whatever
$servermsg = Doctrine_Core::getTable('table')->addDataToTable($dataArray);
return $this->renderText($servermsg);
}
return false;
}
The method of concern in the Table.class.php file looks like this:
public function addDataToTable($dataArray)
{
// process $dataArray and retrieve the necessary data
$data = new Data();
$data->field = $dataArray['field'];
.
.
.
$data->save();
return $data->id ;
}
The method fails up here in the model, when renderText in the action is returned and logged into the console, it returns the HTMl for SFDEBUG. Which indicates that it failed.
If this was not an Ajax call, I could debug it by seeing what the model method spat out, but this is a little tedious with Ajax in the mix.
Not looking for exact answers here, but more on how I can approach debugging ajax requests in a symfony environment, so if there are suggestions on how I can debug this, that would be great.
You must send cookie with session ide key via ajax
(Assuming you have XDEBUG configured on the server)
In order to trigger a debug session by an AJAX request you have to somehow make that request to send additional URL parameter XDEBUG_SESSION_START=1. For your example:
$.post(url + '?XDEBUG_SESSION_START=1', jsonData, function(servermsg) { console.log(servermsg); }) ;
You can also trigger it via cookie, but appending URL parameter usually easier.

How to make an Ajax request in Joomla Component

This a screen shot of what I get when I call my ajax request:
How do I run only the task, without printing the whole page? This is my ajax call:
$.ajax
({
type: "POST",
url: "index.php?option=com_similar&task=abc",
data: {
id: id,
name: name,
similar_id: similar_id,
},
cache: false,
success: function(html)
{
$("#flash").fadeOut("slow");
$("#content"+similar_id).html(html);
}
});
});
$(".close").click(function()
{
$("#votebox").slideUp("slow");
});
});
Don't go with exit or die, Joomla! has it's nice way of dealing with this stuff.
The answers below are tested in Joomla! 2.5 & 3 (for 1.5. may work as well).
General
Your URL for the task needs to look like this:
index.php?option=com_similar&task=abc&format=raw
You than create the controller which will use the view, let's say Abc, which will contain the file view.raw.html (identical to a normal view file).
Below you have the code for generate a raw HTML response:
/controller.php
public function abc()
{
// Set view
JRequest::setVar('view', 'Abc');
parent::display();
}
/views/abc/view.raw.php
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
class SimilarViewAbc extends JView
{
function display($tpl = null)
{
parent::display($tpl);
}
}
/views/abc/tmpl/default.php
<?php
echo "Hello World from /views/abc/tmpl/default.php";
Note: This is the solution I would use if I had to return HTML (it's cleaner and follows Joomla logic). For returning simple JSON data, see below how to put everything in the controller.
If you make your Ajax request to a subcontroller, like:
index.php?option=com_similar&controller=abc&format=raw
Than your subcontroller name (for the raw view) needs to be abc.raw.php.
This means also that you will / may have 2 subcontrollers named Abc.
If you return JSON, it may make sense to use format=json and abc.json.php. In Joomla 2.5. I had some issues getting this option to work (somehow the output was corrupted), so I used raw.
If you need to generate a valid JSON response, check out the docs page Generating JSON output
// We assume that the whatver you do was a success.
$response = array("success" => true);
// You can also return something like:
$response = array("success" => false, "error"=> "Could not find ...");
// Get the document object.
$document = JFactory::getDocument();
// Set the MIME type for JSON output.
$document->setMimeEncoding('application/json');
// Change the suggested filename.
JResponse::setHeader('Content-Disposition','attachment;filename="result.json"');
echo json_encode($response);
You would generally put this code in the controller (you will call a model which will return the data you encode - a very common scenario). If you need to take it further, you can also create a JSON view (view.json.php), similar with the raw example.
Security
Now that the Ajax request is working, don't close the page yet. Read below.
Don't forget to check for request forgeries. JSession::checkToken() come in handy here. Read the documentation on How to add CSRF anti-spoofing to forms
Multilingual sites
It may happen that if you don't send the language name in the request, Joomla won't translate the language strings you want.
Consider appending somehow the lang param to your request (like &lang=de).
New in Joomla 3.2! - Joomla! Ajax Interface
Joomla now provides a lightweight way to handle Ajax request in a plugin or module. You may want to use the Joomla! Ajax Interface if you don't have already a component or if you need to make requests from a module your already have.
If you just want to include the response output in some HTML element, append format=raw to your URL as mentioned above. Then you could have a controller function like this:
function abc(){
//... handle the request, read variables, whatever
print "this is what I want to place in my html";
}
The AJAX response will output everything you printed / echoed in the controller.

Resources