GET var from php to use in javascript function

42 views Asked by At

i want to get a var from a php script and use it in a function .. so if i call the var simply with $.get (and document.write) i got an result but how can i integrate this into a function ?

$.get( 'http://www.domain.de/content/entwicklung/verdienst.php', function(verdienst_php) { 
//document.write(verdienst_php);

});

function sendview () {
var datastring = {uid : uid_clear, verdienst : verdienst_php};
$.ajax({
type: 'POST',
url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
data: datastring,
});
}

only put the function into the $.get part didnt work

if i didnt use $.get and write in datastring like

verdienst: 1000

it works

any suggestions ?

kind regards Dave

2

There are 2 answers

0
epascarello On BEST ANSWER

Assuming you are returning exactly what you want from the server, store it in a variable and reference the variable in the other Ajax call.

var verdienst_php;
$.get( 'http://www.domain.de/content/entwicklung/verdienst.php',
    function(response) { 
    verdienst_php = response;
});

function sendview () {
    var datastring = {uid : uid_clear, verdienst : verdienst_php};
    $.ajax({
        type: 'POST',
        url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
        data: datastring,
    });
}

If you want the GET call to happen when the click happens, than you just need to put the post code inside of the GET success callback.

1
kamal pal On

You have to make an extra ajax call to get php variable, you can do it this way :-

function sendview () {
    var datastring = {uid : uid_clear, verdienst : getPHPVar('verdienst_php')};
    $.ajax({
        type: 'POST',
        url: 'http://www.domain.de/content/entwicklung/view_succeed.php',
        data: datastring,
    });
}

function getPHPVar(varname){
    var returnValue = null;
    $.ajax({
        url: 'yourphpurl.php',
        async: false,
        type: 'post',
        data:{
            task:'getvar',
            varname: varname
        },
        success: function(response){
            returnValue = response;
        }
    });
    return returnValue;
}

and in PHP it will look like:

<?php 
if($_POST['task'] == 'getvar'){
    echo $$_POST['varname'];
}

Also, I think it's actually not needed cause you are getting php variable using ajax, and again using it in another ajax call. so Why don't you just do it in php ?