The best way passing value from jQuery to PHP

Since it looks like you are new on ajax, let’s try something more simple ok? Check this js:

<script>
var string = "my string"; // What i want to pass to php

 $.ajax({
    type: 'post', // the method (could be GET btw)
    url: 'output.php', // The file where my php code is
    data: {
        'test': string // all variables i want to pass. In this case, only one.
    },
    success: function(data) { // in case of success get the output, i named data
        alert(data); // do something with the output, like an alert
    }
});
</script>

Now my output.php

<?php

if(isset($_POST['test'])) { //if i have this post
    echo $_POST['test']; // print it
}

So basically i have a js variable and used in my php code. If i need a response i could get it from php and return it to js like the variable data does.

Everything working so far? Great. Now replace the js mentioned above with your current code. Before run the ajax just do an console.log or alert to check if you variable password is what you expect. If it’s not, you need to check what’s wrong with your js or html code.

Here is a example what i think you are trying to achieve (not sure if i understand correctly)

EDIT

<script>
var hash = "my hash";

 $.ajax({
    type: 'post',
    url: 'output.php',
    data: {
        'hash': hash        },
    success: function(data) {
        if (data == 'ok') {
            alert('All good. Everything saved!');
        } else {
            alert('something went wrong...');
        } 
    }
});
</script>

Now my output.php

<?php

if(isset($_POST['hash'])) {
    //run sql query saving what you need in your db and check if the insert/update was successful;
    // im naming my verification $result (a boolean)
    if ($result) echo 'ok';
    else echo 'error';
}

Since the page won’t redirect to the php, you need a response in you ajax to know what was the result of you php code (if was successful or not).

Here is the others answers i mentioned in the coments:

How to redirect through ‘POST’ method using Javascript?

Send POST data on redirect with Javascript/jQuery?

jQuery – Redirect with post data

Javascript – redirect to a page with POST data

Leave a Comment