Jump to content
aveeva

PHP - Ajax Passing value to another php file

Recommended Posts

Posted (edited)

Here is my PHP, i want to share voice_id and voice_name to another php file using ajax,

 

 

<?php



//fetch_data.php

include('database_connection.php');

if(isset($_POST["action"]))
{
	$query = "
		SELECT * FROM voice_bank_data WHERE voice_status = '1'
	";

	// if(isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"]))
	// {
	// 	$query .= "
	// 	 AND product_price BETWEEN '".$_POST["minimum_price"]."' AND '".$_POST["maximum_price"]."'
	// 	";
	// }

	// Gender
	if(isset($_POST["gender"]))
	{
		$gender_filter = implode("','", $_POST["gender"]);
		$query .= "
		 AND voice_gender IN('".$gender_filter."')
		";
	}

	// Genres
	if(isset($_POST["genres"]))
	{
		$genres_filter = implode("','", $_POST["genres"]);
		$query .= "
		 AND voice_genres IN('".$genres_filter."')
		";
	}

	// Voice Modulation
	if(isset($_POST["voice_modulation"]))
	{
		$voice_modulation_filter = implode("','", $_POST["voice_modulation"]);
		$query .= "
		 AND voice_voice_modulation IN('".$voice_modulation_filter."')
		";
	}


	// Languages
	if(isset($_POST["languages"]))
	{
		$languages_filter = implode("','", $_POST["languages"]);
		$query .= "
		 AND voice_languages IN('".$languages_filter."')
		";
	}

	// Jingle Moods
	if(isset($_POST["jingle_moods"]))
	{
		$jingle_moods_filter = implode("','", $_POST["jingle_moods"]);
		$query .= "
		 AND voice_jingle_moods IN('".$jingle_moods_filter."')
		";
	}

	// IVR
	if(isset($_POST["ivr"]))
	{
		$ivr_filter = implode("','", $_POST["ivr"]);
		$query .= "
		 AND voice_ivr IN('".$ivr_filter."')
		";
	}

	$statement = $connect->prepare($query);
	$statement->execute();
	$result = $statement->fetchAll();
	$total_row = $statement->rowCount();
	$output = '';
	if($total_row > 0)
	{
		foreach($result as $row)
		{
			$output .= '
			<div class="col-sm-3 col-lg-4 col-md-3">
				<div style="border:1px solid #ccc; border-radius:5px; padding:10px; margin-bottom:16px; height:300px;">
					<audio controls controlsList="nodownload" style="padding: 10px 10px 10px 10px;margin-left: -21px;">
						<source src="audio_sample/'. $row['voice_audio_file'] .'" alt="" class="img-responsive">
					</audio>
					<p align="center"><strong> '. $row['voice_name'] .'</strong></p>

					<p style="font-size: 12px;">
					Id		      : '. $row['voice_id'].' <br />
					Name		      : '. $row['voice_name'].' <br />
					Gender		      : '. $row['voice_gender'].' <br />
					Genres 			  : '. $row['voice_genres'].' <br />
					Voice Modulation  : '. $row['voice_voice_modulation'].' <br />
					Languages		  : '. $row['voice_languages'].' <br />
					Jingle Moods	  : '. $row['voice_jingle_moods'].' <br />
					Ivr 			  : '. $row['voice_ivr'].' <br /> </p>
					<button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;">Add to PlayList </button>


				</div>

			</div>
			';
		} 
	}
	else 
	{
		$output = '<h3>No Data Found</h3>';
	}
	echo $output;
}
?>

<script>

	$('.button').on('click',function() {
		var voice_id 	= $("#voice_id").val();
		var voice_name  = $("#voice_name").val();

		$.ajax({
			type 	 : "POST",
			url  	 : "my_cart.php",
			datatype : "text",
			data	 : {voice_id: voice_id, voice_name: voice_name },
			success: function(data)
			{
				console.log(data);
				// console.log('success',data);
				
			}
		});
	});

</script>

Not shared the details,

Edited by aveeva

Share this post


Link to post
Share on other sites

If you're not seeing the results you expect in console. I use postman for troubleshooting. You can put in the URL and the post data in json format, and run it to see what the result actually is. You could have an error in my_cart.php. You could be outputting something along with your json. Your json may not be formatted properly. I would add this 

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

