Hi please I'm new to javascript and ajax and i read that to convert javascript ( client-side)variable to php(server side) variable we have to pass by AJAX.
Please can someone give the the same code using AJAX. Here I'm using bad method but i just post this code to show what is my goal which is : when the user select an id from select tag HTML i want that others information appears in inputs tags (type text) so that he can modify the information
here is my source code:
<script type="text/javascript">
document.getElementById('id').onchange = function(){
var identifiant = document.getElementById('id').value;
<?php
$phpvar='"+identifiant+"';
$sql="select * from inscrits where id=".$phpvar;
$res=mysql_query($sql) or die ('Unable to run query:'.mysql_error());
$ligne=mysql_fetch_array($res);
?>
//document.getElementById('nom').value ="<?php echo $phpvar;?>";
document.getElementById('nom').value = "<?php echo $ligne['nom'] ?>";
document.getElementById('prenom').value = "<?php echo $ligne['prenom'] ?>";
document.getElementById('profession').value = "<?php echo $ligne['profession'] ?>";
document.getElementById('etablissement').value = "<?php echo $ligne['etablissement'] ?>";
document.getElementById('telephone').value = "<?php echo $ligne['telephone'] ?>";
document.getElementById('email').value = "<?php echo $ligne['email'] ?>";
document.getElementById('acceptation').value = "<?php echo $ligne['acceptation'] ?>";
}
</script>
Please appreciate my situation i'm new to javascript programming i just get started
if it is possible to post me the code that i can use in same page.php thank you
There are many ways of doing this, but here is a simple code that can help. I got the code from an old book called Ajax in a Nutshell but modified it for you example,
create a php file lookupCustomer.php and add your php code in it with an additional change to i,
<?php
$phpvar = 'id';
$sql="select * from inscrits where id=".$phpvar;
$res=mysql_query($sql) or die ('Unable to run query:'.mysql_error());
$ligne=mysql_fetch_array($res);
print_r(json_encode($ligne));
?>
Here is how you call the php script and update your form, again this is just a simplified way of doing this logic,
<html>
<head>
<title>EXAMPLE</title>
<script language="javascript" type="text/javascript">
var xmlObj = (typeof window.ActiveXObject != 'undefined')
? new ActiveXObject("Microsoft.XMLHTTP")
: new XMLHttpRequest();
if (xmlObj == null)
alert("Error creating request object!");
function getCustomerInfo()
{
var id = document.getElementById("id").value;
var url = "lookupCustomer.php?id="+ escape(id);
xmlObj.open("GET", url, true);
xmlObj.onreadystatechange = updatePage;
xmlObj.send(null);
//* using POST instead of GET, use this code
//var url = "lookupCustomer.php";
//var req = "id="+ escape(id);
//req = req + "?dummy=" + new Date().getTime();
//document.getElementById("order").value = url;
//xmlObj.open("POST", url, true);
//xmlObj.onreadystatechange = updatePage;
//xmlObj.send(null);
}
function updatePage()
{
alert(xmlObj.readyState+" "+xmlObj.status);
if (xmlObj.readyState == 4)
{
if (xmlObj.status == 200)
{
/* Get the response from the server */
var customerAddress = xmlObj.responseText;
/* Update the HTML web form */
var linqne = JSON.parse(this.responseText);
document.getElementById('nom').value = linqne.nom;
document.getElementById('prenom').value = linqne.prenom;
document.getElementById('profession').value = linqne.profession;
document.getElementById('etablissement').value = linqne.etablissement;
document.getElementById('telephone').value = linqne.telephone;
document.getElementById('email').value = linqne.email;
document.getElementById('acceptation').value = linqne.acceptation;
}
else
{
var customerAddress = xmlObj.responseText;
alert("Server return status error = "+xmlObj.status);
}
}
}
</script>
</head>
<body onLoad="document.forms[0].reset();">
<p><img src="breakneck-logo.gif" alt="Break Neck Pizza" /></p>
<form method="POST" action="lookupCustomer.php">
<p>Enter your id number:
<input type="text" size="14" name="id" id="id" onBlur="getCustomerInfo()" />
<input type="text" size="20" name="nom" id="nom" />
<input type="text" size="20" name="prenom" id="prenom" />
<input type="text" size="20" name="profession" id="profession" />
<input type="text" size="20" name="etablissement" id="etablissement" />
<input type="text" size="20" name="telephone" id="telephone" />
<input type="text" size="20" name="email" id="email" />
<input type="text" size="20" name="acceptation" id="acceptation" />
</p>
</form>
</body>
</html>
Related
I'm struggling to get this to work as part of a larger exercise.
It's pretty simple - a user fills in a form which is sent using an XMLHttpRequest to a processing page. This should return a response below the form.
I had it almost working, but one field wouldn't show... and now nothing. Could this be a cache problem or is a problem with the code.
Here's the form:
<div id="miniContact">
<label for="yourName">Your Name</label>
<input type="text" name="yourName" id="yourName"><br>
<label for="phone">Your Phone</label>
<input type="text" name="phone" id="phone"><br>
<input type="text" name="reqd" id="reqd"><br>
<label for="email">Your Email</label>
<input type="email" name="email" id="email"><br>
<label for="type">Your vehicle type</label>
<input type="text" name="type" id="type">
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
Javascript:
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var yourName = document.getElementById("yourName").value;
var phone = document.getElementById("phone").value;
var reg = document.getElementById("reg").value;
var srv = document.getElementById("reqd").value;
var email = document.getElementById("email").value;
var type = document.getElementById("type").value;
var vars = "yourName="+yourName+"&phone="+phone+"®="+reg+"srv="+service+"email="+email+"&type="+type;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
...and the php file (my_parse_file.php):
<?php
echo 'Thank you '. $_POST['yourName'] . ' ' . $_POST['service'] . ', says the PHP file';
$user_name = $_POST['yourName'];
$reg = $_POST['reg'];
$email = $_POST['email'];
$srv = $_POST['srv'];
$phone_number = $_POST['phone'];
$vehicle = $_POST['type'];
?>
I am trying to get a full address by entering the postal code in a textbox in HTML form by press a button, I have two files the first one has the ajax function and the second one has the PHP code. I am not sure if my ajax code sending a request to PHP or not, Can anyone help me please?
here is the ajax file:
<script type="text/javascript">
$(document).ready(function(){
$('.addressbutton').click(function(){
ss= document.getElementById("address").value;
alert(ss);
$.ajax({
url: 'findaddress.php',
type: 'post',
data: ss,
success: function(response){
var replay = response.postal_code;
alert(replay);
document.getElementById('address').innerHTML = response.postal_code;
document.getElementById('address2').innerHTML = response.route;
document.getElementById('address3').innerHTML = response.locality;
document.getElementById('address4').innerHTML = response.postal_town;
document.getElementById('address5').innerHTML = response.administrative_area_level_2;
}
});
return false;
});
});
</script>
and here is the PHP code (findaddress.php)
<?php
header('Content-Type: application/json');
$ss=$_POST['address'];
$postcode = urlencode($ss);
$url = 'http://maps.googleapis.com/maps/api/geocode/xml?
address='.$postcode.'&sensor=false';
$parsedXML = simplexml_load_file($url);
if($parsedXML->status != "OK") {
echo "There has been a problem: " . $parsedXML->status;
}
$myAddress = array();
foreach($parsedXML->result->address_component as $component) {
if (is_array($component->type)) {
$type = (string)$component->type[0];
} else {
$type = (string)$component->type;
}
$myAddress[$type] = (string)$component->long_name;
}
$f1 = $myAddress['postal_code'];
$f2 = $myAddress['route'];
$f3 = $myAddress['locality'] ;
$f4 = $myAddress['postal_town'] ;
$f5 = $myAddress['administrative_area_level_2'] ;
$f6 = $myAddress['country'];
//print_r($myAddress);
$ORegisertation = array(
'postal_code' => $f1,
'route' => $f2,
'locality' => $f3,
'postal_town' => $f4,
'administrative_area_level_2' => $f5,
'country' => $f6
);
$account_json = json_encode($ORegisertation);
echo $account_json;
?>
HTML
<form name="frmRegistration" id="signup-form" method="post">
<div>
<input type="text" name="address" id="address" class="findaddress" placeholder="Postal code"/>
<input type="button" name="addressbutton" class="addressbutton" value="Find" id="findaddress" />
<input type="text" name="address2" id="address2" class="findaddress" placeholder="Line 1"/>
<input type="text" name="address3" id="address3" class="findaddress" placeholder="Line 2"/>
<input type="text" name="address4" id="address4" class="findaddress" placeholder="Line 3"/>
<input type="text" name="address5" id="address5" class="findaddress" placeholder="Line 4"/>
</div>
</form>
Javascript
$(document).ready(function(){
$('.addressbutton').click(function(){
ss = document.getElementById("address").value;
$.ajax({
url: 'findaddress.php',
type: 'post',
data: {address:ss}, //added an index address here
success: function(response){
var replay = response.postal_code;
//innerHTML is not an attribute of text boxes, so changed it to value
document.getElementById('address').value = response.postal_code;
document.getElementById('address2').value = response.route;
document.getElementById('address3').value = response.locality;
document.getElementById('address4').value = response.postal_town;
document.getElementById('address5').value = response.administrative_area_level_2;
},
error: function(response) {
alert("Error: "+response);
}
});
return false;
}); //added closing brace and bracket
});
added comments in script about changes made.
PHP FILE (findaddress.php)
<?php
header('Content-Type: application/json');
$ss = $_POST['address'];
$postcode = urlencode($ss);
$url = 'http://maps.googleapis.com/maps/api/geocode/xml?address='.$postcode.'&sensor=false';
$parsedXML = simplexml_load_file($url);
if($parsedXML->status != "OK") {
echo "There has been a problem: " . $parsedXML->status;
}
$myAddress = array();
foreach($parsedXML->result->address_component as $component) {
if(is_array($component->type)) $type = (string)$component->type[0];
else $type = (string)$component->type;
$myAddress[$type] = (string)$component->long_name;
}
echo json_encode($myAddress);
die();
?>
taken out irrelevant indexing again, and irrelevant statements.
There is the ajax code with the html form just to have a better idea
<form name="frmRegistration" id="signup-form" method="post">
<div><input type="text" name="address" id="address" class="findaddress" placeholder="Postal code"/>
<input type="button" name="addressbutton" class="addressbutton" value="Find" id="findaddress" onclick="javascript:hello()"/>
<input type="text" name="address2" id="address2" class="findaddress" placeholder="Line 1"/>
<input type="text" name="address3" id="address3" class="findaddress" placeholder="Line 2"/>
<input type="text" name="address4" id="address4" class="findaddress" placeholder="Line 3"/>
<input type="text" name="address5" id="address5" class="findaddress" placeholder="Line 4"/>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.addressbutton').click(function(){
ss = document.getElementById("address").value;
//alert(ss);
$.ajax({
url: 'findaddress.php',
type: 'post',
data: {address:ss},
success: function(response){
var replay = response.postal_code;
alert(replay);
document.getElementById('address').innerHTML = response.postal_code;
document.getElementById('address2').innerHTML = response.route;
document.getElementById('address3').innerHTML = response.locality;
document.getElementById('address4').innerHTML = response.postal_town;
document.getElementById('address5').innerHTML = response.administrative_area_level_2;
}
});
return false;
}); //added closing brace and bracket
});
</script>
</form>
You are not sending data correctly ..
if you want to get value of address in php which is post from ajax do this
data: { address: ss}, //
And Either add dataType:'json' there in your ajax or use jsonParse(response)
you get a string there at your response you cannot directly use response.postal_code;
In this case, you want to make sure to define the type of response from the server. I like to place dataType:'json' in my $.ajax calls. Then in your PHP code, make sure to add a header of type application/json. This will make a difference with some browsers. I like to read the Response Preview with Google Chrome. It will automatically parse the response; especially helpful with debugging.
header('Content-type: application/json');
echo json_encode($account_json);
exit;
I have an alert box that keeps prompting "Image uploaded", even though $imagename is empty.
Here's the script:
<script>
function ajax_post1(ca){
var cat = ca;
var name = document.getElementById("name").value;
var desc = document.getElementById("description").value;
var key = document.getElementById("keyword").value;
var image = document.getElementById("image").value;
if ($.isEmptyObject(image)) {
alert('pls upload your image')
} else {
alert(' image uploaded ')
}
var myData = 'content_ca='+ cat + '&content_desc='+desc+ '&content_key='+key+ '&content_name='+name;//build a post data structure
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "uploadsignuppackageresponse.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//$("#imagebox").append(response);
//$("#contentText").val(''); //empty text field on successful
//alert("haha");
}, error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
};
</script>
This is the main page:
<?php
$sql1 = mysql_query ("SELECT * FROM dumimage WHERE email = '$user_signup' AND cat='company' ");
$row = mysql_fetch_array($sql1);
$imagename = $row['name'];
?>
Name:
<input id="name" type="text" ></input>
<input id="image" type="hidden" value="<?php echo $imagename ?> "></input>
Description
<textarea id="description" rows="7" cols="42"></textarea>
Keywords:
<input id="keyword" type="text" placeholder="3 Maximum Keywords" ></input>
<input type="submit" value="Upload" class="pre" style="float:left; onClick="ajax_post1('company')">
Try this to see if your objects empty
if (image.length < 1) {
alert('pls upload your image')
} else {
alert(' image uploaded ')
}
Try to replace this line:
if ($.isEmptyObject(image)) {
With this one:
if (image != '') {
You also have to correct your php code because you have closed the bracket in the wrong place and you are missing a semicolon:
<input id="image" type="hidden" value="<?php echo $imagename;?>"></input>
I'm trying to send a form's data using jQuery. However, data does not reach the server and it keeps using the GET function to get ./?page=game&mode=search&type=private and it keeps getting that page and doesn't stop getting it. Can you please tell me what i'm doing wrong?
Php:
if (isset($_GET['type'])) {
$type = $secure->clean($_GET['type']);
} else {
$type = '';
}
if ($type == 'private') {
if ( isset($_POST['submit'])) {
$name = $secure->clean($_REQUEST['name']);
$checkuser = $db->fetch("SELECT * FROM accounts WHERE name == '$name''");
if ($checkuser) {
$data ='<h1> The user you searched for does not exist. </h1>
<a class="goback message" href="#">Continue</a>';
}
} else {
$checkMatch = $db->query("SELECT * FROM accounts WHERE `id` = '".$account['id']."'");
while ($info = mysql_fetch_array($checkMatch)) {
$status = $info['status'];
$gameid = $info['gameid'];
}
if($status = 'NULL') {
$data ='<h1> Who do you want to battle against? </h1><br />
<form action="" method="post" id="form-pb" name="pb" target="_self" >
USERNAME:<input name="name" type="text" size="40" maxlength="40" />
<input name="submit" type="submit" value="Search"/>
</form>
<a class="goback" href="#">Cancel</a>';
}
}
echo $data;
exit;
}
Javascripit
case 'submit':
$.post('./?page=game&mode=search&type=private', $("#form-pb").serialize(), function(data){
var $response=$(data);
var error = $response.filter('h3').text();
$('.search').html(data);
if(!error){
match = setInterval(function(){
if(!$('.search').length){
$('#main_container').prepend('<div id="popup"><div class="opacity"></div><div class="search"></div></div>');
}
$('.search').load('./?page=game&mode=search&type=private', function(){
var meta = $('#stopMe').attr('content'); var meta = $('#stopMe').attr('content');
if(meta){
meta = meta.split("URL="), meta = meta[1];
window.location = meta;
}
});
},1000);
}
});
break;
And the form is
<form action="" method="post" id="form-pb" name="pb" target="_self" >
USERNAME:<input name="name" type="text" size="40" maxlength="40" />
<input name="submit" type="submit" value="Search"/>
</form>
You need to fix this:
$checkuser = $db->fetch("SELECT * FROM accounts WHERE name == '$name''");
to something like that:
$checkuser_res=$db->query("SELECT * FROM accounts WHERE name == '$name''");
if($checkuser_res->num_rows==1)
{
// The user exists
}
else
{
// The user doesn't exist
}
For this I'm assuming you are using mysqli, if it is a special mysql wrapper, it could be possible that your code also works.
Hi everyone i'm creating the "Billing address" "Delivery address" form.
When someone fills out the billing address details and the delivery is the same, I would like to save a person to tick the box to populate the details.
I tried to validate it with javascript and php which are on the same page above the form(not in the head tag) with no joy.
*Script updates the database *, ajax doesn't get the echo from php which is another thing that I can not figure out. So I have a couple of issues , don't know, maybe something interferes on the page.
I just want to get the idea of how it should work .
When I hit "submit"- AJAX sends the variables to PHP, then PHP updates database and echos the string, which is passed back to AJAX. But AJAX can't see it, the error strings I have in the AJAX code are not displayed, the only one that displays is "Some error occured " (I even changed it for "successfully updated" at some stage cause the database is updated:))
Any help would be very much appreciated
Page called myaccount.php
<?php
// AJAX CALLS THIS CODE TO EXECUTE
if(isset($_POST['p'])||isset($_POST['a1'])||isset($_POST['a2'])||isset($_POST['c'])||isset($_POST['co'])||isset($_POST['con'])||isset($_POST['da1'])||isset($_POST['da2'])||isset($_POST['dc'])||isset($_POST['dco'])||isset($_POST['addcheckbox'])){
require_once('./includes/mysql_connect.php');
$p = mysql_real_escape_string(trim($_POST['p']));
$a1 = mysql_real_escape_string(trim($_POST['a1']));
$a2 = mysql_real_escape_string(trim($_POST['a2']));
$c = mysql_real_escape_string(trim($_POST['c']));
$co = mysql_real_escape_string(trim($_POST['co']));
$da1 = mysql_real_escape_string(trim($_POST['da1']));
$da2 = mysql_real_escape_string(trim($_POST['da2']));
$dc = mysql_real_escape_string(trim($_POST['dc']));
$dco = mysql_real_escape_string(trim($_POST['dco']));
if(isset($_POST['addcheckbox'])=='ticked'){
$da1 = mysql_real_escape_string(trim($_POST['a1']));
$da2 = mysql_real_escape_string(trim($_POST['a2']));
$dc = mysql_real_escape_string(trim($_POST['c']));
$dco = mysql_real_escape_string(trim($_POST['co']));
}
$sql = "UPDATE customers SET address_1='$a1', address_2='$a2', phone='$p', city='$c', county='$co', country='$con', del_ad_1='$da1', del_ad_2='$da2', del_city='$dc', del_county='$dco' WHERE id_cust='$id'";
$query = mysql_query($sql);
if(!$query){
echo 'success';
exit();
}else{
echo 'not_updated';
exit();
}
}
?>
this is the javascript
<script type="text/javascript" language="javascript">
function changeaddress(){
var p = _("phone").value;
var a1 = _("address_1").value;
var a2 = _("address_2").value;
var c = _("city").value;
var co = _("county").value;
var con = _("country").value;
var da1 = _("deladdress_1").value;
var da2 = _("deladdress_2").value;
var dc = _("delcity").value;
var dco = _("delcounty").value;
//checkbox
if(document.getElementsById("addcheckbox").checked){
var da1 = a1;
var da2 = a2;
var dc = c;
var dco = co;
}else{
var da1 = _("deladdress_1").value;
var da2 = _("deladdress_2").value;
var dc = _("delcity").value;
var dco = _("delcounty").value;}
//ajax call
if((p!=""||p=="") && (a1!="") && (a2!=""||a2=="") && (c!="") && (co!="")){
//_("changeaddbtn").style.display = "none";
_("status").innerHTML = 'updating your details ...';
var ajax = ajaxObj("POST", "/myaccount.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var response = ajax.responseText;
if(response == 'success'){
_("changeaddressform").innerHTML = '<h3>Address is updated, check the first tab!!</p>';
} else if (response == 'not_updated'){
_("status").innerHTML = "An error occured , the details were not updated!";
} else {
_("status").innerHTML = "Some error occured!";
}
}else{
_("status").innerHTML = "loading...";}
}
ajax.send("p="+p+"&a1="+a1+"&a2="+a2+"&c="+c+"&co="+co+"&da1="+da1+"&da2="+da2+"&dc="+dc+"&dco="+dco)
;
}
}
</script>
this is the Billingpart
Address*
--------------------
<input class="input_field" type="text" size="40" id="address_1" name="address_1" value="<?php echo ''.$get_row['address_1'].''; ?>"/>
Address
----------------------
<input class="input_field" type="text" size="40" id="address_2" name="address_2" value="<?php echo ''.$get_row['address_2'].' '; ?>"/>
City/Town*
<input class="input_field" type="text" size="40" id="city" name="city" value="<?php echo ''.$get_row['city'].' '; ?>"/>
County*
-----------------------
<input class="input_field" type="text" size="40" id="county" name="county" value="<?php echo ''.$get_row['county'].' '; ?>"/>
<p><button id="changeaddbtn" class="submit_btn" onclick="changeaddress()" >Submit Changes</button>
Delivery
<input type="checkbox" name="addcheckbox" id="addcheckbox" value="ticked" /> Same as billing </p>
"/>
Address
-------------------------------
<input class="input_field" type="text" size="40" id="deladdress_2" value="<?php echo ''.$get_row['del_ad_2'].' '; ?>"/>
City/Town*
-------------------------
<input class="input_field" type="text" size="40" id="delcity" value="<?php echo ''.$get_row['del_city'].' '; ?>"/>
County*
-------------
<input class="input_field" type="text" size="40" id="delcounty" value="<?php echo ''.$get_row['del_county'].' '; ?>"/>
-----------------------------------------------
<p><button id="changeaddbtn" class="submit_btn" onclick="changeaddress()" >Submit Changes</button></p>
<p id="status"></p>
<p id="status1"></p>
<p id="status2"></p>
<p id="status3"></p>
here is my answer
function checkCheckbox(){
if (_("checkbox1").checked == true){
_("deladdress_1").value = _("address_1").value;
_("deladdress_2").value = _("address_2").value;
_("delcity").value = _("city").value;
_("delcounty").value = _("county").value;
_("delcountry").value = _("country").value;
}else{
_("deladdress_1").value = "";
_("deladdress_2").value = "";
_("delcity").value = "";
_("delcounty").value = "";
_("delcountry").value = "";
}
}