1

I’ve a javascript file I’ve been using as an template for a site I’m working on and in that script there is a simple form validation where it – if no error occur – sends data to an PHP page called contact.php.

But I’m unsure on how I “grab” the data send from the JavaScript in my PHP site? The contact.php works – that is, if I, in my form, direct it directly to contact.php it sends the mail without problem. In that file I send the variables like this: $name = $_POST['formName']; and so on and in the end send it to the mail function.

The code in my JavaScript file where it sends the data and display a “successful” message on the same page is:

$.post("contact.php",
{ formFrom: FromValue, formName: NameValue, formMessage: messageValue },
function(data){
$("#loadingImage").fadeOut("fast", function() {                
$("#loadingImage").before('<p>The message has been sucessfully send. Thank you!</p>');      
});
}
);

The NameValue, messageValue, FromValue is set in the form validation like this var messageValue = $("#formMessage").val();.

Any help would be very much appreciated.

Sincere
- Mestika

Emil Devantie Brockdorff
  • 4,724
  • 12
  • 59
  • 76

1 Answers1

2

Just use the jQuery AJAX call (this syntax is from jQuery 1.5.X):

$.ajax({
    type: 'POST'
    url: urlString,
    data: {formFrom: FromValue, formName: NameValue, formMessage: messageValue}
}).success(function(data, status, xhr) {
    var obj = eval('(' + data + ')');
    //response as object
});

To send JSON back to the JavaScript, use this function in your PHP:

http://php.net/manual/en/function.json-encode.php

One other thing: as a rule of thumb, it's poor practice to use variable names like "FromValue." Initial capitalization is supposed to be used for class names, not variables (JavaScript developers borrowed this practice from Java).

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83