Cakephp 2.0 Ajax post data not showing in the controller? - ajax

I'm working cakephp web application, I have created a small Ajax function in default ctp file. setup file now I want to send value data to another controller function, in the chrome browser network showing that Ajax posting to desire url but in controller post value didn't show up when I try to echo $_post ['selectedlocation']??
Ajax Default File
var DisplayLocationName = $('#ListingLocation option:selected').val();
$.ajax({
type: "POST",
url: '/listings/home',
data: {selectedlocation:DisplayLocationName },
dataType:"text",
success: function(result) {
}
});
Listing Controller Function
function home()
{
if(!isset($this->params['requested']) || $this->params['requested'] != true)
{
$this->actionId = 'home';
}
$this->viewFile = null;
if($this->params['isAjax'] && isset($_POST['selectedlocation']))
{
echo "erreerreer";
echo $selectloc= $_POST['selectedlocation'];
$this->set('selectloc',$selectloc);
}
}
how do I display Ajax post value in default for testing purposes that, make sure me that Ajax is posting proper values to the controller

You will need to use the logging files to read the post data. This will write the data to the error log and you can view it there.
function home()
{
if(!isset($this->params['requested']) || $this->params['requested'] != true)
{
$this->actionId = 'home';
}
$this->viewFile = null;
if($this->params['isAjax'] && isset($_POST['selectedlocation']))
{
echo "erreerreer";
CakeLog::write('error', $this->request->data('selectedlocation));
echo $selectloc= $_POST['selectedlocation'];
$this->set('selectloc',$selectloc);
}
}

When you want to $_POST a data from an ajax request, you should use:
$form_data = $this->request->data; (cakephp 2.x)
$form_data = $this->params['form'] (cakephp 1.3)
Now you got an array with your $_POSTed data, try to var_dump() it to understand its sctructure if you want.

Related

Django - Making an Ajax request

Im having a hard time figuring out how to integrate this ajax request into my view. I'm still learning how to integrate django with ajax requests.
My first question would be: Does the ajax request need to have its own dedicated URL?
In my case I am trying to call it on a button to preform a filter(Preforms a query dependent on what is selected in the template). I have implemented this using just django but it needs to make new request everytime the user preforms a filter which I know is not efficient.
I wrote the most basic function using JQuery to make sure the communication is there. Whenever the user changed the option in the select box it would print the value to the console. As you will see below in the view, I would to call the ajax request inside this view function, if this is possible or the correct way of doing it.
JQuery - Updated
$("#temp").change( function(event) {
var filtered = $(this).val();
console.log($(this).val());
$.ajax({
url : "http://127.0.0.1:8000/req/ajax/",
type : "GET",
data : {
'filtered': filtered
},
dataType: 'json',
success: function(data){
console.log(data)
},
error: function(xhr, errmsg, err){
console.log("error")
console.log(error_data)
}
});
Views.py
def pending_action(request):
requisition_status = ['All', 'Created', 'For Assistance', 'Assistance Complete', 'Assistance Rejected']
FA_status = RequisitionStatus.objects.get(status='For Assistance')
current_status = 'All'
status_list = []
all_status = RequisitionStatus.objects.all()
status_list = [status.status for status in all_status]
# This is where I am handling the filtering currently
if request.GET.get('Filter') in status_list:
user_req_lines_incomplete = RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status=request.GET.get('Filter')))
current_status = request.GET.get('Filter')
else:
user_req_lines_incomplete = RequisitionLine.objects.filter(parent_req__username=request.user).exclude(status__status='Completed')
user_reqs = Requisition.objects.filter(par_req_line__in=user_req_lines_incomplete).annotate(aggregated_price=Sum('par_req_line__total_price'),
header_status=Max('par_req_line__status__rating'))
return render(request, 'req/pending_action.html', { 'user_reqs':user_reqs,
'user_req_lines_incomplete':user_req_lines_incomplete,
'requisition_status':requisition_status,
'current_status':current_status,
'FA_status':FA_status})
def filter_status(request):
status = request.GET.get('Filter')
data = {
'filtered': RequisitionLine.objects.filter(Q(parent_req__username=request.user) & Q(status__status=status)),
'current_status': status
}
return JsonResponse(data)
Urls.py
path('pending/', views.pending_action, name='pending_action')
First: you have to divide your template to unchangeable part and the part that you want to modify with your filter.
Second: for your goal you can use render_to_string. See the followning link https://docs.djangoproject.com/en/2.1/topics/templates/#usage
code example (views.py):
cont = {
'request': request, #important key-value
'your_models_instances': your_models_instances
}
html = render_to_string('your_filter_template.html', cont)
return_dict = {'html': html}
return JsonResponse(return_dict)
In your js file you need to determine relative url "{% url 'name in yours url file'%}"
And in success you need to add next line:
success: function(data){
$(".filter-block").html(data.html);
}
i hope it will help you! Good luck!

Ajax post is working in localhost but not in godaddy server

This ajax post is working in localhost but not in godaddy server. I dont know how to solve this kind of issues. Please let me know how rectify this issue.
Ajax is not working in many places. Locally all of files are working very fine.
I am new to php. Anyone can help me to fix this bug?
Thanks in Advance
function advanced_addTopic(cid) {
$.ajax({
url: "assets/php/checkSubtopicStatus.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {'cid':cid}, // Data sent to server, a set of key/value pairs (i.e. form fields
success: function(data) // A function to be called if request succeeds
{
if(data==="True"){
$("#subtopicDiv").html($("#subtopicDiv"+cid).html());
$("#advanced_testid").val(cid);
var hiddenCourse=$("#createTest").attr('class');
$("#courseHidden").val(hiddenCourse);
$("#advanced_addquestionModal").modal('show');
$("#subtopic").focus();
$("#question").focus();
var tempVal=$("#getID").text();
$("#advanced_courseHidden").val(cid);
} else {
alert("Create subtopics to insert questions!");
}
}
});
My PHP CODE IS:
<?php
class loginValidation {
function validate()
{
ob_start();
session_start();
include "../../connection.php";
$id=$_POST['cid'];
$query = mysql_query("select * from advanced_subtopic where testid='$id'");
if(mysql_num_rows($query)>0){
echo "True";
} else {
echo "False";
}
}}$loginValidation=new loginValidation;
$loginValidation->validate();
?>
Using Ajax URLs like
url: "http://domainname.com/assets/php/checkSubtopicStatus.php";
If you use your domain name HTTPS enter the same as an Ajax URL.

Additional parameters for grid

I am using the jquery-bootgrid to render a couple of grinds. It works brilliant.
I want to send some additional parameters for the grid to my MVC controller.
How can i pass those parameters ?
I have tried :
$("#results-grid").bootgrid({
ajaxSettings: {
url: testResultsListUrl,
data: { testSubject: '2', another : '3' }
}
});
But it does not seem to work. If i put all the properties for the ajax object inside the ajaxSettings, the un set ulr error is thrown.
Can you please help ?
I managed to do it, i saw a discussion on git for this project. What I had to do to be able to send additional params to my controller was :
$("#results-grid").bootgrid({
ajax: true,
url: testResultsListUrl,
requestHandler: function (request) {
if (testSubject != "") {
request.testSubject = testSubject;
}
if (medicalDevice != "") {
request.medicalDevice = medicalDevice;
}
return request;
}
The requestHandler is the object that is sent with all the parameters, for the grid. You can add all your parameters inside of it.

Filter to detect if Response::json was sent

I have a filter. I want this filter to act only if the page is displaying HTML and NOT if it's json or any other format
App::after(function($request, $response)
{
if( $request->getMethod() == 'GET' && $request->getRequestFormat() == 'html' ) {
// do something!
}
});
In my Controller functions I return json data:
return Response::json($data);
However, $request->getRequestFormat() is still equal to 'html' and it shouldn't be.
I know that I can set the format to be 'json' like this:
Request::setRequestFormat('json');
return Response::json($data);
But it seems redundant. If I'm returning a Response::json it should know that it's json and not HTML. How can I detect that it's a Response::json?
The requestFormat is something that isn't set automatically - you either provide it programattically via setRequestFormat or by including a POST/GET parameter _format.
If you want to check if a request is JSON you can do $request->isJson(), but it looks more to me like you're trying to check if the response is JSON? In which case you can do $response instanceof Illuminate\Http\JsonResponse or $response->headers->get('Content-Type') == 'application/json'
This is not a json at all, it's HTML which contains some string inside a div. Remove the div and just pass the json using:
return Response::json($data);
Then in the client side, using jQuery parse the json data and create a div and append the data inside div, for example, in your success callback try something like this:
success(response) {
// Parse the json if not parsed by jQuery
var obj = $.parseJSON(response);
if(obj.success) {
$('<div/>', {id:"query-log"}).append(obj.data).appendTo('body');
}
}
This may not accurate with your json data but hope you got the idea, in short, just pass the json data to the client side and manipulate it in the browser using jQuery.
Update: The better approach would be to provide the dataType when making the request using something like tgis:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function( data ) {
}
});
Also you may use this:
$.getJSON( "url", function( data ) {
// ...
});
So a request header will be sent to the server and you may check if the request is expecting a json response using this:
if($request->wantsJson()) {
//
}
This is the method in the request class:
/**
* Determine if the current request is asking for JSON in return.
*
* #return bool
*/
public function wantsJson()
{
$acceptable = $this->getAcceptableContentTypes();
return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}
App::after(function($request, $response)
{
if( $request->getMethod() == 'GET' && $request->getRequestFormat() == 'html' ) {
// Test if response is JSON (PHP 5.3+ needed for this)
json_decode($response);
if ( json_last_error() != JSON_ERROR_NONE ) {
// Do something
}
}
});

not getting response from ajax call in codeigniter

I am trying to check if the user name is available for use using ajax and codeigniter. I have problem to get the response from the codeingniter controller in my js. file but without success.
Here is the controller function, relevant to the question:
if ($username == 0) {
$this->output->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}
Rest assured that I do get 1 if username already exists in thedatabase and 0 if it does not exist.
I have the following js.file
// list all variables used here...
var
regform = $('#reg-form'),
memberusername = $('#memberusername'),
memberpassword = $('#memberpassword'),
memberemail = $('#memberemail'),
memberconfirmpassword = $('#memberconfirmpassword');
regform.submit(function(e) {
e.preventDefault();
console.log("I am on the beggining here"); // this is displayed in console
var memberusername = $(this).find("#memberusername").val();
var memberemail = $(this).find("#memberemail").val();
var memberpassword = $(this).find("#memberpassword").val();
var url = $(this).attr("action");
$.ajax({
type: "POST",
url: $(this).attr("action"),
dataType: "json",
data: {memberusername: memberusername, memberemail: memberemail, memberpassword: memberpassword},
cache: false,
success: function(output) {
console.log('I am inside...'); // this is never displayed in console...
console.log(r); // is never shonw in console
console.log(output); is also never displayed in console
$.each(output, function(index, value) {
//process your data by index, in example
});
}
});
return false;
})
Can anyone help me to get the username value of r in the ajax, so I can take appropriate action?
Cheers
Basically, you're saying that the success handler is never called - meaning that the request had an error in some way. You should add an error handler and maybe even a complete handler. This will at least show you what's going on with the request. (someone else mentioned about using Chrome Dev Tools -- YES, do that!)
As far as the parse error. Your request is expecting json data, but your data must not be returned as json (it's formatted as json, but without a content type header, the browser just treats it as text). Try changing your php code to this:
if ($username == 0) {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}

Resources