javascript - how to retrieve variable instead of echo -
i've started larn ajax , want know how php variable instead of echo
followed this.
ajax_php_code.php
echo 'your name '.$_post['firstname'].''$_post['lastname].'';
html/ajax
function ajax_post(){ var hr = new xmlhttprequest (); var url = "ajax_php_code.php"; var fn = document.getelementbyid('first_name').value; var ln = document.getelementbyid('last_name').value; var vars = "firstname="+fn+"&lastname="+ln; hr.open("post", url, true); hr.setrequestheader("content-type", "application/x-www-form-urlencoded"); hr.onreadystatechange = function(){ if(hr.readystate == 4 && hr.status == 200){ var return_data = hr.responsetext; document.getelementbyid('status').innerhtml = return_data; } } hr.send(vars); document.getelementbyid('status').innerhtml = "processing..."; } <input type="text" id="first_name" name="first_name" placeholder="namn" /> <input type="text" id="last_name" name="last_name" placeholder="efternamn" /> <input type="submit" value="skicka data" id="knapp" /> <div id="status">
this working fine have variable sent instead of echo possible?
the usual way have php send json, , parse json client-side.
for instance, in php:
$data = array( firstname => $_post['firstname'], lastname => $_post['lastname'] ); header("content-type", "application/json"); echo json_encode($data);
then client-side, in ajax success function:
var info = json.parse(hr.responsetext); // can utilize data.firstname , data.lastname
javascript php ajax
No comments:
Post a Comment