Using Ajax to call a Yii2 function on button click - php

After trying some possible solutions that I found through internet/other questions here, I can't seem to find the problem with my code. What I need is that, after clicking a button in my view, an action in my Yii2 controller gets called through Ajax and performs some action. However, with my current code, after clicking the button nothing seems to happen.
The relevant code is as follows...
The view:
(...)
Html::button('Eliminar', ['data-confirm' => '¿Eliminar enunciado?', 'onclick' => '
$.ajax({
type: "POST",
url: "/evaluacion/eliminar-enunciado",
data: {
id: '.$enunciado->id.'
}, success: function(result) {
if(result == 1) {
$.pjax.reload({container: "#construccion-evaluacion"});
} else {
}
}, error: function(result) {
console.log(\"server error\");
}
});
'])
(...)
The controller:
(...)
public function actionEliminarEnunciado($id)
{
Enunciado::findOne($id)->delete();
if(Enunciado::findOne($id) != null) {
echo 1;
} else {
echo 0;
}
}
(...)
Some considerations for clarification:
- The controller file is called EvaluacionController.php.
- The $enunciado->id variable is properly defined and has a valid value.
Any advice will be appreciated. Thanks for your time!

You need get value of POST request;
if(isset($_POST['id']))
$id = $_POST['id'];

Related

Ajax POST, check PHP $_GET and then $_POST

Using the following Ajax POST function on form submit (simplified here):
$form.on("submit", function (i) {
i.preventDefault();
var sendEmail = 1;
ValidateForm(sendEmail, "goSignup");
});
function ValidateForm(sendEmail, action) {
$.ajax({
type: "POST",
url: window.location.pathname,
dataType: "json",
data: {
ajaxRequest: 1,
sendEmail: sendEmail,
}
}
After I post this I want to use a conditional GET parameter that equals 1 (i.e https://www.example.com?test-parameter=1) and then if it's present in the URL use one or another function from there if the ajaxRequest is received from $_POST in my PHP:
public function __construct() {
$testingParameter = $_GET["test-parameter"] ?? '';
if (trim($testingParameter) == '1') { // if has get parameter equal
if (!empty($_POST['ajaxRequest'])) { // if JS postRequest has been posted
$this->handlePostRequests();
}
echo 'has get parameter';
} else { // else use old logic
if (!empty($_POST['ajaxRequest'])) {
$this->handleOtherRequests();
}
echo 'no get parameter';
}
}
Issue:
I get the correct echo from PHP but when I submit the form with Ajax its still using the handleOtherRequests(); instead of the handlePostRequests(); function if I'm using the url www.example.com?test-parameter=1.
Likely getting some basic PHP logic wrong here, would appreciate if anyone could guide me in the right direction with this.
url: window.location.pathname,
Your Ajax is never going to POST the data to a URL with a query string because you explicitly took only the path name.
Maybe you want location.href instead.

passing javascript variable to php in cakephp 2 view

I am trying to pass a javascript variable into a php code in the view file of the cakephp 2.
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x= book.thumbnail_url;
<?php
$file11 = WWW_ROOT . 'img' . DS . 'book_images';
define('DIRECTORY', $file11);
$content = file_get_contents($abc);
file_put_contents(DIRECTORY . '/'.$isbn.'.jpg', $content);
?>
}
}
i am trying to pass the value of x in the file_get_contents function in place of $abc so that it could save the image coming from the javascript's URL accordingly.
EDIT::
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x= book.thumbnail_url;
$.ajax({
type: "POST",
url: '/BookSearchs/test',
data: {'yourX':x}
}).done(function(result) {
alert("yes");
}).fail(function() {
alert("no");
});
}
}
This is what i wrote after implementing the answers i got . But Everytime it pops up "no". Here BookSearchs is my controller and test is my function inside it.
EDIT 2:
function handleResponse(response) {
var target = '';
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x = book.thumbnail_url;
$.ajax({
type: 'POST',
url: "BookSearchs/test",
data: {
myVal: x
},
success: function() {
alert('AjaX Success')
},
error: function() {
alert('AjaX Failed')
}
})
.done(function() {
alert('AjaX Done!');
});
}
}
return true;
}
Currently this is what i've have done so far , the form method did not work out . It was redirecting me to another page . Anyways this is my current code . And 'test' is the my function inside the controller where i want to access the myVal value using POST . Also i have this question do i need to create a physical file for test in order to make the ajax function work, because if i delete the test.ctp file then the ajax starts giving the fail message . So for now i have created a physical test.file in the BookSearchs folder in the view , although it's empty in order to make the ajax function work . I am having a doubt whether my Url in Ajax is wrong or i am not accessing the values properly in the controller.
I don't think that this is a proper way to do that in theory. But, sometime we might need this.
Before we proceed to this way, you might need to think other technologies such as NodeJs (e.g fs.readFileSync)
Basically, you can't directly do that. Because, JavaScript run on client side and PHP is run on sever side.
Anyway, there might be a few tweak to do that. But, this approach might be slow and it depends on how many loop you making.
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x= book.thumbnail_url;
$.ajax({
type: "POST",
url: '/yourcontroller/route',
data: {'yourX':x}
}).done(function(result) {
//if success, execute other code
}).fail(function() {
//DO other if fail
});
}
}
Then, read this value in your controller
$xValue = $_POST['yourX'];
$file11 = WWW_ROOT . 'img' . DS . 'book_images';
define('DIRECTORY', $file11);
$content = file_get_contents($xValue);
file_put_contents(DIRECTORY . '/'.$isbn.'.jpg', $content);
//do some checking success or fail
//I will assume success
$status = 'success';
echo json_encode(['status'=>$status]);
Usally I use a Trick to pass JS variable to a CakePhp Controller(php variable). Actionly I create a form that contain a hidden input, I'll also put the link of the page that will receive the php variable.
.ctp
<?=
$this->Html->link('<i class="fa fa-file-pdf-o"></i>' .__('Export'),
'javascript:myFunction();',
array('escape' => false, 'class' => 'btn btn-app dispatch', 'id' => 'dispatch_packages',
'style'=>'margin-right:0px;background: #f39c12;color:white;',
'disabled' => 'false'));
?>
<form id="sampleForm" name="sampleForm" style="display: none" method="post" action="<?= $this->Url->build([
'controller' => 'YourController',
'action' => 'youraction']) ?>">
<input type="hidden" name="variable" id="variable" value="">
</form>
JS
var jsVar=0;
function myFunction()
{
document.sampleForm.variable.value = jsVar;
document.forms["sampleForm"].submit();
}
I used it with the CakePhp 3.x framework & it's working very fine. You have just to write the url with the CakePhp 2.x Syntax.
Don't hesitate to comment my answer if you'll have any difficulties to apply it.
Good Luck !

