cannot get ajax responseText with Phalcon - php

I want to call an ajax and display its response :
<script type="text/javascript">
function test() {
var pk = $('#salle_code').val();
var donne = {pk:pk};
var ret = $.ajax({
data: donne,
type: "POST",
url: "<?php echo HTTP_AJAX ?>salle/testAjax.php",
async: false
}).responseText;
return $.trim(ret);
}
$(document).ready(function(){
$('#salle_code').on("blur", function() {
if ($('#salle_code').val() != "") {
alert(""+test());
}
});
});
</script>
Code of the ajax :
<?php
$critere = array();
$critere['salle_code'] = $_POST['pk'];
$ret = Salle::lireParCritere($critere);
echo "111111111111111";
?>
At runtime the alert show a blank result ! So how to work with Phalcon and ajax and models ?

use following code and check browser console for response
$.ajax({
data: donne,
type: "POST",
url: "<?php echo HTTP_AJAX ?>salle/testAjax.php",
async: false
success: function (data) {
console.log(data)
},
error: function (textStatus, errorThrown) {
console.log(textStatus + " : " + errorThrown)
}
});

First you need define a route for AJAX request, e.g. /salle/test:
$router->add('/salle/test', [
'controller' => 'salle',
'action' => 'test',
))->beforeMatch(function ($uri, $route) {
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') {
return false;
}
return true;
});
then create your action:
public function testAction()
{
// some work ..
$this->response->setJsonContent(json_encode(['foo' => 'bar']));
return $this->response;
}
then test:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
function test() {
var response = $.ajax({
type: "POST",
data: {},
url: '/salle/test',
success:function(results) {
console.log(results);
}
});
return response;
}
$(document).ready(function(){
console.log(test());
});
</script>

#Klay there was a very simple solution : I created an ajax action inside the controller of the actual view.

Related

jQuery Ajax get json returned result

I want to get the return result of a php function in an Ajax request in order to make some verification in onSucces. How can I get the JSON result from the php function into the ajax request?
public function verifyEmailAction()
{
$is_valid = true;
$is_duplicate = false;
$email_reset = false;
$register = $this->getRegisterHelper();
$register->addEmailCheck();
$register->setData($this->getAllParams());
$validationErr = $register->getValidationResult();
if (!empty($validationErr['badWords']['email']) || $validationErr['banned']['email'] == true
|| empty($validationErr['isEmailValid'])
) {
$is_valid = false;
} elseif (!empty($validationErr['duplicates']['email'])) {
$is_duplicate = true;
$email_reset = $this->sendResetEmail();
}
$result = [
'duplicate' => $is_duplicate,
'valid' => $is_valid,
'reset' => $email_reset
];
$this->getResponse()->setBody(json_encode($result));
}
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
}
});
});
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
dataType:'json',
success:function(response){
console.log(response);
var duplicate=response.duplicate;
var valid=response.valid;
var reset=response.reset;
},
error:function(err){
console.log('Error '+err);
}
});
You need to use the success and error functions like below,
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
success : function(data, status, xhr) {
console.log(JSON.stringify(data));
},
error: function(jqXhr, textStatus, errorMessage){
console.log("ERROR " + errorMessage);
}
});
});
$.ajax({
type: 'GET',
url: url,
data: {
'email': value
},
dataType:'json',
}).success(function(response){
//YOUR Json KEY
if(response.success){
}
});
I hope this article will help you.
http://api.jquery.com/jquery.ajax/
Specially you can use this
jQuery.ajax({
url: "YOURURL",
type: "YOURTYPE",
dataType:"json",
}).done(function(data) {
console.log(data) // to see the reqested data
// manipulate data here
});
Add dataType:'json':
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
dataType:'json'
});
});
You can use this to convert JSON string to a JavaScript object:
var txtReturned = JSON.parse(data);
Reference:
jQuery AJAX Call to PHP Script with JSON Return

Unable to get the response from ajax call in yii2

