I need to click an image and it should run some php script that sets a php variable and reloads the same page.
I know it sounds simple but i've tried every different way I can think of and i'm guessing it's just something basic i've missed.
I've tried onclick of the image, a href and a onclick, making the image the 'submit button' of a form etc..
Any response would be appreciated.
<a href="#" class='lang'><img src="/images/flags/it.png" alt="it_IT" /></a>
<a href="#" class='lang'><img src="/images/flags/fr.png" alt="fr_FR" /></a>
I want the image alt value to pass it,
How it is possible please give some idea..
try this:
Lets say that the PHP variable you want to change is $my_var:
Set it like this:
if(isset($_GET['VarValue']) And !empty($_GET['VarValue'])){
//if it is passed and not empty store it
$my_var = $_GET['VarValue'];
}
else{ die(''); }//else don't let them display the page.
In the image put an On Click Listener hat call this function PHP_var();
In JavaScript add this function:
function PHP_var(){
location = "?VarValue=The_Value_That_You_Want_To_Set";
}
And the URL must be like this when you first call this page(lets say it is http://www.example.com/script.php?VarValue=The_First_Valeu_Of_Variable).
The function will change the VarValue value and will reload the page
try
$('.lang img').on('click',function(){
var lang = $(this).attr('alt');
var postdata = 'lang='+lang;
$.ajax({
type:'POST',
data:postdata,
url:'process/yourscript.php',
success:function(data){
// more processing here
}
});
return false;
});
Use onclick="ajaxFunctionName()" to call an ajax function which executes your script
<a href="javascript:;" onclick="ajaxFunctionName()" class='lang'><img src="/images/flags/it.png" alt="it_IT"/></a>
<a href="javascript:;" onclick="ajaxFunctionName()" class='lang'><img src="/images/flags/fr.png" alt="fr_FR"/></a>
function ajaxFunctionName() {
$.post({
var lang = $( this ).children('img').attr('alt');
url: "script.php?lang="+lang
}).done(function() {
// do something
});
}
or
<img class='lang' src="/images/flags/it.png" alt="it_IT"/>
$('.lang').click(function(){
$.post({
var lang = $( this ).attr('alt');
url: "script.php?lang="+lang
}).done(function() {
// do something
});
});
Related
The following function is inside a page (mainpage.php) which I load dynamically into a tab (tabcontent.php) .
$('.editlink').on('click', function() {
var id = $(this).attr('data-ds');
$.ajax({
url: 'noticejob.php?step=get&ds='+id,
method: 'GET'
}).success(function(response,status) {
...
});
});
I call this function by this link, which is inside the tabcontent.php
<i class="fa fa-pencil"></i>
All works fine.
Now I want to start this function over a url call for adding links into other pages to open the mainpage.php and start with this function (should open a modal).
For Example: mainpage.php?start=edit&ds=123
Is it possible and in which way?
You can just print the JS you need to execute in the PHP page.
...
?>
<script>
$(function() {
foo();
});
</script>
<?php
...
To open the modal automatically, either create a JS function that opens the modal and call it (with the previous method), or do
<script>
$(function() { $('.editlink').click(); });
</script>
Ok, now it works,
i've put a new (named "edit_function") js function into the mainpage.php with the "old" code of the "$('.editlink').on('click', function() {..."
after that i call this function from the mainpage if there is a url parameter. I do it into the php file and create a dynamicaly js code
if($_GET['job']=='new')
{
$p['JS']='edit_function("'.$_GET['detail'].'");';
}
at the other hand i call the function for the tabcontent.php page in this way
$('.editlink').on('click', function() {
var id = $(this).attr('data-ds');
edit_function(id);
});
for me it works
I want to change url without reload the page because Im using AJAX function to reload a div.
The problem is that when the AJAX load the div, it doesn't read the url parameter.
My code (I've already load the jquery.js etc.) :
index.php
<a href="#page=1" onClick='refresh()'> Link </a>
<a href="#page=2" onClick='refresh()'> Link2 </a>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
function refresh() {
$("#test").load("mypage.php"); //Refresh
}
</script>
<div id="test">
</div>
mypage.php
<?php
if (isset($_GET['page'])){
$page = $_GET['page'];
}
echo $page;
?>
PHP can't read the fragment without reloading the page. This can be done using JS.
Below the script I use to read the parameter values without reloading the page. I don't think it's the best method there is, as there are plugins you could use to do the same (and much more), but it works. I found it online some time ago, but unfortunately I don't remember where :(
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.hash.slice(1);
urlParams = {};
while (match = search.exec(query)) {
urlParams[decode(match[1])] = decode(match[2]);
}
})();
You would then get the parameter value with:
urlParams['page']
If you will work a lot with hash urls, you should check out this plugin: http://benalman.com/projects/jquery-bbq-plugin/
Getting after # hash tag:
With PHP (Required page load)
parse_url() fragment index thats you need
$url = parse_url($_SERVER['REQUEST_URI']);
$url["fragment"]; //This variable contains the fragment
With jQuery: (Not required page load)
var hash = $(this).attr('href').split('#')[1];
var hash = $(this).attr('href').match(/#(.*$)/)[1];
Demo (Used without hash tag)
index.php
Link | Link2
<script type="text/javascript">
$(".myLink").click(function(e) { // when click myLink class
e.preventDefault(); // Do nothing
var pageId = $(this).attr('data-id'); // get page id from setted data-id tag
$.ajax({
type:'POST',
url:'mypage.php', // post to file
data: { id: pageId}, // post data id
success:function(response){
$("#test").html(response); // write into div on success function
}
});
});
</script>
<div id="test"></div>
mypage.php
<?php
// get with $_POST['id']
echo "Loaded Page ID: ".($_POST['id'] ? $_POST['id'] : "FAILED");
?>
You need to pass a page parameter to the URL you're requesting.
Try this:
<a href="#page=1" onClick='refresh(1)'> Link </a>
<a href="#page=2" onClick='refresh(2)'> Link2 </a>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
function refresh(pageNumber) {
$("#test").load("mypage.php?page="+pageNumber); //Refresh
}
</script>
It is possible for you to pass parameters through the load() function in jQuery.
There are 2 common ways of doing so:
Using get:
JS:
$('#test').load('mypage.php?page=mypage');
PHP:
<?php
if (isset($_GET['page']))
{
$page = $_GET['page'];
}
echo $page;
?>
Or using data as a post:
JS:
$('#test').load('mypage.php', { page: mypage });
PHP:
if (isset($_POST['page']))
{
$page = $_POST['page'];
}
echo $page;
?>
I am passing value to a bootstarp modal form like this -
echo '<a data-toggle="modal" data-id="ISBN564541" data-toggle="modal" title="Add this item" class="open-AddBookDialog" href="#addBookDialog">';
javascript:
<script>
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).data('id');
$(".modal-body #bookId").val( myBookId );
$('#addBookDialog').modal('show');
});
</script>
And receiving it in a text area like this -
echo '<textarea name="bookId" id="bookId"></textarea>';
Now my question is how to get this value into a php variable say $receivedValue?
You have to POST it to your PHP script using AJAX-request or plain form submission.
The only way that I can think about is to use post or get method threw the '$.ajax' method.
Here is the code that you need:
.ajax({
url : "URL of the php script",
type: "POST",
data : //The data that you want to pass
success: function(res)
{
//code if everything passed fine
}
});
I have a link that looks like this:
<p class="half_text">
<?php echo $upvotes; ?>
<strong><a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a></strong> |
<?php echo $downvotes; ?>
<strong><a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#">Vote Down</a></strong>
</p>
and I have the jQuery code that looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.vote_up').click(function()
{
alert("up");
alert ( "test: " + $(this).attr("problem_id") );
// $(this).attr("data-problemID").
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
//Return false to prevent page navigation
return false;
});
});
</script>
How can I get the parameter value which is problem_id ? If I add a url in the href parameter, I think the browser will just go to the url, no? Otherwise - how can I pack parameter values into the jQuery?
Thanks!
Because your $.ajax is defined in the same scope of the variable, you can use problem_id to obtain the variable value.
An overview of your current code:
var problem_id = "something"; //Defining problem_id
...
$.ajax(
...
success: function(){
...
//problem_id can also be accessed from here, because it has previously been
// defined in the same scope
...
}, ...)
....
If what you're trying to figure out is how to embed the problem ID in the link from your PHP so that you can fetch it when the link it clicked on, then you can put it a couple different places. You can put an href on the link and fetch the problem ID from the href. If you just do a return(false) from your click handler, then the link will not be followed upon click.
You can also put it as a custom attribute on the link tag like this:
<a class="vote_up" data-problemID="12" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a>
And, then in your jQuery click handler, you can retrieve it with this:
$(this).attr("data-problemID").
do you mean, getting variables from the php page posted?
or to post?
anyway here's a snippet to replace the $.ajax
$.post('/problems/vote.php', {problem_id: problem_id, action: 'up'}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
{problem_id: problem_id, action: 'up'} are the variables posted... use $_POST['problem_id'] and $_POST['action'] to process..
use simple variables names with jQuery.data and make sure you have latest jQuery..
let me try to round it up..
up
down
<script type="text/javascript">
$('.votelink').click(function() {
$.post('/problems/vote.php', {problem_id: $(this).data('problemid'), action: $(this).data('action')}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
});
</script>
I have a profile page that contains a series of images. I want to use jQuery to allow the user to delete an image from the server and have the page update without reloading the entire page. When it's successful, it will remove the image's containing div from the page. My delete function is PHP; fairly simple:
delete.php
<?php
if (isset($_POST['id'])) {
if (unlink($_POST['id'])) {
echo "success";
}
else {
echo "failure";
}
}
?>
(There's already user authentication in place just to get them to the page that calls delete.php.)
Here's the html of one displayed image - there can be up to 5 of these chunks one after another:
<div class="box">
<img src="uploads/t_10DOT_22C_1111_1300370702_3.jpg" />
<h5><a rel="external" href="uploads/10DOT_22C_1111_1300370702_3.jpg">See full version</a></h5>
<a href="#" id="10DOT_22C_1111_1300370702_3.jpg" class="delete" onclick="return ConfirmDelete();" >x</a>
<div class="clear"></div>
</div>
My jQuery so far looks like this:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(data){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The part I'm concerned with is the ajax post. How does the success part actually work? What do I need to do in my php file so that ajax knows whether the delete was a success or failure?
Once an ajax post request has finished executing the file you sent the request to, if there was no error, the code you add in the "success" section is executed, in this case
success: function(data){
/*The code you need*/
});
The previous part if where the code is executed, the "data" variable contains anything you return from your php file, it can be data, it can be a simple "true" or "false", you choose what to send to let your jQuery know if it was successful.
Hope this helps a bit.
Edit Note:
function(applyData){
if ( applyData.toString() == 'invalid' ){
$('#pollError').html('Global styles cannot be modified.');
$('#pollNotice').html('');
}
else{
$('#pollNotice').html('The changes to the style have been applied.');
}
});
The previous example is a live example of what you can do inside the function in the "success" event. There I handle an "invalid" status and otherwise it's successful, after that I refresh a couple DIVs in case of invalid or update a single DIV in case of success.
This is the php that executes:
if ( !$db->isGlobal($id_css)){
$data['id_poll'] = $id_poll;
$data['id_css'] = $id_css;
$data['css'] = $css;
$db->applyCssChanges($data);
}
else{
echo 'invalid';
}
You've two obvious options I can think of:
Your returned text should appear in the data parameter supplied to your success callback function - however you'll probably also need to make sure it's in a format compatible with the MIME Content-Type returned by your PHP, or jQuery might complain that it can't parse it, or:
Send back a 5xx Failure type message from your PHP using the header() function if the delete didn't work. That should then trigger an AJAX error callback, which you'll need to supply.
From delete.php return whether the delete succeeded or not. In the success even check for that data and handle it appropriately.
HTH.