refresh input after ajax submit form

12,706

Solution 1

Since you are using ajax to return the value, save the new value to a varibale say new_input,

then simply use,

$("#target_input_id").val(new_input);

Or your .done() function in ajax call should be like,

.done(function ( data ) {
  $("#target_input_id").val(data); //assuming the php file only returns the value for input
});

Since you have to return multiple values, look at this two links.

json - Jquery return undefined for multiple values in ajax call

How to return multiple values from JQuery AJAX call?

Now .done() would be,

.done(function ( data ) {
      $("#key").val(data.key); 
      $("#nonce").val(data.nonce);
    });

Solution 2

.html file

<!DOCTYPE html>

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
    $("#check").click(function(){
        $("#keyvalue").text($("#key").val());
    });
    $("#submit").click(function(){
    var text = $("#text").val();
    var key = $("#key").val();
        $.ajax({
            url: 'trial.php',
            data: {text: text, key:key},
            type: 'POST',
            dataType: 'json',
            success: function(data) {
                if(data.status == "fail"){
                    $("#status").html(data.message);
                }else{
                    $("#status").html(data.message);
                    $("#key").val(data.key);
                    $("#keyvalue").text('');
                }
            }
        });
        return false;
    });
 });
</script>
</head>
<body>
    <form method="post" action="trial.php" onsubmit="return send_form();">
        <input type="text" name="text" id="text"/>
        <input type="hidden" id="key" name="key" value="xsaigoehf7118191"/>
        <button id="submit">Send data and get new key</button>
    </form>
    <br><br>
    <div id="status"></div>
    <br><br>
    <button id="check">What's current value of key?</button> --------> <span id="keyvalue"></span>

    <div id="response"></div>
</body>

</html>

.php

<?php

//You get the form contents here.

$key = isset($_POST['key']) ? $_POST['key'] : "error";
$text = isset($_POST['text']) ? $_POST['text'] : "empty";

//Check them if it matches with DB's entry, if doesn't you set $key = "error";

if($key=="error"){
    $status = "fail";
    $message = "There was some error processing your form.";
    exit;
} else{

    //You generate another random key.
    $random ='';
    for ($i = 0; $i < 10; $i++) {
        $random .= chr(mt_rand(33, 126));
    }

    //Now here in steps save it to your DB. So that when next form is submitted you can match it.
    //And send back response to html file, where ajax will refresh the key.
    $status = "success";
    $message = "
    Your form was processed succesfully<br>
    The text you sent was ".$text.", and the key you sent was ".$key.".
    The new key sent to you can be seen by pressing the button below, has value, ".$random."<br><br>
    ";
    }

    echo json_encode(array("status" => $status, "message" => $message, "key" => $random));

?>

Hope this helps you.

Share:
12,706
user2635001
Author by

user2635001

Updated on June 04, 2022

