update session variables inside Javascript - javascript

I have a page called index.php where i have all my php functions, javascripts and html tags.
Upon button click (add to cart) event i want to call a php function ( addtToCart($itemID) ) to update session variables. Can you tell me how to implement this in my code ?
<?php
session_start();
$_SESSION['Mid']="";
$_SESSION['$UserName']="test"; ?>
//html part
<button id='cart'
onclick="<script>idk how to call my function here</script>"
class="w3-button">ADD TO CART</button>
//my php function
<?php
function addToCart($Mid){
if(!isset($_SESSION['$UserName'])){
header('Location:signin.html');
}
$_SESSION['Mid'].="+".$Mid;
echo "<script type='text/javascript'>alert(\"ADDED TO CART\");</script>";
}
?>

Use an aJax call to call another PHP script that updates it:
var SendInfo= { "your": data,
"your1": data1 };
$.ajax({
type: 'POST',
url: 'https://yourscript.com/updatesession.php',
data: SendInfo,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
traditional: true,
success: function (data) {
//dostuff
}
});

Related

Can't get JavaScript result using ajax script

I am calling php file with ajax script.but when I am trying to call JavaScript in called php file it's not giving me JavaScript result in response. It's give me
Full script stored in variable.
index.php
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//Here i am print response
}
});
response.php
$return = $_POST;
$return["js"] = "<script>test();</script>";
$return["json"] = json_encode($return);
echo json_encode($return);
?>
<script>
function test(){
return 'Hello';
}
Can any one suggest me. Thanks in advance

AJAX redirect to another php file and pass javascript variable to that same php file

I am new to Ajax. I have here a function that when a button is clicked, you should be redirected to id.php and at the same time pass the value of clicked_id.
Javascript code:
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
$.post('id.php',{ID:clicked_id},
function(data){
window.alert("here");
window.location='id.php';
});
}
Inside my id.php,
<?php
$clickedID = $_GET['ID'];
echo 'here at id.php';
echo $clickedID;
?>
Now the problem is that ID in id.php cannot be identified.
Please help me. I already tried both $_POST and $_GET.
I believe that the problem here is in the passing of the variable.
there is no need for ajax if you wanna pass the id to the id.php after redirection
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
window.location='id.php?id=' + clicked_id;
}
in id.php you can get the id like this:
<?php $id = $_GET['id'];
function buttonClicked() {
$.ajax({
url: "id.php", //url for php function
type: "POST",
data: {'clicked_id':clicked_id}, // data to sent
dataType: 'json',
success: function (data)
{
}
});
}
And in your id.php file:
$_REQUEST['clicked_id']

how to use JavaScript variable in php

I have an onClick event in my test.php file:
for($i=0;$i<4;$i++)
<tr><td onclick="testfun(".$i.")"></td></tr>
Script:
<script>
function testfun(i)
return i;
<script>
Now I want to use that $i in PHP to see on which <tr> the mouse is clicked on so I can perform my other functionalities in the PHP file. e.g
<?php echo $i?>
How can I do that? I saw some AJAX tutorials but I didn't get how its gonna work on my code.
in your html add this to your javascript
$('#clickhere').click(function(){
//get value here from your function
// do the ajax
$.ajax({
url: "path/of/your/php/file.php",
dataType: 'JSON',
data: value_that_you_fetch,
type: 'POST',
success: function(data){
// do something here
}
});
});
and don't forget to add a jquery CDN
and in your file.php
<?php
echo $_POST['value_that_you_fetch'];
the rest is up to you.
your php code should be like this
<?php
for($i=0;$i<4;$i++){
?>
<tr><td onclick="testfun(<?php echo $i ?>)"></td></tr>
<?php } ?>
and javascript code
<script>
function testfun(i){
return i;
}
<script>
So, if this is your onClick event handler:
function testfun(i){
return i;
}
The quickest way to get on to the next step is to have it be something like:
function testfun(i){
$.ajax( {
url: "/ajaxtest.php?i=" + i,
type: 'GET',
// ... other options depend on what you want returned.
} );
}
This is a deep rabbit hole your are looking down into here.