Check db and then redirect using Ajax

So it's my first time handling or rather using ajax and it still rattles my mind. I made this ajax function so when everytime I push a button it checks the value of something on db and if it's true then it should redirect. It works fine or rather redirect when I refresh the webpage but that isn't what I was expecting, I was expecting that if the value on the db being checked is "EQUAL TO" or True then it should redirect without me having to refresh the page just so it can do it's stuff. Hoping for some insights, thanks!
My home.php has this:
<script src="js/ajax.js"></script>
My Ajax JS:
$.ajax
({
url: "testjax.php",
type: "post",
data: $('#Button').serialize(),
dataType:'json',
success: function (data)
{
if (data.status=='SUCCESS')
{
window.location="/anotherdirectory/";
}
else
{}
},
error: function (e) {
console.log('error:'+e);
}
});
Testjax PHP
<?php
session_start();
require_once('path/sql.php');
require_once('path/who.php');
$userID = Who::LoggedUserID(); //Found in who.php
$userData = Who::GetUserData($userID);
$userPoints = $userData['points'];
if ($userPoints==0.00)
{
$tent='SUCCESS';
}
else
{
$tent='ERROR';
}
$ary=array("status"=>$tent);
echo json_encode($ary);
?>

How to switch called php page using AJAX in wordpress

