How to get response from PHP file as an array using Ajax? - javascript

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;

Related

Image upload with ajax and php after submit

I have a modal that submit some information and an image through form to database. I am working with php and javascript...well i am not so good with js so i need some help.
Work i have done so far is that i can insert data from form to db without no errors but i don't know how to start and what to do with image upload. I am working now on localhost.
I want to upload image to local folder and to automatically rename it with title that someone entered through form. So the name of image saves into table and the image in folder.
I will past the code here so if anyone can help me with code i will appreciate it.
ajax:
$(document).ready(function(){
$('form.insert-movie').on('submit', function(e) {
e.preventDefault();
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: 'POST',
data: data,
success: function (msg) {
alert("YOUR SUCCESS MESSAGE HERE");
},
error: function (msg) {
alert("Error " + msg.d.toString());
}
});
return false;
});
});
queries:
<?php
include 'config.php';
$pdo = connect();
if(isset($_POST['InputTitle'], $_POST['InputYear'], $_POST['InputDuration'], $_POST['InputDescription'], $_POST['InputGender'])) {
$InputTitle = $_POST['InputTitle'];
$InputYear = $_POST['InputYear'];
$InputDuration = $_POST['InputDuration'];
$InputDescription = $_POST['InputDescription'];
$InputGender = $_POST['InputGender'];
$InputImage = $_POST['InputImage'];
$sql = $pdo->prepare("INSERT INTO filmovi(naslov,godina,trajanje,opis,id_zanr,slika)
VALUES(:field1,:field2,:field3,:field4,:field5,:field6)");
$sql->execute(array(':field1' => $InputTitle,
':field2' => $InputYear,
':field3' => $InputDuration,
':field4' => $InputDescription,
':field5' => $InputGender,
':field6' => $InputImage));
$affected_rows = $sql->rowCount();
}
modal:
<form action="inc/queries.php" method="post" class="insert-movie" enctype="multipart/form-data">
<div class="form-group"> <!-- TITLE -->
<label for="title">Title</label>
<input type="text" class="form-control" name="InputTitle" id="InputTitle" placeholder="Enter title" required>
</div>
<div class="form-group"> <!-- YEAR -->
<label for="year">Year</label>
<input type="date" class="form-control" name="InputYear" id="InputYear" placeholder="Year" required>
</div>
<div class="form-group"> <!-- DURATION -->
<label for="year">Duration</label>
<input type="time" class="form-control" name="InputDuration" id="InputDuration" placeholder="Duration" required>
</div>
<div class="form-group"> <!-- GENDER -->
<label for="year">Gender</label></br>
<select name="InputGender">
<option>select a genre</option>
<?php
$pdo = connect();
// display the list of all members in table view
$sql = "SELECT * FROM zanr";
$query = $pdo->prepare($sql);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
?>
echo'
<option name="InputGender" value="<?php echo $rs['id'] ?>"><?php echo $rs['naziv'] ?> </option>'
<?php } ?>
echo'
</select>
</div>
<div class="form-group"> <!-- DESCRIPTION -->
<label for="year">Description</label>
<textarea class="form-control" name="InputDescription" placeholder="Description" rows="3" required></textarea>
</div>
<div class="form-group"> <!-- IMAGE -->
<label for="image">Image upload</label>
<input type="file" name="InputImage" id="InputImage">
<p class="help-block">Select image of movie.</p>
</div>
Close
First, you must handle the file upload. Examples here: http://php.net/manual/en/features.file-upload.post-method.php Second you need to figure out what you want to store in your Database.
<?php
include 'config.php';
$pdo = connect();
if(isset($_POST['InputTitle'], $_POST['InputYear'], $_POST['InputDuration'], $_POST['InputDescription'], $_POST['InputGender'])) {
$InputTitle = $_POST['InputTitle'];
$InputYear = $_POST['InputYear'];
$InputDuration = $_POST['InputDuration'];
$InputDescription = $_POST['InputDescription'];
$InputGender = $_POST['InputGender'];
$uploaddir = '/var/www/uploads/'; // Change this to be a path on your server
$uploadfile = $uploaddir . basename($_FILES['InputImage']['name']);
if (move_uploaded_file($_FILES['InputImage']['tmp_name'], $uploadfile)) {
$InputImageStorePath = $uploadfile;
$InputImage = $_FILES['InputImage']['name'];
} else {
$InputImage = "";
}
$sql = $pdo->prepare("INSERT INTO filmovi(naslov,godina,trajanje,opis,id_zanr,slika)
VALUES(:field1,:field2,:field3,:field4,:field5,:field6)");
$sql->execute(array(':field1' => $InputTitle,
':field2' => $InputYear,
':field3' => $InputDuration,
':field4' => $InputDescription,
':field5' => $InputGender,
':field6' => $InputImage));
$affected_rows = $sql->rowCount();
}
?>
I would advise using FormData for your AJAX:
$('form.insert-movie').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($('form.insert-movie')),
url = $(this).attr('action'),
method = $(this).attr('method');
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function (msg) {
alert("YOUR SUCCESS MESSAGE HERE");
// Close Modal here with .hide() ?
},
error: function (msg) {
alert("Error " + msg.d.toString());
}
});
});

