0

I want to pass some data as a variable using jQuery $.post() method to a PHP file and then display the result in a div after clicking a button. But the data isn't getting retrieved in PHP file.

<script> $(document).ready(function () { $("button").click(function () { $.post("add.php", { fname: 'Billy' }, function () { $('#topic').load('add.php'); }); }); }); </script> </head> <body> <br> <div class="container"> <?php echo "Welcome ".get('Name')." !"; ?> <div style="float: right"> <?php echo "<a href='logout.php'> Log Out </a>"; ?> </div> <br> <button>Add Topic</button><br> <div id='topic'></div> 

//the PHP file:

<?php session_start(); echo "".$_POST['fname'].""; //if(isset($_POST['fname'])) //{ //$fname=$_POST['fname']; //echo " ".$fname." topic added!"; //} ?> 

Notice: Undefined index: fname in C:\xampp\htdocs\forum\add.php on line 3

3
  • Are you sure you get the error after the POST is done? Maybe you get the error when you load the page the first time Commented Jul 4, 2019 at 11:57
  • the success-callback ist strange. Why do you do another .load after the post? You should read the return from $.post and use that to fill #topic Commented Jul 4, 2019 at 12:00
  • 1
    try this instead: $.post("add.php", { fname : 'Billy' }, function(response){ $('#topic').html(response);}); }); Commented Jul 4, 2019 at 12:01

2 Answers 2

2

I'm not too familiar with the load function, but it seems to me that you're doubling down on fetching from the same resource.

You could do something like:

$.ajax({ type: "POST", url: 'add.php', data: {fname:"Billy"}, success: function(response){ $( "#topic" ).html(response); // or .text or whichever replacement method you need/works best }, }); 

add.php

if ( isset($_POST['fname'] ){ echo "Topic " . $_POST['fname'] . " added!"; } else { echo "Could not find 'fname'!"; } 
Sign up to request clarification or add additional context in comments.

Comments

0
$.ajax({ type: "POST", url: 'add.php', data: {fname:"your data goes here"}, success: function(response){ // handle success }, error: function(response){ // handle error }, }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.