to the beginning of my_cart.php and either view the results in development tools or download postman and try it that way. 

  • Like 1

Share this post


Link to post
Share on other sites
13 minutes ago, Barand said:

And your problem is ... ?

Not shared with my_cart.php file, 

my my_cart.php file is,

<?PHP
// Get details from fetch_data.php
 
if(isset($_POST['voice_id']) && isset($_POST['voice_name']))
{
$voice_id = $_POST['voice_id'];
$voice_name = $_POST['voice_name'];
}
 
echo "$voice_id & $voice_name";
 
?>

Share this post


Link to post
Share on other sites
Posted (edited)

On closer examination, your button script is expecting HTML elements with ids of "voice_id" and "voice_name" with values.

  1. You don't have any such elements
  2. ids must be unique and you will have several buttons and voice_ids.

i would add hidden fields to hold the names and ids

<input type="hidden" name="voice_id" value="{$row[voice_id]}"   class="voice_id" data-id="{$row[voice_id]}">
                    <input type="hidden" name="voice_name" value="{$row[voice_name]}"   class="voice_name" data-id="{$row[voice_id]}">
                    <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="{$row[voice_id]}">Add to PlayList </button>

Note the hidden fields and button all share the same data-id values.

The use those data-id values to get the voces associated with buttons

$('.btn').on('click',function() {
        var vid = $(this).data("id")
        var voice_id     = $(".voice_id[data-id="+vid+"]").val();
        var voice_name  = $(".voice_name[data-id="+vid+"]").val();

        $.ajax({
            type      : "POST",
            url       : "my_cart.php",
            datatype : "text",
            data     : {voice_id: voice_id, voice_name: voice_name },
            success: function(data)
            {
                console.log(data);
                // console.log('success',data);
                
            }
        });
    });

 

Edited by Barand

Share this post


Link to post
Share on other sites
8 minutes ago, Barand said:

On closer examination, your button script is expecting HTML elements with ids of "voice_id" and "voice_name" with values.

  1. You don't have any such elements
  2. ids must be unique and you will have several buttons and voice_ids.

i would add hidden fields to hold the names and ids


<input type="hidden" name="voice_id" value="{$row[voice_id]}"   class="voice_id" data-id="{$row[voice_id]}">
                    <input type="hidden" name="voice_name" value="{$row[voice_name]}"   class="voice_name" data-id="{$row[voice_id]}">
                    <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="{$row[voice_id]}">Add to PlayList </button>

Note the hidden fields and button all share the same data-id values.

The use those data-id values to get the voces associated with buttons


$('.btn').on('click',function() {
        var vid = $(this).data("id")
        var voice_id     = $(".voice_id[data-id="+vid+"]").val();
        var voice_name  = $(".voice_name[data-id="+vid+"]").val();

        $.ajax({
            type      : "POST",
            url       : "my_cart.php",
            datatype : "text",
            data     : {voice_id: voice_id, voice_name: voice_name },
            success: function(data)
            {
                console.log(data);
                // console.log('success',data);
                
            }
        });
    });

 

 

 

I really appreciate with code help,

 

Actually, i did mistake in my code

 

Now i correct,

<script>

	$('.btn').on('click',function() {
		var voice_id 	= $("#voice_id");
		var voice_name  = $("#voice_name");

		$.ajax({
			type 	 : "POST",
			url  	 : "my_cart.php",
			datatype : "text",
			// data	 : {voice_id: voice_id, voice_name: voice_name },
			data: "voice_id="+voice_id+"&voice_name="+voice_name,


			success: function(data)
			{
				console.log(data);
				// console.log('success',data);
				
			}
		});
	});

</script>

 

finally ,my output 

 

rYQOgn.jpg

sorry to confusing...

Share this post


Link to post
Share on other sites

On further thought you could forget my hidden inputs and just put the two values in the button as "data-id" and "data-name".

Then, in the click function

var voice_id = $(this).data("id")
var voice_name  = $(this).data("name")

 

  • Thanks 1

Share this post


Link to post
Share on other sites
Posted (edited)

@Barand   Here is my my_cart.php,

