简体   繁体   中英

AJAX post call to php script not working

I cant understand why the following is not working, I am trying to call a php script to send an email, but i dont think my ajax call is calling the php script at all, I just get an error returned.

My ajax call:

        var name_field = $('#cf_name').val();
        $.ajax({
            type: 'post',
            url: 'contact.php',
            data: {'name_field' : name_field },
            dataType: 'json',
            success: function(data) {
                if(data.status == 'success')
                    alert("Thank you for subscribing!");
                else if(data.status == 'error')
                    alert("Error on query!");
            },
            error: function(err) {
                alert(err.responseText);
            }
        });

My php script:

$field_name =  isset($_POST['name_field']);
$field_email = 'name@email.com';
$field_phone = '12345';
$field_message = 'Hello World!';

$mail_to = 'emailaddress@email.com';
$subject = 'Message from a website visitor '.$field_name;

$body_message = 'This message has been sent via website:'."\n\n";
$body_message .= 'From: '.$field_name."\n\n";
$body_message .= 'E-mail: '.$field_email."\n\n";
$body_message .= 'Phone Number: '.$field_phone."\n\n";
$body_message .= 'Message: '.$field_message;

$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";

$mail_status = mail($mail_to, $subject, $body_message, $headers);

if ($mail_status) { 
    $response_array['status'] = 'success';  
}
else { 
    $response_array['status'] = 'error';
}
header('Content-type: application/json');
echo json_encode($response_array);

If i navigate to the url directly the php works as intended, but i can not get the ajax post to call it.

$field_name is not an actual string, it's a boolean since you used $field_name=isset($_POST[name_field']). Remove the isset().

You should check url: contact.php as you did not specify the full URL, so your post is going to a relative path. The root path will be same current script path.

See this: jQuery Ajax post cancelled i'm not a js expert but I agree with your problem being the async execution of your ajax call, since it takes a while to send an email, maybe isn't completed in time for your js

See this nice explanation about the "async" propertie in the ajax call:

What does "async: false" do in jQuery.ajax()?

And see this question/answer:

How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM