Class Yii is not found when posting a variable with ajax - javascript

I want to get a variable from ajax to php. I'm using the Yii framework.
So my problem is, when I want to transfer a variable from ajax to a php script I get this error:
Fatal error: Class 'Yii' not found in
/var/www/vhosts/adappter.de/comamos/protected/views/store/search_area.php
on line 44 store.js:1308:13
This is how my Ajax Call looks like
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "../protected/views/store/search_area.php",
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});
and this is my php script to line 44
<?php
if (!isset($_SESSION)) { session_start(); }
$_SESSION['search_type']='';
if (isset($_GET['s'])){
$_SESSION['kr_search_address']=$_GET['s'];
$_SESSION['search_type']='kr_search_address';
}
unset($_SESSION['kr_item']);
unset($_SESSION['kr_merchant_id']);
$marker=Yii::app()->functions->getOptionAdmin('map_marker');
if (!empty($marker)){
echo CHtml::hiddenField('map_marker',$marker);
}
?>
The jQuery call is only when I click on a checkbox. So the value of the selected box gets pushed in an array. I want to return the array to the php script.
When I'm loading the site, I don't get such an error. So I don't know why this error occurs.

You need to use controller with action. Not only view file. You try to call view file from web. But it is wrong, because all code in protected directory. All requests must processing from index file. In index file connected framework. Here a small example. Controller:
class SiteController extends Controller
public function actionTest()
{
//... example
echo CHtml::button('test');
}
js:
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "/site/test", // url for your action
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});

Related

Why can't I toss post variable to PHP when I cover .ajax with function?