<?PHP
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Get details from fetch_data.php
$voice_id = '';
$voice_name = '';
if(isset($_POST['voice_id']) && isset($_POST['voice_name']))
{
    $voice_id   = $_POST['voice_id'];
    $voice_name = $_POST['voice_name'];
}

    echo "$voice_id & $voice_name";

?>

 

My output :

tObmMZ.jpg

 

 

if i click add to playlist button the values not reflect on my_cart.php. I just want if i click add to playlist button the each value display on my my_cart.php page like,

1    1_tamil_voice.mp3

2    3_tamil_voice.mp3

3    3_tamil_voice.mp3

 

Like add-to-cart function. 

Edited by aveeva

Share this post


Link to post
Share on other sites

Use the developer tools in your browser (network tab) and check the ajax message and response.

Have you changed the html in your form so you now have voice_id and voice_name values?

Share this post


Link to post
Share on other sites
Posted (edited)

@Barand Here is my inspect element,

 

DHQTZ6.jpg

 

and my my_cart.php

 

<?PHP

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Get details from fetch_data.php

$voice_id = '';
$voice_name = '';

if(isset($_POST['voice_id']) && isset($_POST['voice_name']))
{
    $voice_id   = $_POST['voice_id'];
    $voice_name = $_POST['voice_name'];
}
    echo "$voice_id & $voice_name";

?>

 

How to make display  like:

bWsU6z.jpg

Edited by aveeva

Share this post


Link to post
Share on other sites

my_cart.php will not display anything to the user.

When you use ajax, all output is sent back to the calling ajax function in the ajax response. In your case it will be in the "data" argument

success: function(data)                    // <-- output from "my_cart.php" is in "data"
    {
        console.log(data);               
        // console.log('success',data);
        
    }

Note that these are processed one at a time as you click each button. If you want to list multiple items then you would add them to a list on the calling page, not in my_cart.php. Alternatively you could store them with my_cart.php (maybe in a "playlist" table in a database) and list them in another page.

If the list needs to be persistent, store them.

Share this post


Link to post
Share on other sites

Yes.

Here's a simplified version of your application as an example

FORM CODE

<?php
   //
   // FOR DEBUG PURPOSES ONLY - LIST CONTENTS OF SESSION PLAYLIST
   //
   session_start();
   if (isset($_SESSION['playlist'])) {
       echo '<pre>', print_r($_SESSION['playlist'], 1), '</pre>';
       echo "</hr><br>\n";
   }
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$().ready( function() {

    $(".btn").click( function() {
        var vid = $(this).data("id");
        var vname = $(this).data("name");
        
        $.post(
            "my_cart.php",
            { "voice_id" : vid, "voice_name" : vname},
            function(resp) {
                var list = "<tr><td><b>ID</b></td><td><b>Title</b></td></tr>\n";
                $.each(resp, function(k, v) {
                    list = list + "<tr><td>" + k + "</td><td>" + v + "</td></tr>\n"
                })
                $("#playlist").html(list)
            },
            "JSON"
        )
    })
})
</script>
</head>
<body>
    Song 1 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="1" data-name="song-1.mp3">Add to PlayList </button> <br>
    Song 2 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="2" data-name="song-2.mp3">Add to PlayList </button> <br>
    Song 3 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="3" data-name="song-3.mp3">Add to PlayList </button> <br>
    Song 4 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="4" data-name="song-4.mp3">Add to PlayList </button> <br>
    Song 5 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="5" data-name="song-5.mp3">Add to PlayList </button> <br>
    Song 6 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="6" data-name="song-6.mp3">Add to PlayList </button> <br>
    <br>
    <h2>Playlist</h2>
    <table style="width:600px" id="playlist">
    
    </table>
</body>
</html>

MY_CART.PHP

<?php
session_start();

if ($_SERVER['REQUEST_METHOD']=='POST') {
    $voice_id = $_POST['voice_id'] ?? 0;
    $voice_name = $_POST['voice_name'] ?? '';
    
    if ($voice_id && $voice_name) {
        $_SESSION['playlist'][$voice_id] = $voice_name;
        exit(json_encode($_SESSION['playlist'])) ;
    }
}
exit("ERROR")  ; 
?>

 

  • Great Answer 1

Share this post


Link to post
Share on other sites

@Barand Yes,  actually i am getting error, i don't want keep you disturb, that's what post to other forum,

 

