I need a help with this script ($.ajax()) - php

Ajax:
$.ajax({
url: 'process.php',
type: 'post',
data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(),
dataType: 'json',
success: function(data){
if(data.success)
{
location.href = data.redirect;
}
else
{
alert(data.message);
}
}
});
And here is process.php code:
<?
$data = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_POST['loginName'] == "test" && $_POST['loginPass'] == "test")
{
$data['redirect'] = "home.php";
$data['success'] = true;
echo json_encode($data);
}
else
{
$data['message'] = "<div id=Message>Your info is wrong...</div>";
$data['success'] = false;
echo json_encode($data);
}
}
?>
Sorry, but I'm from the Czech Republic and I don't speak english :D

Your data: misses a & right before loginPass=, which would lead to a garbled request. But maybe you should give jQuery an data object there anyway (it takes care of proper url encoding):
type: 'POST',
data: {loginName: $("#loginName").val(), loginPass: $("#loginPass").val()},
A second problem might be the lack of content-type in the php script. Add following on top (just to be sure this isn't why the result goes ignored):
<?php
header("Content-Type: application/json");
Another thing: You need more braces in the if statement, because && has higher precedence than the == comparison:
if(($_POST['loginName'] == "test") && ($_POST['loginPass'] == "test")) {
Since it is seemingly a PHP error, you must turn on error_reporting(E_ALL) and display_errors in the php.ini; If you still get no content returned from your URL, then add a print 'test123'; on top. And/or remove the test for REQUEST_METHOD (this adds no security anyway).

Related

force-download xlsx from ajax response not working

I have this little problem with downloading my xlsx-file.
I am sending my request for the file over jquery Ajax and on the backend the data is correctly collected and assembled to a xlsx-file. So now on its way back to the frontend i am setting all the headers in preparation to force download the file, but the download never starts.
These are the response headers of my request:
Connection Keep-Alive
Content-Disposition attachment; filename="export.xlsx"
Content-Length 346420
Content-Type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Date Mon, 23 Nov 2015 13:23:30 GMT
Keep-Alive timeout=5, max=91
Server Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12
Set-Cookie <cookiesettings>
content-transfer-encoding binary
x-powered-by PHP/5.6.12
imho the download should start immediately, but nothing happens.
EDIT:
Until now I used a form submit, but the data amount is really big so the time which is needed to assemble the file is also really long and sometimes a couple of minutes or even an hour, so this was no longer possible.
So I built a java-job to build the file and startet an ajax snippet which asks for completion every second or so.
So here is my Code.
Frontend:
This is called on button-click
download: function (type, maximum) {
var
self = this,
oParams = this.oTable.oApi._fnAjaxParameters(this.oTable.fnSettings()),
aoPost = [
{ 'name': 'exportType', 'value': type },
{ 'name': 'exportMax', 'value': maximum },
{ 'name': 'handleId', 'value': self.options.handleId }
],
nIFrame, nContentWindow, nForm, nInput, i
;
// Call a self made function to get extra search parameters
// without call an data update AJAX call.
self.oTable.fnSettings().addAdditionalSearchData(oParams);
// Create an IFrame to do the request
nIFrame = document.createElement('iframe');
nIFrame.setAttribute('id', 'RemotingIFrame');
nIFrame.style.border = '0px';
nIFrame.style.width = '0px';
nIFrame.style.height = '0px';
document.body.appendChild(nIFrame);
nContentWindow = nIFrame.contentWindow;
nContentWindow.document.open();
nContentWindow.document.close();
nForm = nContentWindow.document.createElement('form');
nForm.className = 'export-table';
nForm.setAttribute('method', 'post');
// Add POST data.
var formData = {};
for (i = 0; i < aoPost.length; i++) {
nInput = nContentWindow.document.createElement('input');
nInput.setAttribute('name', aoPost[ i ].name);
nInput.setAttribute('type', 'text');
nInput.value = aoPost[ i ].value;
nForm.appendChild(nInput);
formData[aoPost[ i ].name] = aoPost[ i ].value;
}
// Add dataTables POST.
for (i = 0; i < oParams.length; i++) {
nInput = nContentWindow.document.createElement('input');
nInput.setAttribute('name', oParams[ i ].name);
nInput.setAttribute('type', 'text');
nInput.value = oParams[ i ].value;
nForm.appendChild(nInput);
formData[oParams[ i ].name] = oParams[ i ].value;
}
nForm.setAttribute('action', '/service/exportTableData');
// Add the form and the iFrame.
nContentWindow.document.body.appendChild(nForm);
// Send the request.
//nForm.submit();
// Send the request.
var form = $(nContentWindow.document.body).find('form.export-table');
var jobId = 0;
form.ajaxForm(
{
'showMessagesOnSuccess': false
},
{
'getData': function () {
return formData;
}
}
).data('ajaxForm').submit();
}
The Ajax request on submit:
$.ajax({
type: 'POST',
url: self.handler.getServiceUrl(),
timeout: GLOBALS.AJAX_REQUEST_TIMEOUT,
cache: false,
data: (<get the Data>)
,
success: function (response) {
if (response.success === true) {
// Check if we have to wait for a result.
if (response.jobId !== undefined && response.jobId !== 0) {
self.checkJobStatus(response.jobId);
} else {
<success - show some messages>
}
} else {
self.handler.error(response);
}
},
error: function () {
<Show error Message>
}
});
The CheckJobStatus:
checkJobStatus: function (jobId) {
var self = this;
$.ajax({
type: 'POST',
timeout: GLOBALS.AJAX_REQUEST_TIMEOUT,
cache: false,
data: { 'jobId': jobId },
url: self.handler.getServiceUrl(),
success: function (response) {
if(response !== null && response.data !== undefined) {
if (response.data.isFinished === true) {
if (response.success === true) {
// Check if we have to wait for a result.
self.handler.success(response);
} else {
self.handler.error(response);
}
} else if (response.success === true && response.data !== null) {
setTimeout(
function () {
self.checkJobStatus(jobId);
},
500
);
} else {
Helper.logFrontendError();
}
} else if (response !== null && response.success === true) {
setTimeout(
function () {
self.checkJobStatus(jobId);
},
1000
);
} else {
Helper.logFrontendError();
}
},
error: function (response) {
Helper.logFrontendError();
}
});
}
Backend - php:
(...)
if ($action == 'exportTableData' || $action == 'exportChartData') {
$responseData = $service->execute();
if(isset($responseData->data['contentType']) && $responseData->data['contentType'] != null && isset($responseData->data['data'])) {
$this->sendTextData($responseData->data['contentType'], $responseData->data['data']);
} else {
$this->sendJsonData($responseData);
}
} else {
$this->sendJsonData($service->execute());
}
(...)
private function sendTextData($contentType, $data) {
$this->set('filename', 'export.xlsx');
$this->set('data', $data);
$this->response->type($contentType);
$this->render('/Layouts/excel', 'excel');
}
(...)
$handlerResult = new HandlerResult();
if($dataServiceResult == null) {
$service = new DataService();
$dataServiceResult = $service->exportTableData(
$controller->Auth->User('id'),
json_encode($request->data),
null
);
} else {
if ($dataServiceResult->header->resultKey == 0) {
$handlerResult->wsData['data'] = $dataServiceResult->data;
$handlerResult->wsData['contentType'] = $dataServiceResult->contentType;
}
}
$handlerResult->wsResultHeader = $dataServiceResult->header;
return $handlerResult; // ++++ this result returns to the first codeblock in this section ++++
Backend - java - This is where the File is assembled:
(...)
if (jobId > 0) {
FrontendJobStatus status = FrontendJobQueue.getJobStatus(context.userId, jobId);
this.result = (WSExportTableDataResult) status.getResult();
logger.info((this.result.data == null) ? "ByteArray is EMPTY" : "ByteArray is NOT EMPTY");
} else {
this.jobId = FrontendJobQueue.addJob(this.context.userId, new ExportTableDataJob(this.context, this.postData));
this.result.header.jobId = this.jobId;
}
(...)
The Jop:
<Workbook assembly>
ByteArrayOutputStream out = new ByteArrayOutputStream();
wb.write(out);
this.result.data = out.toByteArray();
this.result.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// this.result.contentType = "application/vnd.ms-excel";
this.result.setResultHeader(APIConstants.RESULT_SUCCESS);
Layout/excel:
<?php
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
ob_clean();
echo $data;
EDIT 2:
So I tried to open a new window on success with the Data, and i could start the download, but the file ist no valid xlsx File anymore.
var reader = new FileReader();
var blob = new Blob([response.responseText], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
reader.readAsDataURL(blob);
reader.onloadend = function (e) {
window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no', '_blank');
}
Any Ideas?
After a lot of research i found this site and the essence of its statment is that jquery ajax does not support receiving binary data, but provides a solution for implementing plain xhr request which support blob transfer.
The Site:
http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
To expand on my comment, instead of trying to send back binary data via ajax, simply save to a temp file , send the file reference back to js. On receiving the file reference, simply set window.location.href to point to a filereading endpoint, passing the file reference. I have done this a few times and it works fine even on ancient browsers:
$('#start').click(function(){
$.post('/createfile.php', {some:data}, function(response){
if(response.started){
pollFile(response.fileId);
}
});
);
function pollFile(fileId){
$.get('/filestatus.php?fileid=' + fileId, function(response){
if(response.fileCompleted){
window.location.href = '/downloadfile.php?fileid=' + fileId;
}else{
setTimeout('pollFile', 5000, fileId);
}
});
}
//createfile.php
$fileId = uniqid();
SomePersistentStorage::addJob($fileID);
//start file job here, code should run in a seperate process/thread, so
//either use a job queue system, use shell_exec or make an http request,
//then once job is queued/started:
header('Content-Type: application/json');
echo json_encode(['started'=>true, 'fileId'=>$fileId]);
//processjob.php - the file that does the work, could be your java
//program for example, just using php here for consistency
//after file is done
file_put_contents($filepath, $data);
SomePersistentStorage::updateJob($fileID, true);
//filestatus.php
$fileId = $_GET['fileid'];
header('Content-Type: application/json');
echo json_encode(['fileCompleted'=>SomePersistentStorage::isJobCompleted($fileID)]);
//downloadfile.php
$fileId = $_GET['fileid'];
$filepath = 'tmp/' . $fileId . '.tmp';
//correct headers here, then
readfile($filepath);
unlink($filepath);
If you dont want to imediatly delete the file, then you could just run a cron to delete files in the specific folder, that are older than x.

PHP json response not working

I am doing an ajax update. I just want a response of success or failure so I know how to handle some things in the front end. Problem is it isn't working. Brand new to all of this.
$('.delete-template-popup .confirm').on('click', function() {
var templateName = $('.loaded-template-name').html();
var templateArray = {};
templateArray.templateName = templateName;
var JSONObject = [templateArray];
var templateJson = JSON.stringify(JSONObject);
$.ajax({
url: 'http://localhost/ds-layouts/public/delete-template.php',
type: 'post',
data: {"templatePHP" : templateJson},
success: function(data) {
console.log(data)
if (data.status == "success") {
console.log(1)
}
// if (data.status == "success") {
// closePopup($('.delete-template-popup'));
// window.location.replace("http:////localhost/ds-layouts/public/manage-layouts.php");
// } else {
// $('.delete-template-popup .error').show().html('An error occurred processing your request. Please try again. If this error persists contact blah.');
// }
}
});
});
and the php
if ($flag) {
//mysqli_commit($connection);
if ($debug) {
echo "pass";
echo "\r\n";
}
//$_SESSION["message"] = "Template delete was successful.";
//header('Content-Type: application/json');
header('Content-Type: application/json; charset=UTF8');
echo json_encode(array('status' => 'success'));
} else {
if ($debug) {
echo "fail";
echo "\r\n";
}
//mysqli_rollback($connection);
// header('Content-Type: application/json');
// echo json_encode(array('status' => 'failure'));
}
So the deal is I am getting into the if block of the php statment fine. If I have the header part of the block I get all of my echo statements passed properly and I can read them in Chromes developer console. The moment I uncomment the header statement nothing works. This is for either one of $flag cases true or false.
I have this same type of script in another area and it works absolutely fine. Don't mind the comments. I was just commenting things out as a way to figure out where things were breaking. That is how I determened the header was causing it.
Maybe adding the dataType: "json", to your AJAX request object will help?
try this php
header('Content-Type: application/json'); //must be FIRST output.
if ($flag) {
//mysqli_commit($connection);
if ($debug) {
echo json_encode(array('debug' => 'pass'));
}
else
{
echo json_encode(array('status' => 'success'));
}
} else {
if ($debug) {
echo json_encode(array('debug' => 'fail'));
}
else
{
//mysqli_rollback($connection);
echo json_encode(array('status' => 'failure'));
}
}
I've changed the debug blocks to return json, since turning on debug will break the ajax anyway.
As the answer was posted as a comment I can't mark the answer as fixed. I am going to mark this answer as the what fixed the issue:
"The header must be before echo – user4035"
Thank you user4035 for letting me know about the header being before any echos aka before any printed form of html from the server...I should have known that.

#mention and text or no #mention and text

I'm having a little issue with my php file and wondering if somebody can take a look.
If I update with an #mention and some text with the php below it will update the database and output the ajax. If it doesn't have an #mention and just text, it outputs nothing. How can I rectify the code to do both.
They are both contained with $_POST['newmsg'];
I have yet to escape my variables to prevent SQL injection.
PHP:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
session_start();
require_once "rawfeeds_load.php";
include_once "include/functions.youtube.php";
?>
<?
if(isset($_SESSION['id'])){
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
if(isset($_POST['toid'])){
if($_POST['toid']==""){$_POST['toid']=$_SESSION['id'];}
if(isset($_POST['newmsg'])&& isset($_POST['toid'])&& isset($_POST['privacy'])&& isset($_POST['red'])){
$_POST['newmsg']=str_replace('#'.$_POST['red'].'',''.$_POST['red'].'', $_POST['newmsg']);
$date=date('y:m:d H:i:s');
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}else{
rawfeeds_user_core::create_streamitem("3",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}
}
}
PHP USER_CORE
public function create_streamitem($typeid,$creatorid,$content,$ispublic,$targetuser,$date){
global $mysqli;
$content = $content;
// $content = strip_tags($content);
if(strlen($content)>0){
$date=date('y:m:d H:i:s');
$insert = "INSERT INTO streamdata(streamitem_type_id,streamitem_creator,streamitem_target,streamitem_timestamp,streamitem_content,streamitem_public) VALUES ($typeid,$creatorid,$targetuser,'$date','$content',$ispublic)";
$add_post = mysqli_query($mysqli,$insert) or die(mysqli_error($mysqli));
$last_id = mysqli_insert_id($mysqli);
if(!($creatorid==$targetuser)){
$fromuser=rawfeeds_user_core::getuser($creatorid);
rawfeeds_user_core::add_notification(2,$_POST['toid'],$fromuser['id'],$fromuser['fullname']." posted a status on your wall","../singlepoststreamitem.php?sid=$last_id");
$_SESSION['id']==$content;
}
return;
}else{
return false;
}
}
AJAX
$("form#myforms").submit(function(event) {
event.preventDefault();
var content = $(this).children("#toid").val();
var newmsg= $(this).children("#newmsg").text();
var username = $(".red").attr("href");
var privacy = $("#privacy").val();
$.ajax({
type: "POST",
url: "insert.php",
cache: false,
dataType: "json",
data: { toid: content, newmsg: newmsg, privacy: privacy, red: username },
success: function(response){
Move the check for $_POST['red'] out of the main check:
if(isset($_POST['newmsg'])&& isset($_POST['toid'])&& isset($_POST['privacy'])){
// remove $_POST['red'] here -^
if (isset($_POST['red'])) { // check it here, otherwise your insert will not happen if $_POST['red'] is empty.
$_POST['newmsg']=str_replace('#'.$_POST['red'].'',''.$_POST['red'].'', $_POST['newmsg']);
}
$date=date('y:m:d H:i:s');
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}else{
rawfeeds_user_core::create_streamitem("3",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}
}

Jquery, php ajax post 500 Internal Server Error returns

I have some problem with jquery ajax & php. I'm not good in php, but I have to create a login page with php.
The promblem is, when I try to get some information from the server I get server error insted of the value.
Here is my php code (if someone know better method to create login on server side, please correct me):
<?php
//$link = mysql_connect('localhost', 'root', '') or die('A kapcsolódás nem sikerült: '+mysql_error());
$link = mysql_connect("127.0.0.1", "qm", "soR624gA") or die("Nem sikerült kapcsolódni az adatbázishoz!"+mysql_error());
mysql_query("SET NAMES UTF8");
mysql_select_db("qm", $link);
$uname = mysql_real_escape_string($_POST['name']);
$pass = mysql_real_escape_string($_POST['pass']);
$fetch = mysql_query("SELECT * FROM felhasznalok WHERE nev ='{$uname}' AND jelszo = Sha1('{$pass}')") or die(mysql_error());
if (mysql_num_rows($fetch) == 1) {
$a = array();
$['true'] = 'true';
echo json_encode($a);
}else{
$a = array();
$['true'] = 'true';
echo json_encode($a);
}
?>
And here is the code of the login on the client side:
function handleLogin(){
var _url = preUrl + "login.php";
var name = $("#loginForm #name").val();
var pass = $("#loginForm #pass").val();
$.ajax({
type: 'POST',
url: _url,
data: {name: name, pass: pass},
dataType: 'jsonp',
beforeSend: function(){
if((!name) || (!pass)){
notify('error','Kérlek tölts ki minden adatot!');
return false;
}else{
$("#loginForm #loginBtn").prop("disabled", true);
}
},
success: function(data){
if(data[0].true == 'true'){
window.localStorage["username"] = name;
window.localStorage["password"] = pass;
$.mobile.changePage("#wall",{transition:"slide", reverse:false});
}else{
$('#loginForm #name').val("");
$('#loginForm #pass').val("");
notify('error','Hibás adatok!');
}
},
error: function(err){
//átírni ha a cordovajs be lesz szúrva!!!
alert('Hiba: '+err.message);
}
});
$("#loginForm #loginBtn").prop("disabled", false);
return false;
}
I tried it out on different servers but nothing changed. I only get the error.
You made a typo:
$['true'] = 'true';
Should probably be
$a['true'] = true;
(note the $ a )
Also note that whether your login would succeed or not, it will always fill that 'true value' with true. Looking at your Javascript, that's not what you want. Consider setting it on false in your else statement.
learn basic php: $['true'] = 'true'; is a flat-out syntax error. this is the most likely cause of your server 500 error.
Add string like that to see errors in your php script:
error_reporting(E_ALL);
ini_set('error_log', 'path_to_log_file');
ini_set('log_errors_max_len', 0);
ini_set('log_errors', true);

How to hide a email form when it gets response from JSON

I am trying to create an email form with the fields validation, but I'm having trouble with my jQuery script. The script gets message response from a PHP script where I use json_encode(). When PHP response appears, the email form should disappear and reappear in the case that the it gets an error or definitely disappear in the case that email is sent.
Can someone help me please? I don't understand where I made a mistake. Thank you.
p.s. Sorry for my English, it's a bit rusty.
JavaScript:
jQuery(document).ready(function(){
jQuery("#contactform").submit(function(){
jQuery.ajax({
type: "POST",
url: "email.php",
data: jQuery("#contactform").serialize(),
dataType: "json",
success: function(msg){
jQuery("#load").fadeIn();
jQuery("#contactform").hide();
jQuery("#result").removeClass('error');
jQuery("#result").addClass('success');
jQuery("#result").addClass(msg.status);
jQuery("#result").html(msg.message);
},
error: function(){
jQuery("#result").removeClass('success');
jQuery("#result").addClass('error');
jQuery("#result").html("There was an error submitting the form. Please try again.");
}
});
return false;
}); });
PHP:
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
include ('lang.php');
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['message'];
if ((isset($_POST['name']) && !empty($_POST['name'])) &&
(isset($_POST['email']) && !empty($_POST['email'])) &&
(isset($_POST['message']) && !empty($_POST['message']))) {
$email_exp = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i";
if(preg_match($email_exp,$email)) {
// Send Email
$to = ' ';
$subject = ' ';
$message = " $comment ";
$headers = "From: " . $email . "\r\n";
'Reply-To: noreply# localhost' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
$lang['status'] = 'success';
$lang['message'] = $lang['sendmail'];
$lang['message'];
} else {
$lang['status'] = 'error';
$lang['message'] = $lang['errormail'];
$lang['message'];
}
} else {
$lang['error'] = 'error';
$lang['message'] = $lang['errorform'];
$lang['message'];
}
//send the response back
echo json_encode($lang);
?>
Maybe something like this?
jQuery.ajax({
type: "POST",
url: "email.php",
data: jQuery("#contactform").serialize(),
dataType: "json",
success: function(msg){
if (msg == success) {
jQuery("#load").fadeIn();
jQuery("#contactform").hide();
jQuery("#result").removeClass('error');
jQuery("#result").addClass('success');
jQuery("#result").addClass(msg.status);
jQuery("#result").html(msg.message);
} else {
jQuery("#load").fadeIn();
jQuery("#contactform").show();
jQuery("#result").removeClass('error');
jQuery("#result").addClass('success');
jQuery("#result").addClass(msg.status);
jQuery("#result").html(msg.message);
}
}
)};
Hi, thank you for your reply. I just solved my problem for myself!
It works, but I'm sure that my code might be improved. Please let me know if you see any mistake or if you have advices to give me. Thank you!
jQuery(document).ready(function(){
jQuery("#contactform").submit(function(){
jQuery(this).fadeOut();
jQuery("#load").fadeIn();
jQuery.ajax({
type: "POST",
url: "email.php",
data: jQuery("#contactform").serialize(),
dataType: "json",
success: function(msg){
if (msg.status == 'success') {
jQuery("#load").hide();
jQuery("#result").removeClass('error');
jQuery("#result").addClass('success');
jQuery("#result").addClass(msg.status);
jQuery("#result").html(msg.message);
} else {
jQuery("#load").hide();
jQuery("#contactform").fadeIn();
jQuery("#result").removeClass('success');
jQuery("#result").addClass('error');
jQuery("#result").addClass(msg.status);
jQuery("#result").html(msg.message);
}
},
error: function(){
jQuery("#result").removeClass('success');
jQuery("#result").addClass('error');
jQuery("#result").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
I would imagine that you could call a jQuery getJSON() call.
This might work, though you'll probably have to update your version of jQuery if you're still using the jQuery(selector) nomenclature.
$(document).ready(function(){
$.getJSON('email.php', $('#contactform').serialize(), function(data){
// This part completely depends on the format of your returned data.
// I personally would return error codes.
// Maybe something like this.
if(data.status==='error'){
$('#contactform').hide();
setTimeout(function(){$('#contactform').show()}, 1000);
}else if(data.status==='success'){
$('#contactform').hide();
}
});
});

Categories