ozgursana ozgursana - 3 months ago 7
PHP Question

Assign outside variable with ajax

Here is my js page and tcCheck.php page.

<script>
function checkTC() {

$("#loaderTC").show();
jQuery.ajax({
url: "check/tcCheck.php",
data:'tc='+$("#tc").val(),
type: "POST",

success:function(data){
//WORKING CODE
document.getElementById('name').value = data;
//NEEDED CODE
document.getElementById('name').value = "NAME VARIABLE"
document.getElementById('phone').value = "PHONE VARIABLE"

},
error:function (){}
});
}
</script>


tcCheck.php

<?php
require_once("../config.php");
include("../girisbilgi.php");
$query = $link->query("SELECT * FROM musteri where musteriTC='" . $_POST["tc"] . "' and userSaID='".$userSaID."'");
if($veri =$query->fetch_object())
{

//WORKING CODE
echo $veri->musteriAD;
/NEEDED
$name = $veri->musteriAD;
$phone = $veri->musteriTel;
}
?>


tcCheck.php works correctly.I can change input if i change my tcCheck.php result like echo $veri->musteriAD;
But i need to change 2 inputs so i need this variables.
How can i assing $name and $phone variable values in my js page ?

Answer

Return a format you can parse easily with javascript - i would reccomend json:

if($veri =$query->fetch_object()){

    //set correct header
    header('Content-Type: application/json');
    //echo out json
    echo json_encode(['name'=>$veri->musteriAD, 'phone'=>$veri->musteriTel]);
    //done, stop processing
    die();

}

javascript

success:function(data){

     $('#name').val(data.name);
     $('#phone').val(data.phone);
},
Comments