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.
Related
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
}
});
I've a problem with my page, first code (let said is hompe.php)
<html>
<div id="trackingkp"></div>
</html>
then on my ajax I've code like these
$( document ).ready(function() {
var dataString = '';
$.ajax
({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'html',
success: function(html)
{
$('#trackingkp').html($(html).find('#trackingkp').html());
//$("#trackingkp").html($(data).find('#trackingkp').html());
}
});
});
and on my ajax controller, I do like these (I'm using framework laravel)
public function tracking($url)
{
//var_dump("AAA");
$this->view('ajax/tracking/'.$url,[]);
}
on my ajax/tracking view like this
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
When I try that is showing
Syntax error, unrecognized expression: "<input type='text'>
I have solved the problem, I'm using another option without using jQuery, so on same time, on controller when load view home.php, I try put load view too like these
public function index(){
is_header();
$this->view('home',[]);
$this->view('ajax/tracking/kp',[]); ---> I add these
is_footer();
}
and on ajax/tracking/kp (view) I put these code
<input type='text'></input>
and is working.
The problem would be in this one:
success: function(html) {
// Problem : $(html).find('#trackingkp').html();
$('#trackingkp').html($(html).find('#trackingkp').html());
}
From which this html response is expected to return a json value
in your given [controller]
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
Thus this is equivalent to:
$("<input type='text'></input>").find('#trackingkp').html();
In this case, I don't think you might need to call another *.html(). You can simplify / solve this by calling it once:
$.ajax({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'json', // Kindly replace [html] to [json] since you are returning a [json] value
success: function(html) {
$('#trackingkp').html(html);
}
});
Hope this helps for your case
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...
I have searched and tested different solutions all day without luck. In the below code I want (when clicked) to set a session on the "open" links I echo in the foreach loop. I tried using AJAX but I am new to AJAX and could not make it work. I know how to do it using GET but it is too risky, so i welcome your suggestion and preferably examples.
$task_array = array_combine($task_id_unique, $task_status);
foreach ($task_array as $card_nr => $card_status) {
?>
<table>
<tr>
<th>card nr.</th>
<th>Status</th>
</tr>
<td><?php
echo $card_nr;?></td>
<td>
<?php
if ($card_status == true) {
echo "<a href=workcard.php>Open</a>";
}
else echo "Done ". $card_nr;?></td>
</table>
What have you tried and what doesn't work, because this looks like what you need...
HTML:
Register Now!
PHP:
if(isset($_GET['a'])){
$_SESSION['link']= 'whatever';
}
And if you need to do it without a page refresh, then use AJAX.
You should use ajax on click of link:
$.ajax({
url: 'test.php',
dataType: 'json',
type: 'post',
data: {name: "value", name2: "value2" /* ... */},
success: function (data) {
}
});
in your test.php, $_POST['name'] is equal to "value". and there you can do everything you want.
first, add html class on "Open" link and custom html5 attribute to store your card data. for example data-card.
Open
next, create Onclick event for a link to send an ajax request.
$( document ).ready(function() {
$(".your-class").click(function() {
var card_nr = $(this).attr('data-card');
$.ajax({
url: "workcard.php",
type: "POST",
data: "card=" + card_nr
}).done(function() {
// do something
});
return false;
});
});
I have a problem that my Js file is not recognizing a php variable built by ajax.
Here is an example:
index.php:
<script src="js.js">
</script>
<?
include('build.php');
<div id="brand">
<?
echo $brandinput;
?>
</div>
//....more code
?>
build.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function(data){
$("#result").html(data);
}
});
</script>
<?php $brandinput='<div id="result"></div>';
?>
js.js:
$(document).ready(function(){
//dosomething with div's in index.php
}
So, I'll try to explain this in the easiest way. My index.php includes a build.php which as you can see calls ajax to retrieve data from another server. This data is located in a php variable ($brandinput) which will contain many <div>,<input>,... etc. Then index.php echo $brandinput, showing all the content of the variable. But I have a js.js which change appearances in div's, input's, etc.. and is this js which is not recognizing the content of the variable $brandinput.
I'd like to know if you have more ideas or what am I doing wrong...
All the code is working well, I tested many times (except for what I said before)
The ajax call work well and Index.php displays $braninput correctly.
p.s. $brandinput is something like this:
<div id='BlackBerry'><img src='..\/images\/supporteddevices\/blackberry-logo.jpg' alt='blackberry-logo' width='75'><br><input class='adjustRadio' type='radio'
and yeah it works well too.
Actually this is how it supposed to be working, what you need to do is to wait for the ajax request to finish first before executing the functions in js.js
try this way
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
//dosomething with div's in index.php
}
});
});
or (assuming js.js is loaded after the script within build.php, or js.js has to be loaded after it)
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
}
});
});
// in js.js
$(document).ready(function () {
promise.then(function (data) {
//dosomething with div's in index.php
});
});
P.S
$brandinput just hold the string whatever assigned to, and will never be changed with ajax request, where ajax success handler just manipulate the rendered DOM directly in the client side.
You can try moving your <script> tag to after your php codes like this:
<? include('build.php'); ?>
<div id="brand">
<? echo $brandinput; ?>
</div>
<script src="js.js"></script>
//....more code
On a slightly different note, you should consider avoid embedding/intermixing PHP codes with HTML and Javascript. Take a look at this post for better ways way "passing data from PHP to Javascript".