0

I have the below button in my index.php file.

<form action="update.php" method="post" >
<button onclick="myFunction()">Update</button>
</form>

I have the below javascript function.

<script type="text/javascript">
function myFunction()
{
$.ajax({
        type: 'post',
        url: 'update.php',
        data: {
            source1: "some text",
        },
        success: function( data ) {
            console.log( data );
        }
    });
}
</script>

I am using the above javascript function to send the javascript variable to the php server side script file (update.php). I am accessing the variable in update.php as below.

$src1= $_POST['source1'];
echo $src1;

However, I am not able to see the variable in the output of update.php file. What am doing wrong?

2 Answers 2

1

Try to do it on the submit event of the form and cancel the default behavior. First set the button type to submit the form:

<form action="update.php" method="post" >
  <button type="submit">Update</button>
</form>

Then add the event in JavaScript:

$('form').submit(function(e) {
  e.preventDefault();
  // code here
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for providing an answer. I have more than 2 buttons. So, I tried to assign an id to this form and in my javascript function, I tried using the ID name. However, it is not working.
1

Have you tried .done method instead of success parameter which is supposed to be deprecated.

$.ajax({
    type: 'post',
    url: 'update.php',
    data: {
        source1: "some text",
    },

}).done(function( data ) {
        console.log( data );
});

7 Comments

Thanks for providing an answer. I tried it. But am not getting any luck.
Have you checked the request your web browser made and the response it received?
I see 200 OK for my request. However, I am not able to verify the response. I am using google chrome browser and not sure on how to check the console data.
right click and select inspection mode, tab console is the console output. tab network contains all the requests and responses.
If you know how to use this, you almost never need to ask a question ever again
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.