简体   繁体   中英

Getting the value via AJAX, PHP

I have an ajax function with three parameters. The first parameter holds the url that the ajax function go to when it's called. The second parameter contains the id name of the div containing the eventual output. The third parameter contains a variable that can be stored in POST to be sent to the url that the ajax function go to when it's called, so that it can be echoed, and sent to the div with the id 'output' on the original page.

My question is: Are there any ways to get the value in the input type submit, so that it can be stored in POST to be sent to the url that the ajax function go to when it's called, so that it can be echoed, and be seen in the div with the id 'output' on the original page?

So the value in the input type submit would be "submit".

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type = "text/javascript"> 

function ajaxPass(gotoUrl,output,input) {

      $.ajax({
           type: "POST",
           url: gotoUrl,
           data: { input : input },
           error: function(xhr,status,error){alert(error);},
           success:function(data) {
             document.getElementById( output ).innerHTML = data;
           }

      });

}

</script>

<input type = "submit" name = "submit" value = "submit" onclick = "ajaxPass('test2.php','output','input')">
<div id = 'output'> </div>

<?php

$input = $_POST['input'];
echo $input;

?>

Not sure I understood, but I'll try to answer this part:

Are there any ways to get the value in the input type submit

<input type = "submit" name = "submit" value = "submit" onclick = "ajaxPass('test2.php','output',this.value)">

The key is to use this.value , this referencing the input element, and value its, of course, value.


See this simple example to see it in action:

 <input type = "submit" name = "submit" value = "submit value here" onclick = "alert(this.value)"> 


UPDATE

This example will read the value of the text input element and pass that as input variable in the AJAX call:

function ajaxPass(gotoUrl,output) {

      var input = document.getElementById('t').value; // or $('#t').val();

      $.ajax({
           type: "POST",
           url: gotoUrl,
           data: { input : input },
           error: function(xhr,status,error){alert(error);},
           success:function(data) {
             document.getElementById( output ).innerHTML = data;
           }

      });

}

</script>

<input type="text" id="t">
<input type = "submit" name = "submit" value = "submit" onclick = "ajaxPass('test2.php','output')">
<div id = 'output'> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM