How to use php value in jQuery function - php

I have a php file which uses a script within it.
I'm trying to get an image called by php (the_main_image) and prepend a set of links with this image (along with a favicon which is currently working fine) using jQuery. Here's what I have so far but it currently breaks the function
<script>
jQuery(document).ready(function($) {
$("#lesen").click(function() {
var bla = $('#my_hidden_input').val();
var test = "<?php the_main_image(); ?>";
$.ajax({
url: bla,
dataType: "text",
success: function(data) {
$(".text").html(data);
$(".text a[href^='http']").each(function() {
$(this).prepend(test);
$(this).prepend('<img src="https://www.google.com/s2/favicons?domain=' + this.href + '">');
});
}
});
});
});
</script>
How can I use jQuery var values that contain php within a prepend or other similar jQuery functions?

Hi I have done similar thing in my project, below worked for me.
Since you cannot write php directly in JavaScript, you need take help of your html.
Create a hidden input field in you html like below
<input type="hidden" id="something" value="<?php the_main_image(); ?>"/>
Then read this in jquery like
<script>
jQuery(document).ready(function($) {
$("#lesen").click(function() {
var bla = $('#my_hidden_input').val();
var test = $("#something").val();
$.ajax({
url: bla,
dataType: "text",
success: function(data) {
$(".text").html(data);
$(".text a[href^='http']").each(function() {
$(this).prepend(test);
$(this).prepend('<img src="https://www.google.com/s2/favicons?domain=' + this.href + '">');
});
}
});
});
});
</script>
hope this helps.

If your function in php does not echo result. Try to add echo. <?php echo the_main_image(); ?>. Seems like you forgot to echo result.
P.S. You can render results from php, even use it inside js code that placed in php files, but you should remember that mixin php with js is bad practice, and should be done cautiously.
How it works: php interpreter read your file before send static html to user and interpret all php related cod inside <?php ?>, if you echoing something it will appears in that row where you do this (or call function than do echoing). As mentioned by somebody if you echoing string with quotes it can break the js if you inline your php tags inside the same type of quotes.

Try to use ajax to get php value in jquery funcion.

Related

Insert link to a php page using jquery

I am planning to insert a link to my another php page using jquery function, but the code doesn't work... Alternative methods such as attr() has been tried as well, but it was still the same result... Can someone pls give me advices regarding this matter? Following are my codes:
$(document).ready(
function(){
$('#date').change(
function(){
$.ajax (
{
url: 'process.php',
type: 'post',
data: {
item_no:2,
movie_id: $('#movie').val(),
movie_date: $('#date').val()
},
dataType: 'json',
success: function(response){
$('#showtime').empty();
for(var i = 0; i<response.length; i++){
var showtime = response[i]['showtime'];
$('#showtime').append("<a href='movie_seat.php?id="+showtime+"' id='seatlink'>");
$('#showtime').append("<font style='margin-right:50px;'>");
$('#showtime').append(showtime);
$('#showtime').append("</font></a>");
} // for loop
} // function taking response
} // block in ajax
); //ajax
} // function inside change
); // select->date change
} // function inside ready
); // document.ready
*Note that #showtime is the id of a attribute
My expectations:
The value displayed should be able to work as a link that will direct the user to another php page. But apparently, it doesn't....
You need append all together, because if you append something like this:
$('#showtime').append("<a href='movie_seat.php?id="+showtime+"' id='seatlink'>");
$('#showtime').append("<font style='margin-right:50px;'>");
$('#showtime').append(showtime);
$('#showtime').append("</font></a>");
That way the tags will be closed, and you html will seems like this:
<font style="margin-right:50px;"></font>
showtime
So what you need to do is append all together, i mean tags inside tags, try this:
var link = "<a href='movie_seat.php?id="+showtime+"' id='seatlink'>"
+ "<font style='margin-right:50px;'>"
+ showtime
+ "</font></a>";
$('#showtime').append(link);

Why is AJAX only replacing my variable in some places?

