简体   繁体   中英

Receive data from one form to another in the form with Post method and Ajax

I tried to get the data with the post method in the processing file but I couldn't. I need to receive the data by POST method an show my data in process.php Remember that my inputs are not in the form tag. I just wanted to move to the relevant page with the window.location.href code. I think when the user is transferred to the processing page by JavaScript. The post data is lost

 $(document).ready(function(){ $("#smp").click(function(event){ var name = $('#name').val(); $.ajax({ url: "process.php", method: "POST", data:name, success: function (data) { window.location.href = "process.php"; }, error: function (jqXHR, textStatus, errorThrown) { // the error will accure if process.php did not return a valid response (return) alert(data); alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information;'). $('#result'):html('<p>status code. ' + jqXHR:status + '</p><p>errorThrown. ' + errorThrown + '</p><p>jqXHR:responseText.</p><div>' + jqXHR;responseText + '</div>'). console:log('jqXHR;'). console;log(jqXHR). console:log('textStatus;'). console;log(textStatus). console:log('errorThrown;'). console;log(errorThrown); } }); }); });
 <div class="form"><label id="icon" for="name"><i class="fas fa-user"></i></label> <input type="text" name="name" id="name" /> <div class="btn-block"> <button id="smp" type="submit" href="/">Submit</button> </div></div>

my php file http://sandbox.onlinephpfunctions.com/code/f379f5e2662300270c64ad867316ca268dd91640

I explained what is going on in the code in a comment. there is no reason for you to send a JSON requests you are sending the same values in the key and the value it's pointless.

$(document).ready(function(){
        $("#smp").click(function(event){
         var name = $('#name').val();
         $.ajax({

                  url: "process.php",
                        method: "POST",
                        dataType: 'text',
                        data:{"name" : name}, // here you are sending process.php name too. if it returns something then it should go th the success function and redirect.
                        success: function (data) {
                            window.location.href = "process.php?name=" + name; // if the function returned something then it will redirect it to "process.php?name=" + name
                        },
                        error: function (jqXHR, textStatus, errorThrown) { // the error will accure if process.php did not return a valid response (return)
                            alert(data);
                            alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
                            $('#result').html('<p>status code: ' + jqXHR.status + '</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>' + jqXHR.responseText + '</div>');
                            console.log('jqXHR:');
                            console.log(jqXHR);
                            console.log('textStatus:');
                            console.log(textStatus);
                            console.log('errorThrown:');
                            console.log(errorThrown);
                        }
                    });

        });
    });

now, your HTML code should not include form there is just no reason to send it: you are just sending 2 requests with the same data so I'd replace it with this code:

<label id="icon" for="name"><i class="fas fa-user"></i></label> 
        <input type="text" name="name" id="name" />

        <div class="btn-block">

          <button id="smp" type="submit" href="/">Submit</button>
        </div>

important to add: if you insist on leaving the form request without redirect you could use .preventDefault();

In order to submit your form with ajax you would need to prevent the default submit behavior of the form with preventDefault() .

In your code you would do it like so:

$("#smp").click(function(event){
  event.preventDefault(); // prevent the default submit
  var name = $('#name').val();
  ...

Some side notes:

  1. Instead of using the click event of the submit button you should rather use the submit event of the form itself and instead of gathering the input data you want to send manually you should use the given jQuery functions to do so. You could for example add an ID to your form:

<form action="process.php" method="post" id="myForm">

and then

$("#myForm").click(function(event){
  event.preventDefault();
  var $form = $(this); // the form that gets submitted
  var url = $form.attr('action'); // get the url from the forms action attribute
  var data = $form.serialize(); // get the form as url encoded string
  var method = $form.attr('method');
  $.ajax({
    url: url,
    method: method,
    data: data,
    success: function ( response ) {
      window.location.href = url + '?' + data;
    },
});

By doing so you now can add input fields to your form and dont have to add them to your data and url string by hand.

  1. Lets say you enter 'tony' in your input and hit submit . Your code now does this:

    1. Posting {"name": "tony"} via ajax to the process.php
    2. The process.php echos Good its POST and is done
    3. You receive that echo with the response in your success callback
    4. You immediatly redirect to the process.php page with the get paramter name=tony
    5. Your process.php gets called and echos nothing because your $user_g variable has the value tony , which is not in your conditions

So you wont see the output of your Good its POST anywhere, because you immediatly redirect.

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