I have an several online application forms built into a (they differ per country) and I need to switch from one to the other with a users button click.
The code I have does this however it also produces a 500 error which breaks any other scripts.
Can anyone give me an idea of what I am doing wrong?
//Update appURL
if (jQuery('button[id="ukApp"]').hasClass( "checked" )) {
appURL = "wp-content/plugins/GoMarkets_application/uk/uk-application.php";
} else if (jQuery('button[id="itlApp"]').hasClass( "checked" )) {
appURL = "wp-content/plugins/GoMarkets_application/itl/it-application.php";
}
//Get URL path
function getContextPath() {
var ctx = window.location.pathname,
path = '/' !== ctx ? ctx.substring(0, ctx.indexOf('/', 1) + 1) : ctx;
return path + (/\/$/.test(path) ? '' : '/');
}
//Country Application URL
function getOutput() {
jQuery.ajax({
url: getContextPath() + appURL,
complete: function (response) {
jQuery('#output').html(response.responseText);
},
error: function () {
jQuery('#output').html('Bummer: there was an error!');
}
});
return false;
}
here is your ajax function
$.ajax({
url: ajax.url,
...
dataType: "json",
success: function(response) {
$('#myDiv').html(response.html);
},
})
and the php function
function my_ajax_load() {
$post_id = $_POST['post_id'];
ob_start();
include(locate_template('my-template-file.php',false,false));
$page_template = ob_get_contents();
ob_end_clean();
$response['html'] = $page_template;
wp_send_json($response);
}
in your template file you can use your variables declared in the function, in this example you can you $post_id inside the my-template-file.php
For example:
<?php /* Template name: My template */
if($post_id) {
echo get_the_title($post_id);
}
?>
500 error is caused by php error not ajax or jquery, check out your template file for a php errors
There was a missing image being called by the page I was trying to load, the error only showed up in the logs. Thanks all :)

Codeigniter Ajax request appeared twice in view and database

I have created a comment library to handle comments all over my website developed by CI
I am adding comments using ajax so i have came up with practice to have the function located in MY_Controller that handle the ajax
public function comment_add()
{
echo $this->comments->add();
}
and in AJAX Jquery code noting that category is one of controller names as any controller will havethe access to comment_add() found in parent controller
$('#myform').submit(function(e) {
e.preventDefault();
dataString=$("#myform").serialize();
$.ajax({
type:"POST",
url: base_url+"snc/category/comment_add",
data: dataString,
success: function(data){
$(data).hide().insertAfter('#inserAfterThis').slideDown('slow');
$('#comment_new').val('');
}
}
);
});
and in my Comments library
public function add()
{
$post_id=$this->get_post_id();
$post_type=$this->get_post_type();
if(!$post_id || !$post_type || !$this->user_id)
return false;
$id=$this->ci->comments_model->comment_add($this->user_id,$post_id,$post_type);
if($id)
{
return $this->_markup($id);
}
else
return false;
}
and comments model
function comment_add($user_id,$post_id,$post_type)
{
$data['comment_user_id']=$user_id;
$data['comment_post_type']=$post_type;
$data['comment_post_id']=$post_id;
$data['comment_text']=$this->input->post('comment_new');
$this->db->insert('comments', $data);
if($this->db->affected_rows()>0)
return $this->db->insert_id();
else
return false;
}
Problem is that Comment is inserted twice and as well in database twice, i have been tracin this for hours even with x-Debugg found that he go through echo $this->comments->add(); twice dunno why he would do that, thanks for your help
maybe it was submited twice. Try to unbind submit when you get ajax
success or just alet("something") so you will know if that problem is
javascript or php based.
Replace your submit function with:
$('#myform').submit(function(e) {
e.preventDefault();
dataString=$("#myform").serialize();
$(this).unbind("submit"); //so you will submit only once
$.ajax({
type:"POST",
url: base_url+"snc/category/comment_add",
data: dataString,
success: function(data){
$(data).hide().insertAfter('#inserAfterThis').slideDown('slow');
$('#comment_new').val('');
}
}
);
});
The missing piece here is "snc/category/comment_add" controller ... are you sure you aren't calling from both that controller & also the MY_Controller?
Can you post the controller code as well?
Found out that I have loaded Jquery file twice, that was my bad, thanks guys

Categories