How can i do the same function using Ajax

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>

Upload image and text by same form

When I upload image and text by separate form, its work well. But Its not work when I add together.
My form text upload by js and image upload by a php file.
And I think my problem in my form.
If I upload together with js, What change in my js and submit.php, which also add below.
Here is my form code that not work together
<form action="" method="post" id="cmntfrm" enctype="multipart/form-data">
<fieldset id="cmntfs">
<legend class="pyct">
What's your mind
</legend>
<input type="hidden" name="username" size="22" tabindex="1" id="author" value="'.$pname.'"/>
<input type="hidden" name="email" size="22" tabindex="2" id="email" value="'.$email.'"/>
<p><textarea name="comment" rows="10" tabindex="4" id="comment"></textarea></p>
<div id="ajaxuploadfrm">
<form action="uploadpostimg.php" method="post" enctype="multipart/form-data">
<b>Select an image (Maximum 1mb)</b>
<input type="file" name="url" id="url" />
</form>
</div>
<p><input type="submit" name="submit" value="Post comment" tabindex="5" id="submit"/></span></p>
</fieldset>
<input type="hidden" name="parent_id" id="parent_id" value="0" />
<input type="hidden" name="tutid2" id="tutid" value="'.$tutid2.'" />
</form>
js
$(document).ready(function(){
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputEmail = $("#email");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment");
var commentCountList = $("#updatecommentNum");
var error = $("#error");
error.fadeOut();
function updateCommentbox(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=update&tutid="+ tutid,
complete: function(data){
commentList.prepend(data.responseText);
commentList.fadeIn(2000);
}
});
}
function updateCommentnum(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=updatenum&tutid="+ tutid,
complete: function(data){
commentCountList.html(data.responseText);
commentList.fadeIn(2000);
}
});
}
function error_message(){
error.fadeIn();
}
function checkForm(){
if(inputAuthor.attr("value") && inputComment.attr("value") && inputEmail.attr("value"))
return true;
else
return false;
}
//on submit event
$("#cmntfrm").submit(function(){
error.fadeOut();
if(checkForm()){
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var email = inputEmail.attr("value");
var comment = inputComment.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
//we deactivate submit button while sending
$("#submit").attr({ disabled:true, value:"Sending..." });
$("#submit").blur();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=insert&author="+ author + "&url="+ url + "&email="+ email + "&comment="+ comment + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
commentList.prepend(data.responseText);
updateCommentbox();
updateCommentnum();
//reactivate the send button
$("#submit").attr({ disabled:false, value:"Submit Comment!" });
$( '#cmntfrm' ).each(function(){
this.reset();
});
}
});
}
else //alert("Please fill all fields!");
error_message();
//we prevent the refresh of the page after submitting the form
return false;
});
});
Submit.php
<?php header('Content-Type: charset=utf-8'); ?>
<?php
include("db.php");
include_once("include/session.php");
switch($_POST['action']){
case "update":
echo updateComment($_POST['tutid']);
break;
case "updatenum":
echo updateNumComment($_POST['tutid']);
break;
case "insert":
date_default_timezone_set('Asia/Dhaka');
echo insertComment($_POST['author'], $_POST['comment'], $_FILES['url']['name'], $_POST['email'], $_POST['tutid'], $_POST['parent_id'], $date = date("M j, y; g:i a"));
break;
}
function updateNumComment($tutid) {
//Detail here
}
function updateComment($tutid) {
//Detail here
}
function insertComment($username, $description, $url, $email, $qazi_id, $parent_id, $date ){
global $dbh;
//Upload image script that not work here when i try together so i took it at separate file and then tried with above form
$output_dir = "comimage/";
$allowedExts = array("jpg", "jpeg", "gif", "png","JPG");
$extension = #end(explode(".", $_FILES["url"]["name"]));
if(isset($_FILES["url"]["name"]))
{
//Filter the file types , if you want.
if ((($_FILES["url"]["type"] == "image/gif")
|| ($_FILES["url"]["type"] == "image/jpeg")
|| ($_FILES["url"]["type"] == "image/JPG")
|| ($_FILES["url"]["type"] == "image/png")
|| ($_FILES["url"]["type"] == "image/pjpeg"))
&& ($_FILES["url"]["size"] < 504800)
&& in_array($extension, $allowedExts))
{
if ($_FILES["url"]["error"] > 0)
{
echo "Return Code: " . $_FILES["url"]["error"] . "<br>";
}
if (file_exists($output_dir. $_FILES["url"]["name"]))
{
unlink($output_dir. $_FILES["url"]["name"]);
}
else
{
$pic=$_FILES["url"]["name"];
$conv=explode(".",$pic);
$ext=$conv['1'];
$user = $_SESSION['username'];
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["url"] ["tmp_name"],$output_dir.$user.".".$ext);
$pic=$output_dir.$user.".".$ext;
$u_imgurl=$user.".".$ext;
}
}
else{echo '<strong>Warning !</strong> File not Uploaded, Check image' ;}
}
//Submit main comment
if ($parent_id == 0){
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub = "Comment to";
$query = "INSERT INTO comments_lite VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
} else {
if ($parent_id >= 1){
global $dbh;
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub2 = "Reply to";
$query = "INSERT INTO comments_reply VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
}
}
}
?>
on click of submit you can put the code in js you have to make change in the js file
$.post('phpapgename.php',data:jquerydata,function(){
})
in the .php page you can put your query to submit your data.
You cannot have nested form. Try to avoid it and separate out the forms as below. And while submitting any form if you data from other form, create a hidden fields in this form and submit it.
Another suggestion: Since you're working with javascript anyway, outsource the upload-form to an invisible div and make it pop up by clicking/hovering an upload-button or entering the last field of form1 or whatever.

