<input> calling a PHP function using AJAX - javascript

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 ;)

Related

Convert PHP variable to JQuery

Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery
View:
<?php
foreach ($muziek as $ms)
{
if ($ms->id == 2) {
echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
echo '</audio>';
}
}
foreach ($muziek as $ms)
{
echo '<br>';
echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
}
?>
</div>
<script>
$("input").click(function () {
var test = $(this).attr("id");
console.log(test);
//Here needs to be the foreach muziek
});
</script>
Muziek variable:
This is how i fill the music variable
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
return $muziek;
}
Does someone has an idea or show me how this can be done?
I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:
$.get( "base_url/your_controller/getAllMuziek" )
.done(function( muziek ) {
//Here needs to be the foreach muziek
$.each(muziek, function( index, value ) {
// whatever
});
});
with a simple modification to your method getAllMuziek:
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
header('Content-Type: application/json');
echo json_encode($muziek);
}
now when you make you ajax call you will get your result.
Convert $muziek into javascript array using json_encode
<script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>

Moving data from PHP then HTML then jQuery then back to PHP

working around with this code, but can not find what is wrong.
the following code is as follows:
$_POST from php filling attributes
<button class="final-buy-now-btn" type="submit"
book="<?php echo $_POST['book'];?>"
productId="<?php echo $thisProductId?>"
value="<?php echo $thisProductId ?>"
<?php if($book === 'christmas'){ echo "country=\"".$thiscountry."\" ";
echo "city=\"".$thiscity."\">";} ?>
<?php if($book === 'birthday'){ echo "bday=\"".$bday."\" ";
echo "month=\"".$month."\">";} ?>
<a>Buy Now</a>
</button>
after that i am calling final-buy-now-btn which i expect to be making the error, but i couldnt find it:
$('.final-buy-now-btn').click(function(event){
var book = $(this).attr("book");
var productId = $(this).attr("productId");
if( book === "christmas" ){
var country = $(this).attr("country");
var city = $(this).attr("city");
$.ajax({
type: 'POST',
url: '../../wp-admin/admin-ajax.php',
data: { 'action' : 'add_item_meta_data_to_cart_item',
'book' : book, 'productId' : productId,
'country' : country,'city' : city},
success: function (res) {
if (res) {
window.location = 'index.php/cart/';
}
}
})
}
if(book === "birthday"){
var month = $(this).attr("month");
var bday = $(this).attr("bday");
$.ajax({
type: 'POST',
url: '../../wp-admin/admin-ajax.php',
data: {
'action' : 'add_item_meta_data_to_cart_item',
'book' : book,'productId' : productId,
'month' : month,'bday' : bday},
success: function (res) {
if (res) {
window.location = 'index.php/cart/';
}
}
})
}
});
then finally from the action that is called, which is my php function,
for birthday the values are getting returned but for christmas nothing is getting returned.
function add_item_meta_data_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
$item_meta_data = filter_input( INPUT_POST, 'item_meta_data' );
$item_meta_data = json_decode($item_meta_data);
echo "<pre>";
print_r($item_meta_data);
echo "</pre>";
The short answer is that you have typo:
if( book === "chritmas" ){
You forgot letter s in JavaScript code
Other things
You should:
Using input type hidden instead of attributes or replace attributes to data-city, data-book
Remove attribute <a> in button
looking at your code, it doesn't appear that you are closing the button tag. try this snippet with the extra > after the month property.
<button class="final-buy-now-btn" type="submit"
book="<?php echo $_POST['book'];?>"
productId="<?php echo $thisProductId?>"
value="<?php echo $thisProductId ?>"
<?php if($book === 'christmas'){ echo "country=\"".$thiscountry."\" ";
echo "city=\"".$thiscity."\">";} ?>
<?php if($book === 'birthday'){ echo "bday=\"".$bday."\" ";
echo "month=\"".$month."\">";} ?>>
<a>Buy Now</a>
</button>
if its still not working, run the page through https://validator.w3.org/ to look at the html output and see if they are any other syntax errors.
as rafael mentioned: data-field is the best practice for naming properties in tags.

Update Table After User Click using button

I am doing a basic jQuery ajax call on a PHP file and I can't seem to figure it out, why it isn't working. Any help is appreciated.
jQuery
<script>
$(document).ready(function(){
$('#approve').click(function(e){
e.preventDefault();
var email=$("email_address").text();
changeTable(email);
});
return false
});
function changeTable(email){
$.ajax({type:"post",
url:"DB_Update.php",
data:{email:email},
success:function(response){
alert(response);
}
});
}
</script>
PHP
$email=$_POST['email'];
updateTableApproval($email);
public function updateTableApproval($email){
$query_string="UPDATE users SET approved = b'1' WHERE email='$email'";
$result=mysqli_query($this->db->connect(),$query_string);
return $result;
}
PHP MAIN
echo "<td id='email_address'>".$email."</td>";
echo "<td id='approve'>"."<input type='radio' ".($row['approved']==1?'checked':'unchecked').">"."</td>;";
You are not returning data back from php function. Change one of this.
updateTableApproval($email); to echo updateTableApproval($email);
OR
return $result; to echo $result;

JQuery AJax Result Echo PHP

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/

AJAX- getting a specific array value in post

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.

Categories