I have the following AJAX code, which replaces anything with class "percentreplacer" with the data in the "Percent" column of the MYSQL database:
<script type='text/javascript'>
$(document).ready(function () {
$('#functionsquestionform2').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : "aplaygroundajaxtest.php",
type: "POST",
data: $(this).serialize(),
success: function (data) {
$(".percentreplace").text(data.percent);
},
});
});
});
</script>
In another part of my script, I have this snippet of PHP code:
<?php echo '<span class="percentreplace">'.$data['FunctionsPercent'].'</span>'; ?>
When I run the code, the AJAX code at the top successfully replaces the above span with the percent value stored in the database (such as "6").
Later on in my code, I try to set this percent as a variable with the JQuery script shown below:
<script type='text/javascript'>
$(function(){
var carouselbutton1percentage='<?php echo '<span class="percentreplace">'.$data['FunctionsPercent'].'</span>'; ?>' ....[cont'd]
Here, however, instead of replacing the entire PHP snippet with the percent (let's say 6), it sets the variable carouselbutton1percentage equal to <span class="percentreplace">6</span> I want the tags to get stripped here just like they did in the former. I'm guessing this has something to do with the quotes, but I've played around with it quite a bit and I can't figure out what to change.
Any help would be greatly appreciated!
Thanks
I might be missing something. But instead of storing a string 'that contains characters that look like PHP and jquery', I would think you want to actually update that html element, like you do in the AJAX response block. So..
$(".percentreplace").text('6');
or
var carouselbutton1percentage = 6;
$(".percentreplace").text(carouselbutton1percentage);
But again, maybe I'm misunderstanding.
I think you need to escape your string properly?
var carouselbutton1percentage='<?php echo \'<span class="percentreplace">\'.$data[\'FunctionsPercent\'].\'</span>\'‌​; ?>';

How can i pass a variable from js file to another using ajax jquery?

I have 2 js files and i want to pass 2 variables from file1.js to file2.js. What i have done until now is to send these 2 variables from file1.js in a 3rd file file3.php with ajax using this:
$('#replace').click(function(){
var replacement = cur;
var replacement2 = cur2;
$.ajax({
url: DOMAIN_NAME+"file3.php",
type: "post",
data: {replacement: replacement, replacement2 : replacement2},
success:function(data){
console.log(data);
},
error:function(){
alert('Something Went Wrong');
},
});
});
In my file3.php:
if(isset($_POST['replacement']) && isset($_POST['replacement2']){
$a = $_POST['replacement'];
$b = $_POST['replacement2'];
}
<input type="hidden" id="af" value="<?=$a;?>">
<input type="hidden" id="bf" value="<?=$b;?>">
In my File2.js:
var a = $('#af').val();
var b = $('#bf').val();
i can see that in the network the ajax passes the variable with a status 200 OK but in the php file my variables doesn't pass. So the file2.js can't get the values. What i am doing wrong??
Let's say you have this simple form:
<form id="my_form">
<input type="text" name="a_field" id="a_field">
<input type="text" name="b_field" id="b_field">
<button id="submit_form">Submit</button>
</form>
The jquery script file (#1) for this form can be named "script1.js" and can look like that:
$(document).ready(function(){
$('#submit_form').on('click').function(e){
e.preventDefault();
var formData = $('#my_form').serialize();
$.ajax({
type: 'POST',
url: 'my_ajax.php',
data: formData
});
});
});
Notice that I serialized the form to be quicker... (If you want you can specify which variables you want to pass to ajax)
Here is an example of my_ajax.php:
<?php
session_start();
if(isset($_SESSION["a_var"])){unset($_SESSION["a_var"]);}
if(isset($_SESSION["b_var"])){unset($_SESSION["b_var"]);}
if(isset($_POST["a_field"])){$a_field=htmlspecialchars($_POST["a_field"]);}else{$a_field=""; exit();}
if(isset($_POST["b_field"])){$b_field=htmlspecialchars($_POST["b_field"]);}else{$b_field=""; exit();}
$_SESSION["a_var"] = $a_field;
$_SESSION["b_var"] = $b_field;
?>
With the above file, we created two php sessions based to the input-field values that we acquired from our html form.
Now the "tricky" part:
Your SECOND js file (#2) must be given an extension .php and NOT .js
It will however execute any javascript code if of course that code is enclosed in "script" tags
Let's name that file "script2.js.php" -which can be like that:
<?php
session_start();
if(isset($_SESSION["a_var"])){$value_a = $_SESSION["a_var"];}else{$value_a="";}
if(isset($_SESSION["b_var"])){$value_b = $_SESSION["b_var"];}else{$value_b="";}
?>
<script>/*...include jquery here (if necessary)...*/</script>
<script>
$(document).ready(function(){
//jquery is NOT necessary for my example
//I just included it in case you need to do other tasks...
var valueA = '<?php echo $value_a; ?>';
var valueB = '<?php echo $value_b; ?>';
//Now you can do anything with these values... For example, you could alert them:
alert('Value A: '+valueA+' - Value B: '+valueB);
});
</script>
One last thing:
While to include a js file to your html page you do:
<script src="http://www.example.com/scripts/yourscript.js"></script>
To include the "js.php" file you must do it by using the php "include" function:
This is how I would suggest to pass variables from one js file to another by using php sessions!
My example is quite "basic" and could take a lot of "polishing" work regarding functionality and security... But should give you an idea as of how to start...
Hope that helps you and/or others...

.each() makes the page Freeze

The idea is to fetch the content from an external PHP file on Page load using jQuery .each() function. The problem is the page freezes or keeps on loading and never ends. What would be the issue?
PHP Page
<div class='caller-div-holder'>
<div class='calling-div' id='calling-div-1'></div>
<div class='calling-div' id='calling-div-2'></div>
<div class='calling-div' id='calling-div-3'></div>
</div>
In the .js file
$('.calling-div').each(function()
{
var fetch_id=$(this).attr('data-id');
$.ajax(
{
type: "POST",
url: "page-url",
data: {var1: fetch_id},
dataType:"html",
success: function(data)
{
$('#calling-div-'+fetch_id).html(data);
}
}); // Ajax
}); // Each function
Note:
Instead of $.ajax() on using document.write I found that the function is called for 3 times correctly with the variable fetch_id getting the data properly.
The external PHP page is checked with sample data just changing the POST to GET and passing the data through GET method. It works.
Edit 1:
Adding async:"false", reduces the problem intensity. But still the page is considerably slow.
The following will solve the issue by adding all the html at once, this will be faster than the other method...it will still lock the DOM at the end when it adds the html variable to the html of the parent element.
var html = '';
$('.calling-div').each(function()
{
var fetch_id=$(this).attr('data-id');
$.ajax(
{
type: "POST",
url: "page-url",
data: {var1: fetch_id},
dataType:"html",
success: function(data)
{
html += "<div class='calling-div' id='calling-div-" + fetch_id + "'>" + data + "</div>"
}
}); // Ajax
}); // Each function
$('.caller-div-holder').html(html);
Special Note I highly recommend using the following to solve this problem:
jQuery append() for multiple elements after for loop without flattening to HTML
http://jsperf.com/fn-append-apply

Trying to refresh div with jQuery in MVC f/w

Hi everyone I have been working on this particular problem for ages by now,plz help.
I have looked at jQuery: Refresh div after another jquery action?
and it does exactly what I want but only once! I have a table generated from db and when I click on delete it deletes the row and refreshes the div but after which none of my jquery functions will work.
$('#docs td.delete').click(function() {
$("#docs tr.itemDetail").hide();
var i = $(this).parent().attr('id');
$.ajax({
url: "<?php echo site_url('kt_docs/deleteDoc'); ?>",
type: 'POST',
data: 'id=' + i,
success: function(data) {
$("#docs tr.itemDetail").hide();
$("#f1").html(data); // wont work twice
//$("#docs").load(location.href+" #docs>*"); //works once as well
}
});
});
in my body I have
<fieldset class='step' id='f1'>
<?php $this->load->view('profile/docs_table'); ?>
</fieldset>
profile/docs reads data from db. <table id='docs'>....</table>
and my controller:
function deleteDoc() {
$id = $_POST['id'];
$this->load->model('documents_model');
$del = $this->documents_model->deleteDocument($id);
return $this->load->view('docs_table');
}
Thanks in advance!
Are you removing any expressions matching $('#docs td.delete') anywhere? If so, consider using $.live(), which will attach your function to ALL matching elements regardless of current or in the future; e.g.
$('#docs td.delete').live('click', function() {
// Do stuff.
});
http://api.jquery.com/live/
Try using bind() instead of click(). The click() method won't work on dynamically added elements to the DOM, which is probably why it only works the first time and not after you re-populate it with your updated content.
You should just have to replace
$('#docs td.delete').click(function() {
with
$('#docs td.delete').bind('click', function() {
Are you replacing the html elements that have the events on them with the data your getting through ajax? If you end up replacing the td.delete elements, then the new ones won't automatically get the binding.

Categories