sending span text to another page with JS and php - javascript

I have a dynamically changing span on a page displaying the number of votes a project has received. On another (target) page i have a list of projects. i want to be able to display that vote count there. i know how to grab the text from the span on the page.
it would be something like this.
<span id="count1"></span>
var prj1c = $("#count1").text;
in know that on the other page i end up using
<?php echo $prj1c(this being after i assign the prj1c var to php somewhere) ?>
i also know i could create a php include page and call it on the target page, though i would like not to create a separate page for each of these instances.
so to sum up: how do i change a JS var to php and call it from another page- remember the text in the span changes (when users vote up or down)?

Try this, use .text() instead of .text
var prj1c = $("#count1").text(); //instead of var prj1c = $("#count1").text;
$.ajax({
type: "POST",
url: "yourpage.php",
data: {count :prj1c},
success: function(response) {
alert("Response "+response);
}
});
in yourpage.php add this <?php echo $_POST['count']; ?>
Update:
$(function(){
$("#count1").click(function(){
window.location='page2.php?count='+$(this).text();
});
});
in page2.php:
<ul>
<li id="projectName">
<img><span>vote count goes HERE: <?php echo $_GET['count']; ?></span>
</li></ul>

You can try with jQuery Ajax request. When user vote up/down you can make an ajax call to the target page.
Eg.
var prj1c = $("#count1").text();
$.ajax({
type: "POST",
url: "targetPage.php",
data: "count="+prj1c,
success: function(response) {
alert("Response "+response);
}
});
Get the prj1c value in targetPage.php
$prj1c = $_REQUEST['count'];
// Follow appropriate steps later in targetPage.php

Related

How to refresh specific div using Javascript/Jquery with the variables on it

I have a variable $salary which is dynamic. How can I refresh specific div every 5seconds.
index.html
<html>
<body>
<img src="<?php echo $filename.'.jpg'; ?>" />
<p id="salary"><?php echo $salary; ?></p>
</body>
</html>
Is there any javascript/jquery way to refresh #salary only. Please help..
You can execute an ajax call:
function ajaxCall() {
$.ajax({
method: 'POST',
url: 'path/to/asyncHalndler.php',
data: { ... },
success: function (data) {
if (data) {
$('#salary').html(data);
}
}
});
}
// Execute ajax call every 5 seconds
setInterval(function() {
ajaxCall();
},5000);
var salary = document.getElementById('salary');
Now, the value of your variable salary will be the DOM node where you would like to change the value. When you get new data, you can refresh text inside your p tag with salary id by adding salary.innerText = yourNewValue;
This is pure JavaScript way of updating that element with id.
It's better to use ajax way. But if u are looking for a very simple solution then jQuery .load will be the best
setInterval($("#salary").load("<url to get the value>"), 1000);
You will need an jquery ajax call for that.
first you should create php file get_salary.php where you send id from jquery ajax if you want to update the salary for unique id:
in get_salary.php you need to get salary from database so the code in this php file will be like that
$id = $_POST['ID']
$query = mysql_query("SELECT * FROM sallaries WHERE id='$id'") or die("Can't connect");
$fetch = mysql_fetch_array($query)
$salary = $fetch['salary']
echo $salary
after that you will need javascript file(e.g script.js) from where you will send the request and id to the get_salary.php and grab the data from it, after that you will be able to update salary in html, so code in javascript file will be like that:
function updateSalary(){}
var id=25;
$.ajax({
url: "get_salary.php",
type: 'POST',
//sending id
data:'id='+id,
success: function(result){
//updating html
$("#salary").html(result);
}
});
}
//setting interval to update in every second
setInterval(updateSalary, 1000)
so it will update your salary in the div

Is it possible to load content of page without Refreshing the whole page

Actually i want to refresh my content of a page without Refreshing the whole page through JavaScript or j Query ....... and i did my whole project into ( Php or javaScript) so i face such type of problem
Note : i want to refresh my page content when user do some action
Here is my Code:
//On Button click, the below will be execute:
$('body').on('click', '#click', loadDoc);
and the LoadDoc functio:
function loadDoc() {
//alert('heruybvifr');
var _this = $(this);
var order_id= $(this).parents('.modal').find('.order-id').text();
$.get('myPHP.php',{order_id: order_id},function(){
_this.hide();
})
}
Now myPHP.php :
<?php
include("connection.php");
$limit = intval($_GET['order_id']);
echo $valuek;
$query="UPDATE orders
SET status ='cooking'
WHERE id = $limit";
if (mysqli_query($connection,$query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
?>
Yes you can use the jQuery.ajax() call. Like this:
Change the text of a element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
See this tutorial for more information:
http://www.w3schools.com/jquery/ajax_ajax.asp
You can use JQuery Ajax functions to accomplish your requirement.
all there functions given below will work for loading the content without refreshing the page.
$.post("/controller/function", params, function(data) {
// set received data to html
});
$.ajax("/controller/function", params, function(data) {
// set received data to html
});
$.get("/controller/function", params, function(data) {
// set received data to html
});
You can load the data from the server and and place the returned HTML into the matched element.
<div id="content"></div>
$("#content").load( "ajax/test.html" );

How do i send parameter in ajax function call in jquery

I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});

how to pass php value from one file to another through java script

I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}

Assigning selectors to variables to call them depending on the type of button

Thats the best description I could think of. I normally do not post, but I honestly cannot figure this out.
Still in jquery learning mode, and basically what I want to accomplish is that depending on the type of button that is submitted, the script assigns variables to div's on the page. What I am making is a admin side of a user script to allow them to update that particular div that appears on the page.
When I put in the actual selectors, the script works.
When the page loads, it will take the field of the database that corresponds with the and load it. Once they push the update button, a new div will appear. The admin inputs his new data (the new information he wants to display) and it updates the mysql table, then pulls it back in through jquery's ajax.
Sorry for the long explanation. Like I said, I've never really posted, just always liked figuring it out on my own.
php page
<?php //
if(isLoggedIn())
{
echo '<button id="adultClassButton">Edit Class Information</button>';
}
?>
<div class="class" id="adultClass"><?php
$row = checkPost('adult');
echo $row['info'];
?>
</div>
<?php
echo '<div id="adultClassInput">
<textarea rows="2" cols="80" id="adultClassUpdate"></textarea>
<input type="hidden" id="className" name="adult"/>
<button id="adult">Save the Updated Class Info</button></div>';
?>
javascript (jquery) file
$(".button").click(function(){
var button = $(this).attr('id');
if (button == 'adult'){
var classDiv = $("#adultClass");
var className = $("#className");
var classDesc = $("#adultClassUpdate").val();
var classUpdateDiv = $("#adultClassInput");
postData(classDiv, className, classDesc, classUpdateDiv);
}
});
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: "name="+ className+ "& info="+ classDesc,
success:function(data){
$("#" + classDiv).html(data);
}
})
$("#" + classDesc).val('');
$("#" + classUpdateDiv).hide();
}
Like I said, if I have normal selectors in the function, it works as intended. But as of right now, I'm just stumped as to whats wrong.
Thanks a bunch!
classDiv is a jquery object not the ID of the element. So when you use this
$("#" + classDiv).html(data);
That's not working as expected.
Try
classDiv.html(data);
Your function should be like this:
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: {"name": className.val(), "info": classDesc}
success:function(data){
classDiv.html(data);
}
})
$("#"+classDesc).val('');
classUpdateDiv.hide();
}
because you already passed jquery objects (not strings) to your function, except for classDesc.
Hope this helps. Cheers

Categories