code: 

 

			$output .= '
			<div class="col-sm-3 col-lg-4 col-md-3">
				<div style="border:1px solid #ccc; border-radius:5px; padding:10px; margin-bottom:16px; height:300px;">
					<audio controls controlsList="nodownload" style="padding: 10px 10px 10px 10px;margin-left: -21px;">
						<source src="audio_sample/'. $row['voice_audio_file'] .'" alt="" class="img-responsive">
					</audio>
					<p align="center"><strong> '. $row['voice_name'] .'</strong></p>

					<p style="font-size: 12px;">
					Voice Sku		  : '. $row['voice_sku'].' <br />	
					voice Name        :	'. $row['voice_name'].' <br />
					Gender		      : '. $row['voice_gender'].' <br />
					Genres 			  : '. $row['voice_genres'].' <br />
					Voice Modulation  : '. $row['voice_voice_modulation'].' <br />
					Languages		  : '. $row['voice_languages'].' <br />
					Jingle Moods	  : '. $row['voice_jingle_moods'].' <br />
					Ivr 			  : '. $row['voice_ivr'].' <br /> </p>
	
					<button type="button" class="btn btn-primary" style="padding: 5px 83px 5px 83px;" data-voice-sku="'.$row["voice_sku"].'" data-voice-name="'.$row["voice_name"].'">Add to Playlist</button>

				</div>

			</div>
			';
		} 
	}
	else 
	{
		$output = '<h3>No Data Found</h3>';
	}
	echo $output;
}
?>
<script type="text/javascript">

$().ready( function() {

$(".btn").click( function() {
	var voice_sku = $(this).data("voice_sku");
	var voice_name = $(this).data("voice_name");
	
	$.post(
		"my_cart.php",
		{ "voice_sku" : voice_sku, "voice_name" : voice_name},
		function(resp) {
			var list = "<tr><td><b>ID</b></td><td><b>Title</b></td></tr>\n";
			$.each(resp, function(k, v) {
				list = list + "<tr><td>" + k + "</td><td>" + v + "</td></tr>\n"
			})
			$("#playlist").html(list)
		},
		"JSON"
	);
});
});

</script>

 

my_cart.php:

<?php
session_start();

if ($_SERVER['REQUEST_METHOD']=='POST') {
    $voice_sku = $_POST['voice_sku'] ?? 0;
    $voice_name = $_POST['voice_name'] ?? '';
    
    if ($voice_sku && $voice_name) {
        $_SESSION['playlist'][$voice_sku] = $voice_name;
        exit(json_encode($_SESSION['playlist'])) ;
    }
}
exit("ERROR")  ; 
?>

 

screenshot :

CPFXWJ.jpg

 

 

 

Share this post


Link to post
Share on other sites
Posted (edited)

@Barand I just try, i am new to PHP, if i did any stupid things, make me a pardon,

Edited by aveeva

Share this post


Link to post
Share on other sites
Posted (edited)

FYI -> Neglect last reply,

 here is my complete code :

fetch_data.php

<?php
session_start();
if (isset($_SESSION['playlist'])) {
	echo '<pre>', print_r($_SESSION['playlist'], 1), '</pre>';
	echo "</hr><br>\n";
}


//fetch_data.php

include('database_connection.php');



