I must to check the result of Ajax are same with some PHP variable value.
Is there anyway to do this?
Thank you in advance for help.
My Ajax HTML:
<?php
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
if($x == $y){
echo $x;
}
?>
<a id="input" href="#">Get value<input type="hidden" value="2_2_1_3"></a>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
jQuery(document).ready(function(){
$("#input").on("click", function(){
$.ajax({
type: 'POST',
url: "ip2.php",
data:'ip=' + $(this).parent().find('input').val(),
success: function(data){
$("#ip").html(data);
}
});
});
});
</script>
The PHP script:
<?php
if($_POST['ip'] >= 0){
$ip = $_POST['ip'];
echo $ip;
}
?>
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
if($x == $y){ // this will never be true because $x is diferent of $y
echo $x; //so you will never print this out
}
And you won't have the element with id="ip" to print the result from your ajax
success: function(data){
$("#ip").html(data);
}
For it to work try this:
<?php
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
echo $x;
?>
I'm not entirely sure what you want to do, but you can always send your post data as an object in javascript, for simplicity you can use the post function.
Example:
$.post( "ip2.php", { ip: $(this).parent().find('input').val() }, function( data ) {
console.log( data );
});
More info:
https://api.jquery.com/jquery.post/
https://api.jquery.com/jQuery.ajax/
Related
I get this weird error. It happens to be my PHP code that is embedded into jquery.
<?php $user=isset($_GET['u']) ? $_GET['u'] : NULL; //This returns a numeric value ?>
<script>
$("button[name='send_mail']").on('click',function(){
var user = '<?php echo $user;?>'; // <----The Problem
$.ajax({
type:"POST",
url:"ajax/scripts/user_mail.php?u="+user,
success: function(data){
alert(data);
},
});
});
</script>
I tried both, single and double quotes. This piece code happens to work in some of my files and doesn't work in others.
<?php
$user = (!empty($_GET['u']))?intval($_GET['u']):0;
?>
<script language="JavaScript">
console.log("User: " + <?php echo $user; ?>);
// try to debug what is really in the variable
var user = <?php echo $user; ?>;
// same as <?= $user; ?>
</script>
You have a rogue comma in this part of your code:
success: function(data){
alert(data);
}, //<--- here
});
It should be only:
success: function(data){
alert(data);
}
});
This works:
<?php $user=isset($_GET['u']) ? $_GET['u'] : NULL;?>
<span id="user_id_span" style="display:none;"><?php echo $user; ?></span>
<script>
var user = $('#user_id_span').text();
</script>
If your output is more than just a single string or number or single line, this would not work.
i'm creating a plugin for WooCommerce
in my plugin php file when i call a php file with jquery ajax i get empty result
this is my ajax code:
jQuery(function() {
jQuery.ajax({
url: '<?php echo RAKHSH_WC_QUICK_VIEW_URL ?>/rakhsh-data-for-pop.php',
success: function(output) {
alert(output);
}
});
});
and this is my php file:
<?php
$output = 'test';
return $output;
?>
You should change this:
<?php
$output = 'test';
return $output;
?>
To this:
<?php
$output = 'test';
die($output); // or echo or print
?>
Returning a variable will not return it as a response to an ajax call.
try this
<?php
$output = 'test';
echo $output;
?>
You can try this:
create a empty variable and insert your data to this.
var response = '';
$.ajax({ type: "GET",
url: '<?php echo RAKHSH_WC_QUICK_VIEW_URL ?>/rakhsh-data-for-pop.php',
async: false,
success : function(text)
{
response = text;
}
return response;
});
Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.
I am trying to call a PHP function using AJAX to check if the pressed button is the right button.
But I can't seem to figure it out.
I am using this as <input> code :
<?php
$i=0;
while ($i<4){
?>
<input style="background-color: <?php echo $buttonColors[$i]; ?>" onclick="echoHello(<?php echo $i?>)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php $i=$i+1; } ?>
and I'm trying to call a PHP function when the button is clicked. I tried this :
<script>
function echoHello()
{
alert("<?php hello(); ?>");
}
</script>
<?php
function hello() {
echo "Hello World";
}
?>
This worked so I tried to change this to :
<script>
function echoHello(num)
{
alert("<?php hello(num); ?>");
}
</script>
<?php
function hello($num) {
if($num == 1) {
echo "Correct button!!!";
} else {
echo "WRONG BUTTON";
}
?>
But this didn't seem to work. What am I doing wrong?
I think you have quite some thing mixed up here.
I would suggest just writing out the buttons, and pass the buttons value to the javascript:
<?php
$i=0;
while ($i<4){
?>
<input onclick="echoHello(this.value)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php
$i=$i+1;
} ?>
and then in your javascript (after adding all the jQuery goodness):
function echoHello(btnValue) {
$.ajax({
type: "POST",
url: "formhandler.php",
data: { buttonValue: btnValue }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
The javascript above will send the button value to your 'formhandler.php' page, using AJAX.
In the 'formhandler.php', you could then check what the value of $_POST["buttonValue"] is.
Using your setup, together with jQuery, PHP and JSON, it could be something like this:
function echoHello(btnValue) {
$.getJSON('page.php', {
choice: btnValue
})
.done(function(data) {
// based on $_GET["choice"], your PHP could render some JSON like:
// {"background":"image.jpg","fields":["newValue1", "newValue2", "newValue3"]}
// clear the current html
$("#form").html('');
// load a new background
$('body').css({'background-image':data.background})
// set up the new fields:
$.each(data.fields, function( i, item ) {
$("#form").append('<input type="text" value="' + item + '"/>');
});
});
}
This is just a sample, to give you an idea! It's untested also ;)
I can not successfully get the string using the jquery text()
I have my HTML
<span>/</span>
<span onclick="
var inner_text=$.trim($(this).text());
if(inner_text=='Send Request'){
var post_id=<?php echo $blog_id ;?>;
var event_date='<?php echo $blog_feeds['valid_date'] ?>';
var post_text='<?php echo addslashes($blog_feeds['post_text']) ?>'; //if the string contains ' , then would have error
var request_text_id='<?php echo $blog_id.'comment_text';?>';
var request_content=$('#'+request_text_id).val();
var who_post='<?php echo $blog_feeds['username'] ;?>';
$.ajax({
url:'php/join_request.php',
method:'post',
data:{request_content:request_content,post_id:post_id,who_post:who_post,event_date:event_date,post_text:post_text},
success:function(data){
if(data=='ok'){
$('<?php echo '#'.$blog_id.'request_w' ?>').html('You have sent '+who_post+' a joining reuqest on this event');
$('<?php echo '#'.$blog_id.'request_button'; ?>').html('Request Sent');
$('<?php echo '#'.$blog_id.'request_button'; ?>').css('opacity','0.7');
$('<?php echo '#'.$blog_id.'request_button'; ?>').css('cursor','initial');
$('<?php echo '#'.$blog_id.'comment_text';?>').val('');
}
}
})
}
" id="<?php echo $blog_id.'request_button'; ?>" class="j_request_button">
<?php
$select_request=mysql_query("SELECT `id` FROM `join_request` WHERE `post_id`='$blog_id' AND `who_request`='$username'");
if(mysql_num_rows($select_request)>=1){
echo '<span style="opacity:0.7;cursor:initial">Request Sent</span>';
}
else{
echo '<span style="cursor:pointer">Send Request</span>';
}
?>
</span>
if I add a alert(inner_text) right before if statement, I can successfully alert "sent request",but I can not alert ok within the if statement
Try:
var inner_text=$.trim($(this).text());
This will remove any surrounding whitespace, which is likely if you have line breaks between your spans.
Don't put a full script like that in your HTML. Give your span an id, and use jQuery in a separate script tag:
<span id="sent_request">sent request</span>
<script>
$('#sent_request').click(function(){
var inner_text=$(this).text();
if(inner_text=='sent request'){
alert('ok'); //not working
}
});
</script>