I need an assistance on how to transfer this value $row[COMPONENT] in my class1.php into another page process_class.php with jQuery using post method.
i did this but it seems doesnt work ,
$('.cuttingCheckbox').change(function() {
if (this.checked) {
$.post('process_class.php',
{ comp : $($row[COMPONENT]).val(), comp_id : $($row[ID]).val() },
function(response) {
this.setAttribute("disabled", true), alert(comp,comp_id); });
}
});
Does anyone willing to help me ?
you can save that $row[COMPONENT] into session like this:
$_SESSION['row_component'] = $row[COMPONENT];
and in your next page, you just retrieve it:
$row = $_SESSION['row_component'];
As Jonast said (thanks dude), you should initiate the session first at the top of your php file: session_start();
Related
I am developing a plugin in which I get data from API, and then the user has an option to add this data to the cart and purchase the product. Everything works perfectly, except once we reload the page, the user cart value gets lost. How can I solve this?
I think one solution is, If we add the cart object to the session, it will be easy to use that session value to get the cart object. For this, I added the below function
my_file.js
function savecartObj(cartObj) {
$.post(
'cartObj.php',
{
cartobj : cartObj
},
function success(data) {
console.log(data);
}
);
}
and in my cartObj.php
<?php
/** Set up WordPress environment, just in case */
$path = preg_replace('/wp-content(?!.*wp-content).*/','',__DIR__);
require_once($path.'wp-load.php');
session_id() || session_start();
nocache_headers();
$_SESSION['ajjx'] = $_POST;
$value = '';
if (array_key_exists('ajjx', $_SESSION)) {
if (array_key_exists('cartobj', $_SESSION['ajjx']) {
$value = $_SESSION['ajjx']['cartobj'];
}
}
Header('Content-Type: application/json;charset=utf8');
die(json_encode(array(
'result' => $_SESSION['ajjx']['cart_obj'],
)));
Now I can see that $_SESSION['ajjx']['cart_obj'] is set and in console.log(data); I can see the session value. How can i use this value from $_SESSION['ajjx']['cartobj'] as cartobj in my_file.js
What I need is will create one file named get_session.php and in
that file, I will call the value of $_SESSION['ajjx']['cart_obj'] .
And then once my plugin is loaded I will call the value in
get_session.php & need to take the obj from the file and then add that value to add to cart function in the my_file.js. In that way, page reload doesn't
affect my cart.
Update
For getting the value I write the following function in my my_file.js
function get_cartObj(){
$.post(
'get_cartObj.php',
function success(data) {
console.log(data);
}
);
}
and in get_cartObj.php
<?php
/** Set up WordPress environment, just in case */
$path = preg_replace('/wp-content(?!.*wp-content).*/','',__DIR__);
require_once($path.'wp-load.php');
session_id() || session_start();
nocache_headers();
Header('Content-Type: application/json;charset=utf8');
json_encode(array(
'result' => $_SESSION['ajjx']['cart_obj'], // This in case you want to return something to the caller
));
but here get_cartObj() is not working as expected. No data coming in console.log(data);
The same way you saved it. Actually you can add a parameter to (save)CartObj:
function cartObj(operation, cartObj) {
$.post(
'cartObj.php',
{
op : operation,
cartobj : cartObj
},
function success(data) {
console.log(data);
}
);
}
and in the PHP code (7.4+ required because of the ?? operator)
if ($_POST['operation'] === 'set') {
$_SESSION['ajjx']['cartObj'] = $_POST['cartObj'] ?? [ ];
}
$value = $_SESSION['ajjx']['cartObj'] ?? [ ];
Header('Content-Type: application/json;charset=utf8');
die(json_encode(['result' => $value]));
Now calling the function with 'set' will save the Javascript cart into session, using 'get' will recover the cart.
update
You can also do it like this:
assuming that your page might receive a cart or it might not,
and you will always run the same AJAX code regardless,
then the PHP code must avoid removing the cart if the cartObj parameter is empty (you will need a different call to remove the cart when you need to do this; or you may do it from PHP).
session_id()||session_start();
if ('set' === $_POST['operation'] && !empty($_POST['cartObj'])) {
$_SESSION['ajjx']['cartObj'] = $_POST['cartObj'];
}
Header('Content-Type: application/json;charset=utf8');
die(json_encode(['result'=>$_SESSION['ajjx']['cartObj']??[]]));
This way, if you reload the page but the POSTed cart is now empty (because it's a reload), the AJAX script will not update the session, and it will return the previous session value.
Before im going to answer the question i have some dubt to clear, it looks like you are in a wordpress environment but you are not using his AJAX standard procedures. Check it out here https://codex.wordpress.org/AJAX_in_Plugins
About the issue since JS is client side and PHP is server side you need something to have the values available in JS. I can think of two option:
Print into the page with some PHP a little script tag which is made like this:
<script>
var myObjectVar = '<?php echo json_encode($_SESSION['ajjx']['cart_obj']); ?>';
</script>
You make a new AJAX call as soon as the page load to read that same value from PHP again and then use it to make what you need to do
I have passed some values from a page to another using ajax with request method post. But there is one condition that f some one is directly accessing the url, it should be redirected to some other page. Problem is that its not getting redirected (In else condition in img.php) . Can any one tell me what mistake I am committing?
Thanks in advance.
Code:-
imageupload.php:
document.getElementById("submit").addEventListener("click", function(event){
event.preventDefault();
saveImgfunc();
});
function saveImgfunc(){
var form = new FormData(document.getElementById('saveImg'));
var file = document.getElementById('imgVid').files[0];
if (file) {
form.append('imgVid', file);
}
$.ajax({
type : 'POST',
url : 'core/img.php',
data : form,
cache : false,
contentType : false,
processData : false
}).success(function(data){
document.getElementById('msg').innerHTML = data;
});
}
img.php:
<?php
require '../core.php';
$qry = new ProcessQuery('localhost', 'root', '', 'mkart');
$uid = 6;
if($_SERVER["REQUEST_METHOD"] == "POST"){
//Some code here
}
else{
header("Location : ../core.php");
}
See this post https://stackoverflow.com/a/21229246/682754
There's a good chance that you may have some whitespace before you use the header function? Perhaps in the form of a hidden error/warning.
Try the following at the top of your PHP code in img.php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
Would advise removing that once you've found your issue
It works for me removing the whitespace between Location and :
header("Location: ../core.php");
Error found. In the core.php thre is one code which stopping the further execution of code. Its specially coded for uid = 6. Thanks for your time.
Dont use header("Location : ../core.php"); some time it gives error or not working properly so use javascript redirection
like
?>
<script>window.location='../core.php';</script>
<?php
I have the following javascript loop which correctly alerts the value I need to use in a Codeigniter method. Here is the js loop:
function myInsert(){
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
// need to replace this alert with codeigniter method below
alert ($(this).prop('value'));
}
});
}
Instead of alerting the required value, I need to somehow execute this Codeigniter method:
//this would never work because it mixes JS with PHP, but I need a workaround
$this->appeal_model->myMethod($(this).prop('value'), 888, 999);
Is there someway that I can run this PHP code inside the javascript loop? I know about PHP being server-side and JS being client-side, but I'm sure there must be a solution to my problem that I'm just not aware of yet. Thanks.
The solution to this is to make an ajax call to the server, you can have a method on your controller which calls your codeigniter method. This divides your php call and your client side call.
If you are inserting something into the database, you should use the ajax post method.
http://api.jquery.com/jQuery.post/
function myInsert() {
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
var value = $(this).prop('value');
$.post("controllername/functionname", { value: value }, function(data) {
alert(data); // Returned message from the server
});
}
});
}
Use ajax to store data to the server side:
The code should be something like this:
function myInsert(){
$dataArray=[];
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
// need to replace this alert with codeigniter method below
dataArray.push($(this).prop('value'))
}
});
if(dataArray.length>0)
{
$.ajax({
url:"your file name",//this file should contain your server side scripting
type:"POST",
data:{dataName : dataArray}
success:function(){
}
});
}
}
you can use $.post from jquery
function myInsert(){
$('input[name=r_maybe].r_box').each(function(){
if( $(this).prop('checked') ){
$.post('<?php echo site_url("controllerName/functionName")?>',
{"post1": $(this).prop('value'), "post2":888, "post3": 999 },
function(data.res == "something"){
//here you can process your returned data.
}, "json"); //**
}
});
}
In your controller you can have:
function functionName()
{
//getting your posted sec token.
$post1 = $this->input->post('post1');
$post2 = $this->input->post('post2');
$post3 = $this->input->post('post3');
$data['res'] = "something";// return anything you like.
// you should use json_encode here because your post's return specified as json. see **
echo json_encode($data); //$data is checked in the callback function in jquery.
}
Since this will be dumping data directly into your db, make sure this is secured in some manner as well, in terms of who has access to that controller function and the amount of scrubbing/verification done on the data being passed.
Fiddling inside CodeIgniter and trying to get a grip on it all as I've never worked with AJAX before.
For some reason, my AJAX is working perfectly when I use the GET method, but if I switch it over to the POST method, it stops working.
My JS:
$(document).ready(function(){
$('.love').click(function(event) {
$.ajax({
type: 'GET',
url: base_url + '/ajax/love_forum_post',
data: { post_id: 2, user_id: 1, ajax: 1 },
});
return false;
});
});
And my CONTROLLER:
function love_forum_post()
{
$post_id = $this->input->get('post_id');
$user_id = $this->input->get('user_id');
$is_ajax = $this->input->get('ajax');
if ($is_ajax)
{
$this->load->model('forums_model');
$this->forums_model->add_love($post_id, $user_id);
}
// If someone tries to access the AJAX function directly.
else
{
redirect('', 'location');
}
}
If I switch the type to 'POST' inside my JS and then catch it on the other end with $this->input->post() it doesn't work.
Any suggestions?
I have tested your code in 2 scenarios:
first - without csrf protection, and I see no reason for your code not to run properly.
To be able to test it easier, append $.ajax call with success response.
Something like this
success: function(response) {
alert(response);
}
And add response to your love_forum_post method.
echo print_r($this->input->post(), true);
This would give you clean view of what it going on in your method.
In my installation everything works just fine.
Second scenario is with csrf protection.
In this case add new param to your post object.
<?php if ($this->config->item('csrf_protection') === true) : ?>
post_data.<?php echo $this->security->get_csrf_token_name()?> = '<?php echo $this->security->get_csrf_hash()?>';
<?php endif ?>
This would make CI accept post from this url.
Hopefuly it would help.
Cheers
By any chance you have csrf_protection enabled?
If yes you need to send the token and the value key as post parameter along with post request.
Try to use this
$post_data = $_POST;
and print the post data using this
print_r($post_data);die();
and you can see there if you catch the post data;
Gudluck!!
I have a file which is loaded at the top of my document, which is called Videos.php. Inside that file are several functions, such as getYoutubeVideos. On some pages, I need to call upon that function several times (up to 50), and it of course creates major lag on load times. So I have been trying to figure out how to call that function in, only when it is need (when someone clicks the show videos button). I have very little experience with jQuery's ajax abilities. I would like the ajax call to be made inside of something like this:
jQuery('a[rel=VideoPreview1).click(function(){
jQuery ("a[rel=VideoPreview1]").hide();
jQuery ("a[rel=HideVideoPreview1]").show();
jQuery ("#VideoPreview1").show();
//AJAX STUFF HERE
preventDefault();
});
Ok I have created this based on the responses, but it is still not working:
jQuery Code:
jQuery(document).ready(function(){
jQuery("a[rel=VideoPreview5]").click(function(){
jQuery("a[rel=VideoPreview5]").hide();
jQuery("a[rel=HideVideoPreview5]").show();
jQuery.post("/Classes/Video.php", {action: "getYoutubeVideos",
artist: "Train", track: "Hey, Soul Sister"},
function(data){
jQuery("#VideoPreview5").html(data);
}, 'json');
jQuery("#VideoPreview5").show();
preventDefault();
});
jQuery("a[rel=HideVideoPreview5]").click(function(){
jQuery("a[rel=VideoPreview5]").show();
jQuery("a[rel=HideVideoPreview5]").hide();
jQuery("#VideoPreview5").hide();
preventDefault();
});
});
And the PHP code:
$Action = isset($_POST['action']);
$Artist = isset($_POST['artist']);
$Track = isset($_POST['track']);
if($Action == 'getYoutubeVideos')
{
echo 'where are the videos';
echo json_encode(getYoutubeVideos($Artist.' '.$Track, 1, 5, 'relevance'));
}
$.post('Videos.php', {
'action': 'getYoutubeVideos'
}, function(data) {
// do your stuff
}, 'json');
In your php code, do something like this:
$action = isset($_POST['action'])? $_POST['action'] : '';
if($action == 'getYoutubeVideos')
{
echo json_encode(getYoutubeVideos());
}
Then data in your JavaScript function will be the array/object/value returned by getYoutubeVideos().
I would do the JS part like ThiefMaster describes, but the php part would i handle a little bit different.
I would do something like this:
if(isset($_POST['action'], $_POST['par1'], $_POST['par2'])
{
$action = $_POST['action'];
$result = $this->$action($_POST['par1'], $_POST['par2]);
echo json_encode(result);
}
But be careful, if you have some methods in the class which shouldn't be called by the user, trough manipulating POST data, then you need some way to whitelist the methods the JavaScript may call. You can do it by prefixing the methods i.e:
$this->jsMethod.$action(....);
or by simple if/switch condition.
Ok here is what ended up working:
PHP CODE
$Action = isset($_POST['action']);
if($Action == 'getYoutubeVideos')
{
getYoutubeVideos($_POST['artist'].' '.$_POST['track'], 1, 5, 'relevance');
}
JQUERY
jQuery.ajax({
type: "POST",
url: "/Classes/Video.php",
data: "action=getYoutubeVideos&artist=artist&track=track",
success: function(data){
jQuery("#VideoPreview1").html(data);
}
});
json encoding was annoying, not sure if json is hte better way of doing it, I could actually use the jQuery.post function as well, because the real problem was with the PHP. If anyone knows about any security problems with the method I am doing, please let me know. Seems fine though.