-7

I wonder how I can pass value from Jquery to PHP. I found similar codes but not even one of them work. Everytime alert shows value of variable but when I open site there is not any. Var_dump shows that $_POST is null. I am ran out of ideas do you have any?

jQuery code:

$("#password-button").click(function(){
 var password="";
 var numbers =[0,0,0,0,0,0];
 for(var i=0;i<=5;i++){
    numbers[i] = Math.floor((Math.random() * 25) + 65);
    password += String.fromCharCode(numbers[i]);
 }
   $(".LoginError").text("Nowe haslo: " + password);

  $.ajax({
                    type: 'post',
                    url: 'dzialaj.php',
                    data: {'password': password},
                    cache:false,
                    success: function(data)
                    {
                        alert(data);
                         console.log(result)
        console.log(result.status);
                    }
                });

});

PHP:

if(isset($_POST['password'])){
$temp = $_POST['password'];
echo $temp;
}
Insane Skull
  • 8,810
  • 9
  • 38
  • 59
Seweryn
  • 33
  • 1
  • 1
  • 7
  • 1
    Please post your code here so it is preserved for future SO visitors. – Jay Blanchard Nov 11 '15 at 14:15
  • 2
    Use AJAX to pass data from Javascript to PHP. It's hard to be of any more help with such a vague question. – Rory McCrossan Nov 11 '15 at 14:15
  • 1
    AJAX is how you pass values from jQuery to PHP. – Jay Blanchard Nov 11 '15 at 14:15
  • AJAX is the solution – Tal Nov 11 '15 at 14:20
  • I know that Ajax is the solution. When I check data parameter has value inside but in php the value is gone, it is null. I do not know why. – Seweryn Nov 11 '15 at 14:24
  • post your HTML form that goes with this. Use error reporting http://php.net/manual/en/function.error-reporting.php and check your console. – Funk Forty Niner Nov 11 '15 at 14:29
  • 1
    where are you setting `result`? suggest using `POST` for your `type` also. And as @Fred-ii- says, use the console – Rob G Nov 11 '15 at 14:34
  • I have a 5 minute span of attention. I am out of this question. @ me if you want and when you posted your HTML form that should have been posted in the first place. Good luck, I am moving on... *ciao!* – Funk Forty Niner Nov 11 '15 at 14:36
  • @Fred-ii- Which form? I do not have any. This is just function, create some random string after user clicked button. jQuery code works fine i think cause I can generate random string and alert shows this value. Problem is with PHP code. var_dump($_POST['password'] always shows null. $_POST['password'] is never set I guess but I can not figure out why – Seweryn Nov 11 '15 at 15:08
  • what does `var_dump($_REQUEST)` show? Use firefox/chrome & inspect the network traffic to see what HTTP request headers are being sent to your script. If the headers are being sent but PHP can't see them, there must be something odd with your PHP installation – Rob G Nov 11 '15 at 16:54

1 Answers1

6

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

Community
  • 1
  • 1
Clyff
  • 3,826
  • 2
  • 14
  • 32
  • all clear thanks. This is the same way how my jQuery code works. When you open in browser output.php do you see value "my string"? The problem is that I can not, even using your code – Seweryn Nov 11 '15 at 15:18
  • Sure you can't. If you open the php file directly there won't be the post you set in your js. Same thing if you use GET parameters instead. The purpose of this ajax is with your js script, you run you php code as well. If you are going to access the php directly you probably don't need the js part. – Clyff Nov 11 '15 at 15:30
  • As you can see the php file only works if someone open the file with the post parameter expected. Just like the js does. – Clyff Nov 11 '15 at 15:33
  • "If you open the php file directly there won't be the post you set in your js".Even if I open window with javascript first? What I think it works: User open site, click button, some random string generate, send to php, user open new window(with this php code this time) and see this generated string. Am I right? – Seweryn Nov 11 '15 at 15:37
  • It does'nt works that way. Is more like: User open an site > User fills a form and click the submit > js is triggered and get the inputs > js call the ajax to a php code > php code do what it needs to do with the information given and can output a response to js > js gets the response and show to the user (if that is the case) > User didn't had to leave the page to get the response of the form. – Clyff Nov 11 '15 at 15:47
  • The real point of this is the user don't need to go to the other page. If the user have to do... would not be better just make a form and submit to that page? – Clyff Nov 11 '15 at 15:51
  • "would not be better just make a form and submit to that page?". I have only one value. Maybe I should tell what I want achive. This function in jQuery generate random string. I want save to database this value. This value does not need to be send back to site because php code will send this to database. I know that the idea of Ajax is not to re-load page. "... and see this generated string." I meant that was control point for me to check if everything is ok but I noticed that is not because echo does not display values which I generate – Seweryn Nov 11 '15 at 16:03
  • Maybe I was wrong. I wanted to echo value from jQuery but maybe it does not work that way. Should I make header to output.php from site where I generate string? and the second header should be from output.php to site where I generate string?(Just like logout from session() ) ? but instead of unset variables and destroy session send value to database. Am I right these time? – Seweryn Nov 11 '15 at 16:09
  • I updated the answer, not sure i understand 100% though. If you really need to go to the php page (as you asked before). You could see this answers for "how to redirect to a page sending POST" . Spoiler: most of than says to you make a hidden form and submit it. :) – Clyff Nov 11 '15 at 16:27
  • I do not need to go to the php page. I just want jQuery value send to database. I thought that I could pass value to php and later connect to database but in the middle of work I noticed that $_POST in php file gives me only null not value from jQuery function and here I am few hours and 2 pages of Google search later – Seweryn Nov 11 '15 at 16:35
  • I vote for this answer because it has a very detailed description (comments) and helped me understand how to make a simple ajax call. Thank you – kanlukasz May 15 '20 at 05:52