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>\'; ?>';
Related
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.
I have like:
<script type="text/javascript">
$(document).ready(function() {
var n = $('<?php echo $_GET['name'];?>').val();
var e = $('<?php echo $_GET['email'];?>').val();
$.ajax({
method: "POST",
url: "file.php",
data: {name: n, email: e},
success: function(status) {
$('#result').append(status);
}
});
});
</script>
Why does it store empty values inside e and n?
And inside file.php when I echo em they are empty.
But here when I echo $_GET['name'] or email it show real values?
Thanks
you have a mistake in your code. you have to store that variable like below.
var n = '<?php echo $_GET['name'];?>';
var e = '<?php echo $_GET['email'];?>';
Why does it store empty values inside e and n?
My guess is that jQuery isn't finding the matching elements you're looking for. For example, if I go to your page with this:
page.php?name=David
Then that code will emit this:
var n = $('David').val();
That jQuery selector would be looking for this:
<David />
Which probably doesn't exist on that page. (With an email address it would be even stranger.)
If you want to store the values themselves in a JavaScript variable, you don't need any jQuery for that:
var n = '<?php echo $_GET['name'];?>';
If, on the other hand, the $_GET['name'] value is supposed to be the name of the HTML input and you want to use jQuery to find that input, it would be more like this:
var n = $('input[name=<?php echo $_GET['name'];?>]').val();
It's not entirely clear if that's what you're looking to do, though. Depends on what you expect $_GET['name'] to contain.
You can confirm all of this using the debugging tools in your browser. (Usually opened by pressing F12.) Examine the page source client-side (after the PHP code has been processed) to see what your JavaScript is actually doing, look at the jQuery selector(s) you're trying to build, debug the JavaScript to see if the target elements are found, etc.
I have following php:
$my_name = $my_site->getUserData("dfd_Name");
<?php echo $my_name?>
It outputs as following: Steve, Kim
I want to keep the format as it is. However there are times when I only need the first part (for example, "steve").
Is there a jquery way to remove everything after (including ",") the comma, so it will be "Steve" as the output.
EDIT
So, I am using the following php:
<a class="my_name_class" href="http://example.com/section1/section2/section3/<?php echo $my_name ?>" >
<?php echo esc_html($my_name) ; ?>
</a>
What would be the jQuery (or any other ways) to remove the second part (, kim) within the href?
In PHP,
<?php echo explode(',', $my_name)[0]?>
In jQuery,
First select that DOM part,
var thing = $('#anything').html();
and explode like,
var name = thing.split(',');
Your desired value,
name[0];
Place it in DOM like,
thing.html(name[0]);
Here is a quick solution in pure jQuery
HTML:
<span class="name">Steve, Kim</span>
JS:
$(function () {
$(".name").text($(".name").text().split(',')[0]);
});
To get the second part, change the above code to:
$(function () {
$(".name").text($(".name").text().split(',')[1]);
});
Include jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
https://jsfiddle.net/myLnnd0e/
Showing second name: https://jsfiddle.net/myLnnd0e/1/
Fixed for URL: https://jsfiddle.net/myLnnd0e/3/
Solution for URL:
HTML:
http://example.com/section1/section2/section3/
JS:
$(function () {
$(".name-url").attr("href", ($(".name-url").attr("href") + $(".name-url").data("names").split(',')[1].trim())).append($(".name-url").data("names").split(',')[1].trim());
});
While this is a completely valid use of Javascript, it is always best to provide users with an alternate way to access this data, for usability issues and also in the case that Javascript is disabled.
I am attempting to use AJAX to generate PHP to be displayed inside of a div based on the ID of the link clicked. (I haven't dealt with HTML formatting yet, just want to figure this out first)
My Code:
<script type="text/javascript">
jQuery(document).ready(function()
{
$(".myClass h3").click(function(){
var clickID = $(this).attr('id'); //For sake of argument lets say id = 1.
$.ajax({
url: 'landingPage.php',
data: {ProductIDNumber: clickID},
success: function(html) {
$('#container').append(html);
}
});
});
});
</script>
I have dealt with getting the PHP to run when the url is landingPage.php?ProductIDNumber=1 and that all works properly, I just don't quite grasp how to return the resultant HTML.
Edits made and commented on.
You need to include success, which is run once the response is received, similar to;
<script type="text/javascript">
jQuery(document).ready(function()
{
$(".myClass h3").click(function(){
var clickID = $(this).attr('id'); //For sake of argument lets say id = 1.
$.ajax({
url: 'landingPage.php',
data: {
ProductIDNumber : clickID
},
success: function(html) {
// Do what you need to here with 'html'
$('#container').append(html);
}
});
});
</script>
As Alvaro said the structure of the data was also incorrect
Here's a link to the jQuery docs where you can find out more about the parameters and options you have (such as handling fails etc)
the data is wrong,
it is like this:
data: {varname: value, varname1: value},
I can't get the following PHP + jQuery to work - all I want the script to do is pass the value through ajax, and get the php to grab it, check it matches and add 1 to score.
This is the code I've written:
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}else{
//Do nothing
}
echo $score;
?>
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
var value = "145";
alert(value);
$.ajax({
url: 'processing.php', //This is the current doc
type: "POST",
data: ({name: value}),
success: function(){
location.reload();
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
Thanks for the help, I've changed GET to POST in both instances, and no joy - there's something else wrong.
First of all: Do not go back to the dark ages... don't use the same script to generate HTML and to respond to an ajax request.
I can't make any sense of what you are trying to do... Let me change your code so it at least makes some sense and document what's going on. It seems like the problem is the fact that you are calling location.reload from your success handler.
// ajax.php - Outputs 2 if the name parameter is 145, 1 otherwise (????)
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}
echo $score;
?>
// test.html
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
// Why were you reloading the page? This is probably your bug
// location.reload();
// Replace the content of the clicked paragraph
// with the result from the ajax call
$("#raaagh").html(data);
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
You use POST in your jQuery, but you try and get a GET in you php.
BTW it is good practice to check if a GET/POST variable is set before reading it.
using the isset() function.
Replace $_GET with $_POST and there you are.
Basically POST and GET are two different way to pass variables to a script. The get method in php can also be attached at the end of a url : script.php?variable=value and it is really easy to hack. While the post method can be submitted with forms or ajax calls and it is pretty safe, at least more than the get.
Also i'd suggest you to check whatever a GET or POST variable is set before calling it, so that you can prevent stupid notice errors.
Just use the following code:
if (isset($_POST['var']) and !empty($_POST['var'])) { // do something }
You can also delete the
}else{
// do nothing
}
part of the script, since the else clause it is not necessary always.
You're submitting the data with an Ajax POST, but trying to read it out of a GET. Either use type: "GET" in your Ajax call or $_POST['name'] in your PHP.
The problem is you are using jQuery to POST your value, yet you are reading it with GET.
You should be able to fix your problem by changing your $_GET['name'] to $_POST['name']