Comments

  • user2635001
    user2635001 almost 2 years

    I searched all over but couldn't find how to refresh specific input field via js/jquery/ajax.

    This my input that change on every post :

    <input type='hidden' id='nonce' name='nonce' value=''>
    <input type='hidden' id='key' name='key' value=''>
    

    I need after ajax form submit to refresh this inputs, any idea?

    A better explanation : This php code generates random hashed keys.

    <form action="#">
    
    <?php $n->generateFormFields() ?>
    
    </form>
    

    I send this generated key via ajax POST, the problem is when I send the code to the ajax, the key changes in server side, so after next submit the key will be wrong because it didn't change after the ajax response, so I need to refresh this code after ajax submit/ refresh the inputs above.

    edit 2 :

    I am using this php script :

    http://github.com/greatwitenorth/php-nonce

    The script is working on php POST, but I am using AJAX post so I need to refresh the keys with ajax somehow.

    edit 3:

    The form ex:

    <form action="#">
    
    <?php $n->generateFormFields() ?>
    
    </form>
    

    The php function above is creating Hashed keys. These hashed keys I send via ajax json POST, after I send them, I verify that the key is the same as the database key . - if ok continue, if not show error. now the problem is the key changes every time the form submitted. So it changes but in the input on the form, its not changed because ajax is not refreshing the page, so it will be sending the same key value that was before.

  • user2635001
    user2635001 over 10 years
    its not good , look i will explain more better : i have form login , in my form login i have php function that generate random keys and i send them via ajax post and in the server side file i verfiy if it correct code. now the code change every post on server side , so i need to refresh it also after ajax response so i need to refresh the specific inputs - just refresh not take new values and not clear just make it refreshed..
  • Optimus Prime
    Optimus Prime over 10 years
    Still not clear what you are looking for, this is how you refresh/change input values. Look here. jsfiddle.net/TSc8E/48
  • user2635001
    user2635001 over 10 years
    thanks you for your help , it close to what i need but still not what i need , look i have login form . in my login form i have hidden input that generate random hash keys with php function .i send the key with ajax POST to sever side php file and verfiy if the key is correct . so the problem is every time i press submit the key changes on the server side on not on the input , so its send old key instead of the new one , so i need to trigger the ajax to refresh this input to the the serverside key , only when i make refresh to the page it show the new key but ajax dont refresh
  • Optimus Prime
    Optimus Prime over 10 years
    Are you refreshing key on server side or client side first?
  • user2635001
    user2635001 over 10 years
    the keys generated on php server side function inside the form input and auto refreshred by server side after been used , i mean if this key : 123 , verfiyed and already been used , it will be changed to 132 on serverside - Database . - but it wont change on the input since ajax post not refreshring the page.
  • user2635001
    user2635001 over 10 years
    no , the key using for verfiying if the user submit the form via my site form ,and no csrf from other location .. every form in my site i using input hidden with value hashed key to verfiy that the user come from my site and not trying to hack the login system. github.com/greatwitenorth/php-nonce look here - that what i use in my form. i trying to refresh this key after ajax completed.
  • Optimus Prime
    Optimus Prime over 10 years
    Look hidden inputs are changed too the same way, see here jsfiddle.net/alexdickson/S9mUL/5. i dont understand what's your problem are you receiving the new verification code from the server correctly, that will be the new value of key?
  • user2635001
    user2635001 over 10 years
    ok look this : github.com/greatwitenorth/php-nonce , that what i using in my forms . the problem is with AJAX . php normal POST makeing refresh to page after submit , and ajax post not refreshing the page . so the problem here that the key the genereated with php function once u enter the form sends the right key , but after second submit it wont send the right code cuz its keep the old code on the value seens ajax not refreshing the page and the value not changing , and i dont know how to refresh the inputs/form so the key will be the new one the generated.
  • Optimus Prime
    Optimus Prime over 10 years
    So you change the key value after the first ajax gets submitted, whats the problem there?
  • user2635001
    user2635001 over 10 years
    its not changing the key after AJAX subbmited , i want that it will changing ,this why i ask how to refresh the inputs so the key will be change to the new one. the problem is the key changing , but not on the input cuz the ajax not doing refresh to the page and it send always the same key --- look at the first post edit 3 more explained.
  • Optimus Prime
    Optimus Prime over 10 years
    No, when you do the form submit first time, return a json array with data.status =success,data.key= new key and data.nonce=new nonce, then you use what I told .val() to change the value of key and nonce next time you submit the form, new value will be submitted for sure
  • user2635001
    user2635001 over 10 years
    yea i understand but in the serverside php i just verfing the key and not creating new one , i create keys only the form , so how can i return another key if i create only in the form ? look this ex: key:kAuQ7MloJfn1alFcDBZ/evOYl7+i1FcdlXJxqkSscT8= i created this key with php inside input inside form , now i sended this key via ajax post , now after i sended and verfied that the currect key it will contiue else will return error , now after each form submitted the key changes on the form side and i need to send the new , but ajax not refreshing the page so how i do it?
  • user2635001
    user2635001 over 10 years
    the keys created only in the forms and send to verfiy with ajax post and return succses or false , but it not returning new key , the new key created only in the form and changes after every submit,the problem is ajax not refreshing the login form so the input keep the same old key and keep sensing it over over cuz the form didnot refreshed and the value kept the same value always
  • Optimus Prime
    Optimus Prime over 10 years
    Are you not saving this key in a database?
  • Optimus Prime
    Optimus Prime over 10 years
    Why won't ajax refresh the keys? What do you mean. If you are creating the key using php, you later change it so you need a new key from the server.
  • Optimus Prime
    Optimus Prime over 10 years
    Use location.reload() to refresh the page using jquery otherwise.
  • user2635001
    user2635001 over 10 years
    somthing that i think as like that maybe :$.ajax({ url: '../includes/nonce.php', data: {action: '<?php $n->generateFormFields() ?>'}, type: 'GET', success: function(output) { $("form").html(output); } }); which i call the function with ajax and output it inside the form ?
  • user2635001
    user2635001 over 10 years
    yea but the php function creating the input fields + the keys and store them in Database and then after form submitted i verify if the key correct and if true or false the keys changes anyway
  • Optimus Prime
    Optimus Prime over 10 years
    So you are changing the entire form, so 'output' that you get as response doesn't contain the newer code? If your php file returns the newer code, you will have it in your form too.
  • user2635001
    user2635001 over 10 years
    no , my php file "proccses.php" just check the form submitted details , in the form i created hidden input with random hashed keys that stored on the database , that hashed key sends with the ajax post and in my php file "proc.." i check with other function if the key is correct from DB . the php file have nothing with new keys. its just check if good key or wrong , in the form i create every submit new key , but the ajax not refreshing the page so it keep sends the same key. how can i explain u better ? thanks for help and sry for anoying and bad english
  • user2635001
    user2635001 over 10 years
    i mean the input value have the same value ex : input value='23432'--> form submited the php check if the value key is the same in the DB then again change the value to value="423461" so that value changed and everything ok but AJAX not refreshing the page so the value keep stay value='23432' the first one so it will say wrong key , i need to make the value refreshed to the new one
  • user2635001
    user2635001 over 10 years
    there is no way to trigger ajax refresh only the value and thats all ?
  • Optimus Prime
    Optimus Prime over 10 years
    Yes so that is exactly what I told you to do, the new key in your DB is 423461. So for the first submit where you return success, do not just return success, also return the key i.e return another varibale key of value 423461. Do you know about returning multiple values with ajax? Return the new keys too. These new keys will be the keys which have been refreshed in your DB. Does this help?
  • Optimus Prime
    Optimus Prime over 10 years
    There is, the way is you do not generate the entire php form, you send your variable to a php file, that php file sends you 3 values, in array output. output.status which will have success/failure. output.key = 423461, output.nonce = 'whatever'. Now when this is returned you use the method, .val() to change the input as I showed you in the fiddle.
  • user2635001
    user2635001 over 10 years
    thanks you very much but i dont help me i still stuck , very very thanks that u try to help me .. but i have other sitatuin maybe u understand me wrong so my bad cuz i have bad english... :(
  • Optimus Prime
    Optimus Prime over 10 years
    Oh you dont worry. I will try to create a html for and php file, to show you how you do it.
  • Optimus Prime
    Optimus Prime over 10 years
    I am adding code of a .html and trial.php file which will work with each other.
  • user2635001
    user2635001 over 10 years
    Thanks you very much for you help , so its allmost what i have but in your php when u check the key i have php function that do it and just return msg text and not generate new key i will show u what i mean in the next answer , again thanks you so much.
  • Optimus Prime
    Optimus Prime over 10 years
    Okay. Welcome. But a suggestion please work on your english. ;)
  • Optimus Prime
    Optimus Prime over 10 years
    Editing the question for new question is a wrong idea. You should have started a new one. Please add a new question, and give me the link here. Make this question same as before. I would surely help on the newer one.
  • user2635001
    user2635001 over 10 years
    stackoverflow.com/questions/18053078/… here i make new one please help me i stuck very hard i am newbie ajax
  • Optimus Prime
    Optimus Prime over 10 years
    Yes I will see that link after my class.