if(isset($_POST["action"]))
{
	$query = "
		SELECT * FROM voice_bank_data WHERE voice_status = '1'
	";

	// if(isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"]))
	// {
	// 	$query .= "
	// 	 AND product_price BETWEEN '".$_POST["minimum_price"]."' AND '".$_POST["maximum_price"]."'
	// 	";
	// }

	// Gender
	if(isset($_POST["gender"]))
	{
		$gender_filter = implode("','", $_POST["gender"]);
		$query .= "
		 AND voice_gender IN('".$gender_filter."')
		";
	}

	// Genres
	if(isset($_POST["genres"]))
	{
		$genres_filter = implode("','", $_POST["genres"]);
		$query .= "
		 AND voice_genres IN('".$genres_filter."')
		";
	}

	// Voice Modulation
	if(isset($_POST["voice_modulation"]))
	{
		$voice_modulation_filter = implode("','", $_POST["voice_modulation"]);
		$query .= "
		 AND voice_voice_modulation IN('".$voice_modulation_filter."')
		";
	}


	// Languages
	if(isset($_POST["languages"]))
	{
		$languages_filter = implode("','", $_POST["languages"]);
		$query .= "
		 AND voice_languages IN('".$languages_filter."')
		";
	}

	// Jingle Moods
	if(isset($_POST["jingle_moods"]))
	{
		$jingle_moods_filter = implode("','", $_POST["jingle_moods"]);
		$query .= "
		 AND voice_jingle_moods IN('".$jingle_moods_filter."')
		";
	}

	// IVR
	if(isset($_POST["ivr"]))
	{
		$ivr_filter = implode("','", $_POST["ivr"]);
		$query .= "
		 AND voice_ivr IN('".$ivr_filter."')
		";
	}

	$statement = $connect->prepare($query);
	$statement->execute();
	$result = $statement->fetchAll();
	$total_row = $statement->rowCount();
	$output = '';
	if($total_row > 0)
	{
		foreach($result as $row)
		{
			$output .= '
			<div class="col-sm-3 col-lg-4 col-md-3">
				<div style="border:1px solid #ccc; border-radius:5px; padding:10px; margin-bottom:16px; height:300px;">
					<audio controls controlsList="nodownload" style="padding: 10px 10px 10px 10px;margin-left: -21px;">
						<source src="audio_sample/'. $row['voice_audio_file'] .'" alt="" class="img-responsive">
					</audio>
					<p align="center"><strong> '. $row['voice_name'] .'</strong></p>

					<p style="font-size: 12px;">
					Voice Sku		  : '. $row['voice_sku'].' <br />	
					voice Name        :	'. $row['voice_name'].' <br />
					Gender		      : '. $row['voice_gender'].' <br />
					Genres 			  : '. $row['voice_genres'].' <br />
					Voice Modulation  : '. $row['voice_voice_modulation'].' <br />
					Languages		  : '. $row['voice_languages'].' <br />
					Jingle Moods	  : '. $row['voice_jingle_moods'].' <br />
					Ivr 			  : '. $row['voice_ivr'].' <br /> </p>
	

					<button type="button" class="btn btn-primary" style="padding: 5px 83px 5px 83px;" data-voice-sku="'.$row["voice_sku"].'" data-voice-name="'.$row["voice_name"].'">Add to Playlist</button>


				</div>

			</div>
			';
		} 
	}
	else 
	{
		$output = '<h3>No Data Found</h3>';
	}
	echo $output;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$().ready( function() {

    $(".btn").click( function() {
        var vid = $(this).data("id");
        var vname = $(this).data("name");
        
        $.post(
            "my_cart.php",
            { "voice_id" : vid, "voice_name" : vname},
            function(resp) {
                var list = "<tr><td><b>ID</b></td><td><b>Title</b></td></tr>\n";
                $.each(resp, function(k, v) {
                    list = list + "<tr><td>" + k + "</td><td>" + v + "</td></tr>\n"
                })
                $("#playlist").html(list)
            },
            "JSON"
        )
    })
})
</script>
</head>
<body>
    Song 1 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="1" data-name="song-1.mp3">Add to PlayList </button> <br>
    Song 2 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="2" data-name="song-2.mp3">Add to PlayList </button> <br>
    Song 3 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="3" data-name="song-3.mp3">Add to PlayList </button> <br>
    Song 4 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="4" data-name="song-4.mp3">Add to PlayList </button> <br>
    Song 5 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="5" data-name="song-5.mp3">Add to PlayList </button> <br>
    Song 6 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="6" data-name="song-6.mp3">Add to PlayList </button> <br>
    <br>
    <h2>Playlist</h2>
    <table style="width:600px" id="playlist">
    
    </table>
</body>
</html>

My_cart.php

 

<?php
session_start();

if ($_SERVER['REQUEST_METHOD']=='POST') {
    $voice_id = $_POST['voice_id'] ?? 0;
    $voice_name = $_POST['voice_name'] ?? '';
    
    if ($voice_id && $voice_name) {
        $_SESSION['playlist'][$voice_id] = $voice_name;
        exit(json_encode($_SESSION['playlist'])) ;
    }
}
exit("ERROR")  ; 
?>

 

output is ERROR.

 

 

 

Edited by aveeva

Share this post


Link to post
Share on other sites

How can i use my 

			$output .= '
			<div class="col-sm-3 col-lg-4 col-md-3">
				<div style="border:1px solid #ccc; border-radius:5px; padding:10px; margin-bottom:16px; height:300px;">
					<audio controls controlsList="nodownload" style="padding: 10px 10px 10px 10px;margin-left: -21px;">
						<source src="audio_sample/'. $row['voice_audio_file'] .'" alt="" class="img-responsive">
					</audio>
					<p align="center"><strong> '. $row['voice_name'] .'</strong></p>

					<p style="font-size: 12px;">
					Voice Sku		  : '. $row['voice_sku'].' <br />	
					voice Name        :	'. $row['voice_name'].' <br />
					Gender		      : '. $row['voice_gender'].' <br />
					Genres 			  : '. $row['voice_genres'].' <br />
					Voice Modulation  : '. $row['voice_voice_modulation'].' <br />
					Languages		  : '. $row['voice_languages'].' <br />
					Jingle Moods	  : '. $row['voice_jingle_moods'].' <br />
					Ivr 			  : '. $row['voice_ivr'].' <br /> </p>
	

					<button type="button" class="btn btn-primary" style="padding: 5px 83px 5px 83px;" data-voice-sku="'.$row["voice_sku"].'" data-voice-name="'.$row["voice_name"].'">Add to Playlist</button>


				</div>

			</div>
			';

instead of,

<body>
    Song 1 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="1" data-name="song-1.mp3">Add to PlayList </button> <br>
    Song 2 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="2" data-name="song-2.mp3">Add to PlayList </button> <br>
    Song 3 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="3" data-name="song-3.mp3">Add to PlayList </button> <br>
    Song 4 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="4" data-name="song-4.mp3">Add to PlayList </button> <br>
    Song 5 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="5" data-name="song-5.mp3">Add to PlayList </button> <br>
    Song 6 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="6" data-name="song-6.mp3">Add to PlayList </button> <br>
    <br>
    <h2>Playlist</h2>
    <table style="width:600px" id="playlist">
    
    </table>
</body>

 

Share this post


Link to post
Share on other sites

*Finally done,  sorry for lots of reply, i can't able to delete.

Share this post


Link to post
Share on other sites

I have modofied my original example to include "Delete" buttons in the playlist. At some point you will need to commit the playlist stored in the session to permanant storage.

Selection page...

<?php
   //
   // FOR DEBUG PURPOSES ONLY - LIST CONTENTS OF SESSION PLAYLIST
   //
   session_start();
   if (isset($_SESSION['playlist'])) {
       echo '<pre>', print_r($_SESSION['playlist'], 1), '</pre>';
       echo "</hr><br>\n";
   }
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$().ready( function() {

    $(".btn").click( function() {
        var vid = $(this).data("id");
        var vname = $(this).data("name");
        
        $.post(
            "my_cart.php",
            { "voice_id" : vid, "voice_name" : vname, "action" : "Add" },
            function(resp) {
                outputPlaylist(resp)
            },
            "JSON"
        )
    })
    
    
    function outputPlaylist(resp) {
        var list = "<tr><td><b>ID</b></td><td><b>Title</b></td></tr>\n";
        $.each(resp, function(k, v) {
            list = list + "<tr><td>" + k + "</td><td>" + v + "</td>"
            list = list + "<td><button class='delbtn' data-id='"+ k +"'>Delete</button></td></tr>\n"     // add "Delete" button to each playlist item
        })
        $("#playlist").html(list)
        
        // define action for new delbtn's
        $(".delbtn").click( function() {
            var vid = $(this).data("id");
            
            $.post(
                "my_cart.php",
                { "voice_id" : vid, "action" : "Delete"},
                function(resp) {
                    outputPlaylist(resp)
                },
                "JSON"
            )
        })
    }
})
</script>
</head>
<body>
    Song 1 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="1" data-name="song-1.mp3">Add to PlayList </button> <br>
    Song 2 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="2" data-name="song-2.mp3">Add to PlayList </button> <br>
    Song 3 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="3" data-name="song-3.mp3">Add to PlayList </button> <br>
    Song 4 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="4" data-name="song-4.mp3">Add to PlayList </button> <br>
    Song 5 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="5" data-name="song-5.mp3">Add to PlayList </button> <br>
    Song 6 <button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-id="6" data-name="song-6.mp3">Add to PlayList </button> <br>
    <br>
    <h2>Playlist</h2>
    <table style="width:600px" id="playlist">
    
    </table>
</body>
</html>

my_cart.php (handles ajax requests)...

<?php
session_start();

if ($_SERVER['REQUEST_METHOD']=='POST') {
    
    $voice_id = $_POST['voice_id'] ?? 0;
    $action = $_POST['action'] ?? '';
    
    if ($action == 'Delete')  {
        // we are deleting the item from the session array
        if ($voice_id) {
            unset($_SESSION['playlist'][$voice_id]);
            exit(json_encode($_SESSION['playlist'])) ;
        }
    }
    elseif ($action == 'Add')  {
        // we are adding the item
        $voice_name = $_POST['voice_name'] ?? '';
        
        if ($voice_id && $voice_name) {
            $_SESSION['playlist'][$voice_id] = $voice_name;
            exit(json_encode($_SESSION['playlist'])) ;
        }
    }
    else {
        exit("ERROR")  ; 
    }
}
exit("ERROR")  ; 
?>

 

Share this post


Link to post
Share on other sites
Posted (edited)

@Barand      FYI -> here i changed my_cart.php to manage_cart.php & voice_id to voice_sku

 

Main PHP file,

 

<?php

session_start();
if (isset($_SESSION['playlist'])) {
	echo '<pre>', print_r($_SESSION['playlist'], 1), '</pre>';
	echo "</hr><br>\n";
}


include('database_connection.php');


// start Custom filter

if(isset($_POST["action"]))
{
	$query = "
		SELECT * FROM voice_bank_data WHERE voice_status = '1'
	";


	// Gender
	if(isset($_POST["gender"]))
	{
		$gender_filter = implode("','", $_POST["gender"]);
		$query .= "
		 AND voice_gender IN('".$gender_filter."')
		";
	}

	// Genres
	if(isset($_POST["genres"]))
	{
		$genres_filter = implode("','", $_POST["genres"]);
		$query .= "
		 AND voice_genres IN('".$genres_filter."')
		";
	}

	// Voice Modulation
	if(isset($_POST["voice_modulation"]))
	{
		$voice_modulation_filter = implode("','", $_POST["voice_modulation"]);
		$query .= "
		 AND voice_voice_modulation IN('".$voice_modulation_filter."')
		";
	}


	// Languages
	if(isset($_POST["languages"]))
	{
		$languages_filter = implode("','", $_POST["languages"]);
		$query .= "
		 AND voice_languages IN('".$languages_filter."')
		";
	}

	// Jingle Moods
	if(isset($_POST["jingle_moods"]))
	{
		$jingle_moods_filter = implode("','", $_POST["jingle_moods"]);
		$query .= "
		 AND voice_jingle_moods IN('".$jingle_moods_filter."')
		";
	}

	// IVR
	if(isset($_POST["ivr"]))
	{
		$ivr_filter = implode("','", $_POST["ivr"]);
		$query .= "
		 AND voice_ivr IN('".$ivr_filter."')
		";
	}

// end Custom filter

	$statement = $connect->prepare($query);
	$statement->execute();
	$result = $statement->fetchAll();
	$total_row = $statement->rowCount();
	$output = '';
	if($total_row > 0)
	{
		foreach($result as $row)
		{
			$output .= '
			<div class="col-sm-3 col-lg-4 col-md-3">
				<div style="border:1px solid #ccc; border-radius:5px; padding:10px; margin-bottom:16px; height:300px;">
					<audio controls controlsList="nodownload" style="padding: 10px 10px 10px 10px;margin-left: -21px;">
						<source src="audio_sample/'. $row['voice_audio_file'] .'" alt="" class="img-responsive">
					</audio>
					<p align="center"><strong> '. $row['voice_name'] .'</strong></p>

					<p style="font-size: 12px;">
					Voice Sku		  : '. $row['voice_sku'].' <br />	
					voice Name        :	'. $row['voice_name'].' <br />
					Gender		      : '. $row['voice_gender'].' <br />
					Genres 			  : '. $row['voice_genres'].' <br />
					Voice Modulation  : '. $row['voice_voice_modulation'].' <br />
					Languages		  : '. $row['voice_languages'].' <br />
					Jingle Moods	  : '. $row['voice_jingle_moods'].' <br />
					Ivr 			  : '. $row['voice_ivr'].' <br /> </p>
	

					<button type="button" class="btn btn-primary" type="submit" style="padding: 5px 83px 5px 83px;" data-voice_sku="'.$row["voice_sku"].'" data-voice_name="'.$row["voice_name"].'">Add to Playlist</button>

				</div>

			</div>
			';
		} 
	}
	else 
	{
		$output = '<h3>No Data Found</h3>';
	}
	echo $output;
}
?>

<html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$().ready( function() {

    $(".btn").click( function() {
        var vid = $(this).data("sku");
        var vname = $(this).data("name");
        
        $.post(
            "manage_cart.php",
            { "voice_sku" : vid, "voice_name" : vname, "action" : "Add" },
            function(resp) {
                outputPlaylist(resp)
            },
            "JSON"
        )
    })
    
    function outputPlaylist(resp) {
        var list = "<tr><td><b>ID</b></td><td><b>Title</b></td></tr>\n";
        $.each(resp, function(k, v) {
            list = list + "<tr><td>" + k + "</td><td>" + v + "</td>"
            list = list + "<td><button class='delbtn' data-id='"+ k +"'>Delete</button></td></tr>\n"     // add "Delete" button to each playlist item
        })
        $("#playlist").html(list)
        
        // define action for new delbtn's
        $(".delbtn").click( function() {
            var vid = $(this).data("sku");
            
            $.post(
                "manage_cart.php",
                { "voice_sku" : vid, "action" : "Delete"},
                function(resp) {
                    outputPlaylist(resp)
                },
                "JSON"
            )
        })
    }
})
</script>
</head>
<body>

		<h2>Playlists...</h2>
		
    	<table style="width:600px" id="playlist">

	
		</table>

</body>
</html>

 

 

manage_cart.php (prior - my_cart.php)

<?php
session_start();

if ($_SERVER['REQUEST_METHOD']=='POST') {
    
    $voice_sku = $_POST['$voice_sku'] ?? 0;
    $action = $_POST['action'] ?? '';
    
    if ($action == 'Delete')  {
        // we are deleting the item from the session array
        if ($voice_sku) {
            unset($_SESSION['playlist'][$voice_sku]);
            exit(json_encode($_SESSION['playlist'])) ;
        }
    }
    elseif ($action == 'Add')  {
        // we are adding the item
        $voice_name = $_POST['voice_name'] ?? '';
        
        if ($voice_sku && $voice_name) {
            $_SESSION['playlist'][$voice_sku] = $voice_name;
            exit(json_encode($_SESSION['playlist'])) ;
        }
    }
    else {
        exit("ERROR")  ; 
    }
}
exit("ERROR")  ; 
?>

 

Expected output : added to playlists

actual output : Not added to playlist

 

output :

 

X4Jhwp.jpg

How to solve the error?

Edited by aveeva

Share this post


Link to post
Share on other sites
Posted (edited)

Finally working after changes the value sku to voice_sku and name to voice_name in JS.

Edited by aveeva

Share this post


Link to post
Share on other sites
Posted (edited)

@Barand    I just want to show playlist to other page, so i create 

view_cart.php :

<html>
<head>

    <style type="text/css">
        table {
            border-collapse: collapse;
            border: 1px solid black;
        }
        table td,th {
            border: 1px solid black;
        }
        td {
            text-align: center;
        }
    </style>
</head>

<body>

    <h2>Play Lists</h2>

    <table>
        <th>Voice SKU</th>
        <th>Voice Name</th>

        <?php
       session_start();
      foreach ($_SESSION['playlist'] as $key => $value) {
           echo "<tr>";
           echo "<td>" . $key . "</td>\n<td>" . $value . "</td>";
            echo "</tr>";
        }

        ?>
    </table>
</body>
</html>

I have passed both voice_sku and voice_name to view_cart.php, here how can i pass along with delete option.

 

Output:

 

qaMkOn.jpg

Edited by aveeva

Share this post


Link to post
Share on other sites

In your loop above, when you output the key and the value, also output a delete button (just as I did in my example).

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.