I have 3 files for showing data from myAdmin and it shows no error but after I put function around .ajax, to re-use it, I cannot pass button id to PHP. " Undefined index: btnId"
What seems wrong?
HTML file, written in PHP (below looped in for code)
print"<button class='refresh' data-name='$btnId' id='$btnId'>{$btnId}</button>";
print "<table id='$idForShowNewData' class='showNewData'></table>";
show.js
$(document).ready(function(){
$('.refresh').click(function(){
$(function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $(this).data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
showTable();
});
});
PHP file that get's data from myAdmin. Getting id like below is at the top of the script.
$gotBtnId = $_POST['btnId'];
this in showTable refers to window object and not the button whose data-name you want to send in the request.
If you want showTable to be invoked when the page is loaded and also be registered as a listener for click events to the refresh button, declare it as follows:
const $refreshBtn = $('button.refresh');
function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $refreshBtn.data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
$(function() {
showTable();
$refreshBtn.click(showTable);
});

How to show response from AJAX call to Spring controller method?

How do I display the response of a call to a Spring MVC Controller returning HTML? In my Javascript code I make a (GET) call to my Spring Controller. From what I can make is that the response from the call is HTML. I guess I need to replace 'alert(response)' with Javascript to display the html.
My Javascript code:
$('#parcelsTable').on( 'click', 'tr', function () {
var data = table.row( this ).data();
$.ajax({
url:"/parcel/showFormForUpdate",
type:"GET",
data:{parcelId:data.parcelId},
success: function(response){
alert(response)
}
});
} );
My controller code in Spring:
#GetMapping("/showFormForUpdate")
public String showFormForUpdate(#RequestParam("parcelId") int theId, Model theModel) {
Parcel theParcel = parcelService.findById(theId);
theModel.addAttribute("theParcel", theParcel);
return "parcel-form";
}
Here "parcel-form" is the name of a template.
$('#parcelsTable').on( 'click', 'tr', function () {
var data = table.row( this ).data();
$.ajax({
url:"/parcel/showFormForUpdate",
type:"GET",
data:{parcelId:data.parcelId},
success: function(response){
$.get(response.html, function(data, status){
$("#ID").html(data);
});
}
});
} );
response.html is the page you want to show on the success of get request. Just make a get request to the response.html file or any template file and put this file in any div where you want to show it.
Hope that it works

Jquery ajax call in Cake PHP 3.0

Hi,
I'm trying to make a ajax request to the view A from the controller B like this :
In the view A :
var tab = new Array();
function updateResult(){
$.ajax({
type:"POST",
url:"<?php echo Router::url(array('controller'=>'B','action'=>'viewresult'));?>",
dataType: 'text',
async:false,
success: function(tab){
alert('success');
},
error: function (tab) {
alert('error');
}
});
}
In the controller B:
public function viewresult()
{
echo 'SUCCESS';
}
The problem is that in the 'response' of ajax, I've 'SUCCESS' but also the entire view A, I don't understand why...
I want only 'SUCCESS'...
Thanks in advance !
Detect if its ajax as per following code in cakephp way :
if($this->request->is('Ajax')) //Ajax Detection
{
$this->autoRender = false; // Set Render False
$this->response->body('Success');
return $this->response;
}
Check here for more detectors - http://book.cakephp.org/3.0/en/controllers/request-response.html#Cake\Network\Request::addDetector
You can also use $this->Url->build instead of including Router for creating links in view.
echo $this->Url->build(['action'=>'index']);
The easiest way to achieve it is adding die() at the end of your function so it prevents to load whole layout:
public function viewresult()
{
echo 'SUCCESS';
die;
}
OR
public function viewresult()
{
die('SUCCESS');
}
But more conventional way is using JSONView. Your action should look as follows:
public function viewresult()
{
$this->set('text', 'SUCCESS');
$this->set('_serialize', ['text']);
}
You also have to load RequestHandler component in initialize() method in your controller:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
You need to set allowed extensions for all routes connected later in routes.php:
Router::extensions('json', 'xml');
Now you can access your action adding extension .json at the end of it's URL, so you need to modify ajax call url:
url:"<?php echo Router::url(array('controller'=>'Main','action'=>'viewresult', '_ext' => 'json'));?>"
That's all, but keep in mind that this solution force you to handle JSON array in response. In this example output will be looks as follows:
{"text": "SUCCESS"}

How to export a model function from a controller to a view in Laravel 4

I am trying to display some data from my database that is dependent on some input from the user. I am using an ajax request to get the data, send it back to a function in my controller, and then export it back to my view. I would like to collect this data and display it without going to another view (I just hide the previous form and unhide the new form).
Here is the relevant code:
Javascript:
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
Controller functions:
public function pick_favorite() {
$fbid=Input::get('fbid');
return Artist::specific_artist($fbid);
}
public function getWelcome() {
return View::make('fans.welcome')
->with('artists', Artist::artists_all())
->with('favorite_artist', Artist::favorite_artist())
->with('pick', FansController::pick_favorite());
}
Model function:
public static function specific_artist($fbid) {
$specific_artist = DB::table('artists')
->where('artists.fbid', '=', $fbid)
->get();
return $specific_artist;
}
The view is on the "welcome" page. My question is how do I display the model data in my view and make sure it is printing out the correct data from the fbid input?
I tried something like this:
#foreach($pick as $p)
<span class="artist_text">{{$p->stage_name}}</span>
<br>
<span class="artist_city">{{$p->city}}</span>
#endforeach
but this is not printing out anything. Any ideas?
i see lots of issues here.
Server side:
public function pick_favorite().... what does it do? it just returns some data.
in public function getWelcome() { , you wrote, FansController::pick_favorite(). supposing both are the same method, you are accessing a static method whilst the method is non static. you are getting an error for this but you are not seeing it because you didn't define fail().
and i don't see what the point of declaring a method which does nothing else then a model call which you can do directly.
e.g let's say i have a fooModel
public function index(){}
in controller, i can just write,
public function bar()
{
$model = new fooModel;
return View::make(array('param1'=>$model->index()));
}
or if i declare index() method in fooModel as static, then i can write,
public function bar()
{
return View::make(array('param1'=>fooModel::index()));
}
Client side:
now in your javascript,
$('#submit_one').on('click', function(event) {
event.preventDefault();
if(! $(this).hasClass('faded')) {
var fbid = $("input[name='like']:checked").val();
//variable to be collected is fbid
request = $.ajax({
url: "http://crowdtest.dev:8888/fans/pick_favorite",
type: "post", success:function(data){},
data: {'fbid': fbid} ,beforeSend: function(data){
console.log(data);
}
});
to_welcome_two();
}
});
function to_welcome_two()
{
$('#welcome_one').addClass('hidden');
$('#welcome_two').removeClass('hidden');
}
why it should print any data? you didn't asked the script to print anything. where is your .done or .success param in your code?
If you look at your console, you'l get lots of php errors, i am almost sure of.
an advice, you need to lear some basics. e.g. jquery ajax call.
a basic ajax call can be
var request = $.ajax({
url: "script.php",
type: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
implement it in your code and then see what errors it throws.
Conclusion:
1st one will be (supposing rest of your codes are ok) the static error. if you want to call it as static, declare it as static. but a static function in controller? i don't see any purpose of it.
and then start the debug. your problem is both client and server side. deal one by one.

jquery .ajax always returns error - data being added to database

I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});

Categories