Jump to content
Sign in to follow this  
exceedinglife

Php jquery call not finishing ajax-success: php create file and email

Recommended Posts

Hello all

I have a php and jquery/ajax call I am using to create a file/send an email. I get all the contents from my textboxes but I want a message to display on the screen afterwards being success or fail. In my .ajax call My call is exiting right before the ‘success:’  part. Why is my call not succeeding? Any tips/help will be appreciated

Thank you

Html page just a form with a submit button
$(document).ready(function () {
    var form = $("#formData");
    
    $(form).on("submit", function (event) {
        event.preventDefault();
        $.ajax({
            type: "post",
            url: "file.php",
            data: $(this).serialize(),
            beforeSend: function () {
                $("#status").html('<span style="color:red;">Loading everything actually creating a .TXT file of contents...</span>')  //--works
            },
            success: function (data) { 
                var responseMsgType = "alert-" + data.type;
                var responseMsgText = data.message;
                // message below
                var alertBox = '<div class="alert ' + responseMsgType + ' alert-dismissable"><button type="button" class="close" ' +
                    'data-dismiss="alert" aria-hidden="true">&times;</button>' + responseMsgText + '</div>';
                if (responseMsgType && responseMsgText) {
                    $(form).find(".successArea").html(alertBox);
                    $(form)[0].reset();
                }
            }
        });
        return false;
    });
<?php
$controls = array('txtName' => 'Name', 'txtEmail' => 'Email', 'txtSubject' => 'Subject', 'txtMessage' => 'Message');
try {
	if(count($_POST)==0) { throw new \Exception ('Contact Form Message is empty'); }

	$headers = array('Content-Type: text/plain; charset="UTF-8";',
					 'From: ' . $email,
					 'Reply-To: ' . $email,
					 'Return-Path: ' .$email);

	$emailMessage = "You have a new message from your contact form" . PHP_EOL;
	$emailMessage .= "-------------------------------------------------------" . PHP_EOL;

	foreach($_POST as $key => $value){
        if(isset($controls[$key])) {
            $emailMessage .= "$controls[$key]: $value". PHP_EOL;
        }
    }
$mailMsg = "email6.txt";
	if(file_exists($filename) == false) {
		$fh = fopen($mailMsg, "w");
		fwrite($fh, $headers);
		fwrite($fh, $emailMessage);
		fclose($fh);
	} else {
		$fhexists = fopen($filename, "a");
		fwrite($fhexists, $content);
		fclose($fhexists);
	}

	$responseMessage = array("type" => "success", "message" => $successMessage);
}
catch (\Exception $ex) {
	$responseMessage = array("type" => "errorM", "message" => $errorMessage);
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
	$encodedJSON = json_encode($responseMessage);
	header("Content-Type: application/json");
	echo $encodedJSON;
} else {
	echo $responseMessage["message"];
}

 

Share this post


Link to post
Share on other sites

According to the documentation, the success function will only run when the call succeeds - you need to check for errors using the error function. What does the network tab of your developer tools have to say?

Share this post


Link to post
Share on other sites

I have no errors in my developer tools on chrome and everythng runs I will check error in ajax

Share this post


Link to post
Share on other sites

There probably won't be any errors in your console - everything's working fine on the client side. Check the Network tab - look for the ajax call to 'file.php', then see what the return is.

Share this post


Link to post
Share on other sites

You're not returning the success in the right format. It needs to be something like this. From the jquery ajax documentation. 

$response_array=array($data,True,XMLHttpRequestObject); 
echo json_encode($response_array); 

 

Share this post


Link to post
Share on other sites

Have you tried using

success(data) { 
console.log('Type: ' + data.type + ' Message: ' + data.message); 
}

then check console to make sure it's getting to that point. 

Share this post


Link to post
Share on other sites

Post your code here - not everyone trusts external links. In the meantime, looking at the code you've already posted, where does $filename come from?

Share this post


Link to post
Share on other sites

I got everything working now

 error: function (errorThrown) {
                //here is the status error code xhr, status, 
                console.log(errorThrown);
                alert(errorThrown);

I used this to find out what bugs I was getting.

I debugged everything now It works as I wanted it to. I do have a new question though about something else. Its something with css or Javascript so I will make a new post.

Thanks all for the help on this topic.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.