Js: pass button id to the same page - javascript

<script type="text/javascript">
$(document).ready(function () {
$(".Categories").click(function () {
var catId = $(this).attr('id');
catId = String(catId);
jQuery.ajax({
url: "index.php",
data: { catId },
type: "POST",
success: function (data) {
$("#categoryField").html(data);
}
});
});
});
</script>
I need to pass my clicked button id to the same index.php page, without page refreshing and work with that id value.My code is wrong, because page is rendered second time.
Here is my php code:
<?php
$category=$user_home->runQuery("SELECT DISTINCT category FROM products");
$category->execute();
$categoryArray=$category->fetchAll(PDO::FETCH_ASSOC);
foreach($categoryArray as $listID){
?>
<input type="button" id="<?php echo $listID['category']?>" class="Categories" value="<?php echo $listID["category"]?>"/><br>
<?
}
?>

Call preventDefault method inside the button click event handler to prevent default button behaviour ("page is rendered second time"):
...
$(".Categories").click(function (e) {
e.preventDefault();
...

There is a syntax error in your code
$(document).ready(function () {
$(".Categories").click(function () {
var catId = $(this).attr('id');
catId = String(catId);
jQuery.ajax({
url: "index.php",
data: { catId: catId },
type: "POST",
success: function (data) {
$("#categoryField").html(data);
}
});
});
});
You have to pass data in valid literal object format. {"property_name": "property_value"}.
Change: data: { catId } to data: { "catId": catId }
For server side:
<?
if (isset($_POST['catId'])) {
/* YOUR CODE FOR CATEGORY */
$catId = intval($_POST['catId']);
echo 'SUCCESS';
exit(0);
}
// YOU OTHER PHP CODE
?>

I think I need to post my variable to another page and then return it.I dont know how to do it in same page.This variant with exit(0) is bad because all variables inside if statement after exit(0) will be deleted.
<?
if (isset($_POST['catId'])) {
/* YOUR CODE FOR CATEGORY */
$catId = intval($_POST['catId']);
echo 'SUCCESS';
exit(0);
}
// YOU OTHER PHP CODE
?>

Related

Two target for one <a> tag and display two results in two different div

Student.php -here i am getting list of students from a specific Institution in a tag
<?php
if(isset($_POST['c_id'])) { //input field value which contain Institution name
$val=$_POST['c_id'];
$sql="select RegistrationId from `students` where `Institution`='$val' ";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$number=$row['RegistrationId'];
?>
<a href='<?php echo "index.php?StudentID=$number"; ?>' target="index" id="link">
//getting student id in the dynamic link
<?php echo "$number";
echo "<br/>";
}}
?>
<div id="index" name="index"> </div>
<div id="Documents"> </div>
<script>
$(document).on('change', 'a#link', function()
{
$.ajax({
url: 'Documents.php',
type: 'get',
success: function(html)
{
$('div#Documents').append(html);
}
});
});
</script>
In index.php - I am Getting students details based on $_GET['StudentID'] ('a' tag value)
<?php
$link=$_GET['StudentID'];
$sql = "select StudentName,Course,Age,Address from `students` where `RegistrationId`="."'".$link."'";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['StudentName']."<br/>";
echo $row['Course']."<br/>";
echo $row['Age']."<br/>";
echo $row['Address']."<br/>";
}
?>
In Documents.php -I am getting documents related to the speific student selected in 'a' tag
$link=$_GET['StudentID'];
$qry = "select Image,Marksheet from `documents` where `RegistrationId`='$link'";
$result = mysql_query($qry) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$image = $row["Image"];
$image1 = $row["Marksheet"];
echo '<embed src='. $image.'>';
echo ' <object data='. $image1.'width="750" height="600">';
echo ' </object>';
}
On click of student id i am trying to get result from index.php to div()
and result from Documents.php to div()
(i.e)two target for one click in tag
My code only take me to the index.php file result in a new Window
Please Help me to solve this problem
(sorry if my question seems silly i am new to php)
Update:
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
});
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
From your question, it seems that you want to load the two results, one from index.php and one from Documents.php in two separate divs on the same page when the link is clicked.
But you're using a change event on the link, not a click event. The change event is not fired when the link is clicked, so JavaScript does not get executed and the page loads to the URL specified in the href attribute of the link. So first you need to change $(document).on('change') to $(document).on('click').
Furthermore, since you want two results to load - one from index.php and one from Documents.php, you'll need to create two ajax requests, one to index.php and the other for Documents.php. In the success function of each of the ajax requests, you can get the response and put it in the corresponding divs.
In addition to this, you'll also need to prevent the page from loading to the new page specified in href attribute when the link is clicked, otherwise the ajax requests fired on clicking the link will get lost in the page load. Thus, you need to add a e.preventDefault(); to your onclick event handler like this:
$(document).on('click', 'a#link', function(e) {
// Stop new page from loading
e.preventDefault();
// Two ajax requests for index.php and Documents.php
});
Update: You don't need to add two click handlers for each ajax request. Inside one click handler, you can put both the ajax requests.
Also your event handlers won't register if you're adding them before jQuery, or if you're adding them before the DOM has loaded. So move your code to bottom of the HTML page, just before the closing </body> tag.
$(document).on('click', 'a#link', function(e) {
e.preventDefault();
$.ajax({
url:"details.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#index").html(resp);
alert(resp);
}
});
$.ajax({
url:"index.php",
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#Documents").html(resp);
alert(resp);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Link
You can change your <a> tag like below :
..
Then , in your jquery code do below changes :
$(document).on('click', 'a.link', function(e) {
var StudentID = $(this).attr("data-id") //get id
console.log(StudentID)
e.preventDefault();
$.ajax({
url: "details.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
call_next_page(StudentID);//next ajax call
}
});
});
function call_next_page(StudentID) {
$.ajax({
url: "index.php",
data: {
StudentID: StudentID
}, //pass same to ajax
type: 'POST',
success: function(response) {
//do something
}
});
}
And then at your backend page use $_POST['StudentID'] to get value of student id instead of $_GET['StudentID'];

mysql_php_insert query from inside a while

I'm trying to make a like button, but i can't send proper query from a loop.
this is my sample code:
$supql="SELECT * FROM `tbl_users_posts`";
$rez=mysqli_query($conn,$supql);
while ($row=mysqli_fetch_assoc($rez)){
$psid=$row['id'];
echo $row['post']."<br>";
$squlk="SELECT uid FROM t_plik WHERE pid='$psid' AND uid='$uid'";
$msqs=mysqli_query($conn,$squlk);
$asnu=mysqli_num_rows($msqs);
if($asnu==0){?>
like
<?php }else{ ?>
unlike
<?php }
}
i try send this query:
if(isset($_POST['liked'])){
$pstid=$_POST['postid'];
$inslik="INSERT INTO t_plik (pid,uid)VALUES('$pstid','$uid') ";
mysqli_query($conn,$inslik);
}
with this jquery code:
<script>
$(document).ready(function() {
//when click on like
$('.like').click(function(){
var postid = $(this).attr('id');
$.ajax({
url:'test.php',
type:'post',
async: false,
data:{
'liked': 1,
'postid':postid
},
success:function(){
}
});
});
});
</script>
but every time when i click like button i can send query for last post id. how can i affect other postids inside the while?
thanks

How to post a value to a controller function on button click using Ajax and also redirect to new page at the same time?

I have a button Next that changes the page -
<a class="disabled" href="step">
<button class="btn btn-primary launch-btn disabled next">NEXT</button>
</a>
Also, when this button is clicked, I have an Ajax function that sends data to a controller function -
<script type="text/javascript">
$(function(){
$('.next').click(function() {
var a = $('#box').data('val');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>study/CreateData",
data: a,
success: function(data)
{
console.log(data);
},
error: function()
{
console.log("fail");
}
});
});
});
</script>
And I'm using this to receive the value from Ajax -
public function CreateData() {
$data = $this->input->post('data');
return $data;
}
When the Next button hits its controller where it changes to a new page, I'm trying to retrieve the value posted by Ajax to the CreateData() function -
public function step()
{
$data = $this->CreateData();
if(!empty($data)){
print_r($data); exit;
}
else {
echo "blank"; exit;
}
$this->load->view('step2');
}
However, this keeps echoing blank. This obviously means that the $data being returned is empty but I'm not sure why. The success function in my Ajax script is logging data, so it's posting the value to CreateData(). What am I doing wrong here?
Your javascript should be something like this
<script type="text/javascript">
$(function(){
$('.next').click(function() {
var a = $('#box').data('val');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>study/CreateData",
data: {my_data: a},
success: function(data)
{
console.log(data);
},
error: function()
{
console.log("fail");
}
});
});
});
</script>
Notice the data property. I have changed it to an object containing the variable a.
Now you should be able to retrieve this in your php function using
public function CreateData() {
$data = $this->input->post('my_data');
return $data;
}
Adr's answer solved part of the problem. In order to actually store and access the data, storing it in the session instead of a variable did the trick -
public function CreateData() {
$data = $this->input->post();
$this->session->unset_userdata('createData');
$this->session->set_userdata('createData', $data);
}
This prevented the $data variable from being overwritten when called the second time.