Send js value to php controller by ajax

I have this button
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
And this button related to this
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
I'm using this script to send value of button to my php controller
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable,
success: function (data){
}
});
}
When I use alert, the result of javascriptVariable is correct and I want it in my controller so I'm trying in my controller to do this:
if(isset($_POST['activation']))
{
$name = $this->input->post('myname');
var_dump($name);
}
But I get null value, what is the wrong?
When you pass data from the browser via AJAX only the data you pass in the data: parameter is sent to the PHP script.
So if you want to test for activation in the PHP script you must actually send that parameter
Also see the amendment to the data: parameter creation below. Its easier to read and a lot easier to code correctly when passing more than one parameter as you dont have to remember &'s and + concatenation.
function handleButton(obj) {
obj.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {activation: 1, myname: obj.id}, // add parameter
success: function (data){
alert(data);
}
});
}
Now the PHP will see 2 parameters in the $_POST array activation and myname
if(isset($_POST['activation']))
{
$name = $_POST['myname'];
var_dumb($name);
}
Or if you are using a framework which I assume you are
if(isset($this->input->post('activation')) {
$name = $this->input->post('myname');
var_dumb($name);
}
EDIT:
Spotted another issue your button has an attribute type="submit" this will cause the javascript to run AS WELL AS the form being submitted in the normal way.
Remove the type="submit" attribute and to be doubly sure that the form will not be submitted as well as the AJAX add a call to preventDefault(); as well before the AJAX call
Since the php script is conditioned by a second POST variable [if(isset($_POST['activation']))], you should post that as well.
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable+'&activation=1',// <-- RIGHT HERE
success: function (data){
alert(data);
}
});
}
SIDE NOTE: you could also echo instead of dump the variable:
if(isset($_POST['activation']))
{
echo $this->input->post('myname');
}
Try this in your ajax function :
function handleButton(obj) {
var javascriptVariable = obj.id;
//alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {myname: javascriptVariable},
success: function (data) {}
});
}
And in your PHP script, you can do $_POST['myname'] to get it (maybe $this->input->post('myname') can work, you can test it)
Look two id
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
AND
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
For both html elements id is same.It can not be used with in the same page.This may cause a problem for you...

Submit form for php without refreshing page

I've search for many solution but without success.
I have a html form;
<form id="objectsForm" method="POST">
<input type="submit" name="objectsButton" id="objectsButton">
</form>
This is used for a menu button.
I'm using jquery to prevent the site from refreshing;
$('#objectsForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function () {
alert('success');
}
});
});
In my php file I try to echo text to the body of my site;
<?php
if (isset($_POST["objectsButton"])){
echo '<div id="success"><p>objects</p></div>';
} else {
echo '<div id="fail"><p>nope</p></div>';
}
?>
I know the path to my php file is correct, but it doesn't show anything? Not even the "fail div".
Does anyone has a solution for me?
Thanks in advance!
The success function takes two parameters. The first parameter is what is returned from the php file. Try changing it to:
success: function (xhr){ alert(xhr);}
Based in your php source..
$.ajax({
type: 'post',
dataType: "html", // Receive html content
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function (result) {
$('#divResult').html(result);
}
});
PHP scripts run on the server, that means any echo you do won't appear at the user's end.
Instead of echoing the html just echo a json encoded success/ failure flag e.g. 0 or 1.
You'll be able to get that value in your success function and use jQuery to place divs on the web page.
PHP:
<?php
if (isset($_POST["objectsButton"])){
echo json_encode(1); // for success
} else {
echo json_encode(0); // for failure
}
?>
jQuery:
var formData = $('#objectsForm').serializeArray();
formData.push({name:this.name, value:this.value });
$.ajax({
type: 'post',
url: '/php/objects.php',
dataType: 'json',
data: formData,
success: function (response) {
if (response == 1) {
alert('success');
} else {
alert('fail');
}
}
});
EDIT:
To include the button, try using the following (just before the $.ajax block, see above):
formData.push({name:this.name, value:this.value });
Also, have the value attribute for your button:
<input type="submit" name="objectsButton" value="objectsButton" id="objectsButton">

Categories