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 !
Related
I have this simple AJAX code to get the User Timezone whenever he is successfully login to the dashboard.
JS
<script type="text/javascript">
$(document).ready(function(){
'use strict';
/**
* Getting user current timezone offset
*/
var timezone_offset = new Date().getTimezoneOffset();
timezone_offset = timezone_offset == 0 ? 0 : -timezone_offset;
$.ajax({
type: "POST",
url: "<?php echo base_url('dashboard'); ?>",
data: {"timezone": timezone_offset},
cache: false,
success: function(data){
alert(data);
},
error: function(){
console.log('error');
}
});
});
</script>
Controller
public function index()
{
$data = $this->global_data->logged_user();
$data['page_title'] = 'Dashboard';
$data['page_directory'] = 'pages/dashboard';
$data['greeting'] = $this->global_helpers->greeting() . ' !';
$chart_data = array();
$order_history = $this->trade_history->chart_data();
foreach($order_history AS $d)
{
$chart_data[] = array(
'y' => $this->global_helpers->month_name($d->month) ."' ". $d->year,
'a' => $d->profit,
'b' => $d->loss
);
}
echo $_POST['timezone'];
$data['chart_data'] = json_encode($chart_data);
$this->load->view('template', $data);
}
But the problem is, when it's success why it's return the HTML header? not the data I wish to get?
What do I do wrong here? And I put this AJAX code in footer.php file. Sorry for this silly question but I just got stuck here.
I appreciated any kind of helps, Thanks!
Edited
Sorry for this silly post, I can't use that way, i just need to create another controller for handling any kind of AJAX value, so the problem will be fixed.
Well, you can't render HTML inside an alert anyway.
I see that you ended up solving this issue, but, FYI, if you ever need a controller to return HTML as data, use the third parameter on view method:
echo $this->load->view('template', $data, TRUE);
See more at Codeigniter docs :)
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'];
I am currently migrating an already built web application to MVC, and I'm figuring out that I'm too newbie to do some kind of changes. There are some ajax calls that are freaking me out. I'll try to be as clear as possible, but due to my inexperience I'm not sure if I won't let some important information by the way.
The point is in the old application, things go this way:
In the php code:
if ($action_user == 'show_alerts') {
$list = array();
$query = "SELECT alert_type FROM alert_contact WHERE NOT
deleted AND user_email=" . typeFormat($email);
$result = mysqli_query($db, $query) or die('Error in query "'.$query . '": ' . mysqli_error($db));
while ($db_field = mysqli_fetch_assoc($result)) {
$list[] = $db_field['alert_type'];
}
echo json_encode($list);
In the jquery code:
$.ajax({
type: 'POST',
url: 'userpost.php',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Here comes my problem, and since I don't have an userpost.php file anymore, I have to send it to the index.php and call my users component by a get petition, which I don't like, but I coudn't find another way to do it. And, what is even worse, I don't know at all how ajax is getting the variables that it needs. It must be a pretty basic mistake, but I recognize my skills at this point are't so good. That's what I'm doing in my version:
In the php code:
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
In the jquery code:
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json',
success: function(data) {
alert ('gotcha');
$.each(alertsarray, function(index, value) {
if ($.inArray(value, data) === -1) {
$("#sub" + value).prop("checked", false);
$('#alert' + value).removeClass("list_alert_sub");
}
else {
$("#sub" + value).prop("checked", true);
$('#alert' + value).addClass("list_alert_sub");
}
});
},
error: function(data) {
alert("¡Error (ajax)!");
}
});
Any help would be appreciated, and if there's some more information I've missed, please let me know. Thanks in advance.
UPDATE:
I've been making some progress but don't seem to find a real solution. Now I know that the url has to be the controller, so I'm using 'components/userpost/controller.php' as it, and it reaches the ajax call, cause the success alert is showing up. The problem is the MVC way, because I send ajax to the controller, but since I don't have a reload in the page, all the includes are failing so they are obviously not being loaded, and I'm getting errors like this:
PHP Warning: include(components/userpost/model.php): failed to open
stream: No such file or directory in
/var/www/html/viewer_mvc/components/userpost/controller.php on line 3,
referer: http://localhost/viewer_mvc/index.php
Really hope you guys can show me where am I failing, and if there's a special way to do these thing in MVC.
For the JQuery call it makes a POST request to index.php?option=users with JSON data. The form with the ID userForm is serialized using the Jquery serialize method.
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Now for your PHP sample
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
This code will be looking for variables that probably don't exist anymore if it is a different file i.e. is there an $action_user variable?
To start reimplementing it you will need to add the logic so that it checks the POST variable if your not using the framework code. So if you have a form element with the name 'name' then that will be available in your PHP script POST variable
$_POST['name']
[How to call a PHP function in MVC using AJAX]
$.ajax({
type: 'POST',
url: 'save-user.php',
data: { fname: "manish", email: "manishkp#com", role:"admin"},
success: function(data) {
console.log(data);
if(data == 'error')
{
$('#Register_error').text('Must Be filled...');
$('#Register_error').show();
}
else {
$('#Register_error').hide();
$('#Register_success').text('Successfully submit');
$('#Register_success').show();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$fname = $_POST['fname'];
$email = $_POST['email'];
$role = $_POST['role'];
if(!empty($fname) && !empty($email) && !empty($role))
{
#MYSQL CONNECTION QUERY #
echo"success";
}
else{
echo "error";
}
?>
I'm implementing a photo tagging system.
in my php file I have:
if($_POST['type'] == "insert") {
$pid = $post->ID;
$tag_name = $_POST['tag_name'];
$tag_link = $_POST['tag_link'];
$pic_x = $_POST['pic_x'];
$pic_y = $_POST['pic_y'];
$arr = array("tag_name" => $tag_name, "tag_link" => $tag_link, "pic_x" => $pic_x, "pic_y" => $pic_y);
add_photo_tag($pid, $arr);
wp_redirect("http://www.test.com");
}
to catch the data. in my js file i have:
$('#tagit #btnsave').live('click',function(){
name = $('#tagname').val();
link = $('#taglink').val();
counter++;
$('#taglist ol').append('<li rel="'+counter+'">'+counter+'. '+name+' (<a class="remove">Entfernen</a>)</li>');
$('#imgtag').append('<div class="tagview" id="view_'+counter+'">'+counter+'</div>');
$('#view_' + counter).css({top:mouseY,left:mouseX});
$('#tagit').fadeOut();
$.ajax({
type: "POST",
url: "content.php",
data: "tag_name=" + name + "&tag_link=" + link + "&pic_x=" + mouseX + "&pic_y=" + mouseY + "&type=insert",
cache: true,
success: function(data) {
alert("success!");
}
});
});
Somehow the variables don't get passed to the php resulting in me not able to save the data properly to database.
The problem must be somewhere in either the $.ajax part or php. Can someone help me?
Well, you're checking post variable $_POST['type'] == "insert_tag" while it's actual value is: &type=insert. Others look fine. Btw never user .live(), it's obsolete, do it with .on()
Also, if all your elements are on a form you may use $('your_form_selector').serialize() - that'l be your post data
Your php code is looking for 'type' to be equal to 'insert_tag'.
Your JavaScript is POSTing with type=insert - so your php code ignores it.
Why are you redirecting in your PHP code? Remove this line:
wp_redirect("http://www.test.com");
You can replace it with some sort of a simple feedback system. After all you want the server-side to pass back the status and maybe some validation messages.
$return = array('status' => 0, 'msg' => 'all is well');
if(!add_photo_tag($pid, $arr)) {
$return['msg'] = __('Could not add photo tag.');
$return['status'] = -1;
}
echo json_encode($return);
Try with the following code:
$.ajax({
type: "POST",
url: "content.php",
data: {"tag_name": name,"tag_link":link,"pic_x": mouseX,"pic_y":mouseY, "type":"insert"},
//change here like I have done
cache: true,
success: function(data) {
alert("success!");
}
});
And Replace the if($_POST['type'] == "insert_tag") line with following:
if($_POST['type'] == "insert")
As the value you are passing of $_POST['type'] is insert not insert_tag.
EDITED:
one more thing as I have found that is you have not used the var before initializing the variable. use the var name = ...
Page elements are defined like this.
<div id="readf" class="tabbertab">
<h2>First Reading</h2>
<div id='titlefe' class='rtitle'>
</div>
<div id='readfe' class='rtext'>
</div>
</div>
I make an ajax call to a php script to add data to these page elements.
<script>
$('#readings').ready(function(){
$.ajax({
url: "loadenglish.php",
type: "GET",
data: { },
cache: false,
async: true,
success: function (response) {
if (response != '')
{
alert (response);
}
},
error: function (request, status, error) {
alert ("status "+status+" error "+error+"responseText "+request.responseText);
},
});
});
</script>
The php script gets the data and does a script echo to add the data.
<?php
$titlefe = 'text 1';
$readfe = 'text 2';
echo "<script type='text/javascript'> $('#titlefe').append('".$titlefe."'); $('#readfe').append('".$readfe."'); </script>";
?>
The alert statements shows that the php script gets the right information. But the page elements are not updated. Is there a different way to add $titlefe to element id titlefe?
In addition to what MK_Dev posted you can use PHP function json_encode();
<?php
//loadenglish.php
$params = array(
'titlefe' => 'text 1',
'readfe' => 'text 2',
);
echo json_encode($params);
Also there is a jQuery function $.getJSON(), which is a shortcut for $.ajax() function usage like yours.
Try eval(response); after your alert in the success callback.
Returning javascript methods is not a good idea. You should return data in JSON format and use javascript on the client side to perform the actual update.
Your PHP return statement should look like:
echo "{ 'titlefe': '" + $titlefe + "', 'readfe': '" + $readfe + "' }";
and your success call back should look like this:
success: function(response) {
$('#titlefe').text(response.titlefe);
$('#readfe').text(response.readfe);
}
If you insist on returning JavaScript, you should be using getScript() instead of an Ajax get.