I have a GirdView which includes checkbox. Now I have a button which i routed to another action controller. Below is my code
<?= GridView::widget([
'dataProvider' => $dataProvider,
/*'filterModel' => $searchModel,*/
'id'=>'grid',
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'Meter Serial Number',
'Issued To',
'Store',
],
]); ?>
Set PDF
$(document).ready(function () {
$('#myid').click(function() {
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.post({
url: 'ogpheader/viewsetpdf',
dataType: 'json',
data:{keylist: keys},
success:function(data) {
alert('Done')
}
});
}) });
Then in my controller
public function actionViewsetpdf()
{
/*$model = $this->findModel($id);
print_r($model);*/
if(isset($_POST['keylist']))
{
$keys = json_decode($_POST['keylist']);
print_r($keys);
}
exit();
}
When I click on the button i get empty view. I followed this tutorialI don't know what is the problem. I am stuck to it.
Update1
While checking it in network
Update 2
As suggested I have tried with $.ajax and below is the result
Update 3
After changing the JS
$('#myid').click(function(e) {
e.preventDefault();
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.ajax({
url: '<?= URL::toRoute(["ogpheader/viewsetpdf"])?>',
dataType: 'json',
data:{keylist: keys},
type: 'post',
success:function(data) {
alert('Done')
}
});
The result is
Any help would be highly appreciated.
Change the controller and see what return, probably csrf token missing that why you got empty output
public function actionViewsetpdf()
{
if(isset($_POST['keylist']))
{
$keys = json_decode($_POST['keylist']);
print_r($keys);
}
else{
echo 'no data';
}
exit();
}
POST method required csrf token so you have to pass _csrf token as a parameter
$.ajax({
url: 'ogpheader/viewsetpdf',
type: 'post',
dataType: 'json',
data: {
keylist: keys,
_csrf: '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function(data) {
console.log(data);
}
});
Or you can disable csrf valdation by adding this to your controller
public function beforeAction()
{
if ($this->action->id == 'viewsetpdf') {
Yii::$app->controller->enableCsrfValidation = false;
}
return true;
}
Or simplest way just change POST to GET
$.post() has limited parameter to pass. Use $.ajax(). Also you need to add e.preventDefault() to stop redirection from a tag
$(document).ready(function () {
$('#myid').click(function(e) {
e.preventDefault();
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.ajax({
url: '<?php echo URL::toRoute(["ogpheader/viewsetpdf"]); ?>',
dataType: 'json',
data:{keylist: keys},
type: 'post',
success:function(data) {
alert('Done')
}
});
}) });
Use below js
<?php
$url = Url::toRoute(['ogpheader/viewsetpdf']);
$this->registerJs(<<< JS
$(document).ready(function () {
$('#myid').click(function() {
var keys = $('#grid').yiiGridView('getSelectedRows');
$.ajax({
url: '$url',
data: {keylist: keys},
type: "POST",
dataType: 'json',
success:function(data) {
alert('Done');
}
});
});
});
JS
); ?>

jquery not working with if statement

I am using an jquery script with an ajax update method that is bound to the focus event of a form element. It works, but I first want to check if the form element is not empty. As soon as I do that, the function stops working. Below is the code:
<script type="text/javascript">
if ($('#txt_updateone').val().trim().length > 0) {
function single_change(txt_updateone) {
$.ajax({
type: "POST",
data: { "txt_updateone": 1 },
url: "single_scorechange.php",
success: function (data) {
$('#listinscore').load(document.URL + '#listinscore');
},
error: function (xhr) {
alert("error");
}
});
return false;
}
}
</script>
txt_updateone is a textarea and the onfocus event calls the single_change function. When I remove the if..... on the second line, it works, but I want it to work only if the textarea is NOT empty.
There are two methods.
1) Validate the data at the place where you are calling this function.
2) Validate the data before sending ajax request using beforeSend.
<script type="text/javascript">
function single_change(txt_updateone) {
$.ajax({
type: "POST",
data: { "txt_updateone": 1 },
url: "single_scorechange.php",
success: function (data) {
$('#listinscore').load(document.URL + '#listinscore');
},
beforeSend: function(xhr) {
alert("Enter some value");
return $('#txt_updateone').val().trim().length > 0 ? true: false;
}
error: function (xhr) {
alert("error");
}
});
return false;
}
</script>
Change your code to
function single_change(txt_updateone) {
if ($('#txt_updateone').val().trim().length > 0) {
$.ajax({
type: "POST",
data: {
"txt_updateone": 1
},
url: "single_scorechange.php",
success: function(data) {
$('#listinscore').load(document.URL + ' #
listinscore ');
},
error: function(xhr) {
alert("error");
}
});
return false;
}
}
You need to perform the if check inside the method.
As you mentioned if condition before the function, the function is actually declared there. So you are calling the undefined function.
function single_change(txt_updateone) {
if ($('#txt_updateone').val().trim().length < 1) {
//form element is empty
return false;
}
$.ajax({
type: "POST",
data: { "txt_updateone": 1 },
url: "single_scorechange.php",
success: function (data) {
$('#listinscore').load(document.URL + '#listinscore');
},
error: function (xhr) {
alert("error");
}
});
return false;
}
Just swap function and if statement
//Declare function in all cases
function single_change(txt_updateone) {
//When you call function, check if statement.
if ($('#txt_updateone').val().trim().length > 0) {
$.ajax({
type: "POST",
data: { "txt_updateone": 1 },
url: "single_scorechange.php",
success: function (data) {
$('#listinscore').load(document.URL + '#listinscore');
},
error: function (xhr) {
alert("error");
}
});
return false;
}
}
What you are doing is defining your function only if the text area is non-empty (and it is likely that when this code runs, it may be empty). I think what you mean to do is to always have the function defined, but only execute the body if the text area has content.
If that's what you want, this may work:
<script type = "text/javascript">
function single_change ( txt_updateone ) {
var content = $('#txt_updateone').val().trim();
if (!content.length) { return; }
// now execute function with non-empty content.
}
</script>

How to pass the value using ajax to the controller in laravel

Here is my ajax
$(document).ready(function()
{
$( ".iCheck-helper" ).on( "click", function(){
var value_to_send = $('.i-check:checked').map(function() {
//alert(this.value);
return this.value;
}).get().join(', ');
});
});
Here,its my URL '/hotel/hotelresults/'.folder_name/function_name and the my Controller Name is HotelController
How should I get the ""return this.value"" using ajax to the controller.
Can Someone help me.
Try this:
$.ajax({
type: "POST",
url: "hotel/hotelresults",
data: {
key : value
},
success: function (data) {
alert(data)
}
});
Route:
Route::post('hotel/hotelresults', 'YourController#YourMethod');
In YourController:
public function YourMethod(Request $request)
{
//
return $request->key; //or return Input::get('key');
}
Please read more
docs
Thank you so much #rome 웃
I Tried like this..
$(document).ready(function()
{
$( ".iCheck-helper" ).on( "click", function(){
console.log($('.i-check:checked').map(function() {
// alert(this.value);
var value = this.value;
$.ajax({
// alert();
type: "POST",
url: "hotelresults",
data: {
key : value
},
success: function (data) {
// alert(data);
}
});
}).get().join(', '));
});
});
And in Route:
Route::get('hotel/hotelresults', 'HotelController#postHotelresults');
And in my Controller:
public function postHotelresults(Request $request)
{
//
return $request->key; //or return Input::get('key');
}
Because of giving the URL as "url: "hotel/hotelresults"," It seems to be an error in my console

PHP variable not echoing on page via ajax jquery

I am having a problem with my code as my php variable is not being echoed on page when using ajax jquery. Here is my code...
<script>
function refresh_div() {
$('.loader').show();
var username = "<?php echo $user; ?>";
jQuery.ajax({
type: "POST",
url: "load.php",
data:{user : username},
success:function() {
jQuery("#load_msgs").append(response+'<br>');
},
complete: function(){
$('.loader').hide();
}
});
}
t = setInterval(refresh_div,1000);
</script>
i am trying to send "username" to page url "load.php"... i called it this way but nothing is being echoed...
if(isset($_POST['user'])) {
echo $_POST['user'];
}
pls help out thanks... :)
edited...
when i tried using this code i.e adding passing response as parameter in success function like this ...
<script>
function refresh_div() {
$('.loader').show();
var username = "<?php echo $user; ?>";
jQuery.ajax({
type: "POST",
url: "load.php",
data:{user : username},
success:function() {
jQuery("#load_msgs").append(response+'<br>');
},
complete: function(){
$('.loader').hide();
}
});
}
t = setInterval(refresh_div,1000);
</script>
.... the data (username) gets displayed every second.. like a blink toggling on and off the page... how do i make the data display static in order to use the variable on the ajax page. Thanks :)
Where the response variable you get? Should be :
success : function( response ) {
jQuery("#load_msgs").append(response+'<br>');
},
please take a datatype as json in ajax call
and in loads.php function add two line as below..
if(isset($_POST['user'])) {
$data['user'] = $_POST['user'];
}
echo json_encode($data);
also change in success function.
success:function(response) {
jQuery("#load_msgs").append(response.user);
}
A bit more simplified would be:
$.post(URL, { data: somefield }, function(result) {
result = JSON.parse(result);
If(result && result.status === 'true'){
}
)};
Depends a bit on the return at server side.
You missed response in success function.
Try this:
<script>
function refresh_div() {
$('.loader').show();
var username = "<?php echo $user; ?>";
jQuery.ajax({
type: "POST",
url: "load.php",
data:{user : username},
success:function(response) {
$("#load_msgs").append(response+'<br>');
},
complete: function(){
$('.loader').hide();
}
});
}
t = setInterval(refresh_div,1000);
</script>

Categories