PHP function is not echoing anything in Zend Framework

I'm working on a website where clicking on a button will cause a variable to be initialized containing the contents of the associated text field.
However, I've noticed that none of my echo commands are executed and none of the related JS-alerts are showing up either. I have already checked the debugger and know that the action requests are being validated. It's just that nothing is showing up.
My controller:
public function validateuser2Action() {
echo 'asdasdfasdf';
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if (Zend_Auth::getInstance()->hasIdentity()) {
$model = new Application_Model_User();
$emailAddress = $this->getRequest()->getPost("emailAddress");
echo 'he';
} else{
echo 'whatever';
}
}
My PHTML-file:
<script>
$(document).ready(function() {
$(".btn-test").click(function() {
var form_data = document.getElementById("textbox").value
var form_url = "/workspace/validateuser2";
var form_method = "POST";
alert("cool");
$.ajax({
url: form_url,
type: 'POST',
data: form_data,
success: function(data){
alert(data);
},
error: function(){
alert("tpai");
}
});
})
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

Calling js function on button click isn't working

Any reason why this isn't running when clicked? I can't seem to figure it out.
<button id="button-container-like" onclick="rate($(this).attr(\'id\'))"><span class="thumbs-up"></span>Like</button>
<script>
function rate(rating){
var data = 'rating='+rating+'&id=<?php echo $eventId; ?>&userid56=<?PHP echo $userid55; ?>';
$.ajax({
type: 'POST',
url: 'includes/rate.php', //POSTS FORM TO THIS FILE
data: data,
success: function(e){
$(".ratings").html(e); //REPLACES THE TEXT OF view.php
}
});
}
</script>
here you go:
<button id="button-container-like" ><span class="thumbs-up"></span>Like</button>
<script>
jQuery(document).ready(function () {
$("#button-container-like").click(function() {
rate($(this).attr("id"));
});
function rate(rating) {
var data = 'rating=' + rating + '&id=<?php echo $eventId; ?>&userid56=<?PHP echo $userid55; ?>';
$.ajax({
type: 'POST',
url: 'includes/rate.php', //POSTS FORM TO THIS FILE
data: data,
success: function(e) {
$(".ratings").html(e); //REPLACES THE TEXT OF view.php
}
});
}
});
</script>
If there's nothing else going on in this code, then remove the slashes from your onclick code. They are unnecessary and cause an error.
onclick="rate($(this).attr('id'))"

Categories