JS/Ajax alert box error

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>

Why is this AJAX form not submitting?

Whenever I press the "Submit Request" button within the form, no error pops up and it does not redirect me to the page which is noted in the PHP script. Any ideas as to why this is occurring?
Code from webpage w/ form:
<form id="consultation-reservation" action="actions/consultation-request.php" method="post">
<input name="fullname" type="text" placeholder="Full Name (Required)" class="mt5" />
<input name="phonenumber" type="text" placeholder="Phone Number (Required)" class="mt5" />
<input name="emailaddress" type="text" placeholder="E-Mail Address (Required)" class="mt5" />
<textarea name="comments" placeholder="Additional Comments/Questions" class="mt10"></textarea>
<p class="hidden" id="consultation-reservation-error">Please verify all required fields are complete.</p>
<a class="button" id="consultation-reservation-submit">Submit Request</a>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#consultation-reservation-submit").click(function(){
$("#consultation-reservation").submit();
});
});
$('#consultation-reservation').submit(function(e) {
register();
e.preventDefault();
});
function register()
{
jQuery.ajax({
method: "POST",
url: "actions/consultation-request.php",
data: $('#consultation-reservation').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).hide(0).slideDown(500, 'linear');
else $('#'+el).hide();
}
function error(act,txt)
{
if(txt) $('#consultation-reservation-error').html(txt);
$('#consultation-reservation-error').hide(0).slideDown(500, 'linear');
}
</script>
PHP Script which is supposed to be executed via ajax: (I am going to apply the mysql_real_escape_string to the variables containing the form data, but just haven't yet)
<?php
if(empty($_POST['fullname']) || empty($_POST['phonenumber']) || empty($_POST['emailaddress']))
{
die('{status:0,"txt":"Please verify all required fields are complete."}');
}
$name = $_POST['fullname'];
$phonenumber = $_POST['phonenumber'];
$email = $_POST['emailaddress'];
$comments = $_POST['comments'];
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['emailaddress'])))
die('{status:0,"txt":"Please Provide a Valid E-Mail Address."}');
echo '{status:1,txt:"consultation-request-successful"}';
?>
echo '{status:1,txt:"consultation-request-successful"}';
The above is invalid JSON because it doesn't use the double quotes around the txt and status key. You specified the response data type as json, so jQuery will try to parse the response as JSON, and if it fails it will run the error handler (if set) instead of the success handler.
So either add the double quotes, or build the JSON in another way:
$response = array('status' => 1, 'txt' => 'consultation-request-successful');
echo json_encode($response);
Building JSON in this way is much better because all of the quotes will be automatically handled, also special characters within the values will be escaped as necessary.

Categories