0

I'm having problems with passing variables from jQuery into PHP. I search for the solutions on the internet, and i came to the AJAX. Never used Ajax before, so i guess that the problem is known.

So i have the following code in "index.php"

$("#inviteForm").submit(function(e) {

e.preventDefault();
var emailVal = $("#email").val();

$.ajax({
 type: "POST",
 url: "processAjax.php",
 data: {email: emailVal},
 success: function(data) {
    alert(data);  
}
});
});

In form, i have one input box (for email) and a submit button (the method is POST).

In processAjax.php i have the following code

<?php
    $x = $_POST['email'];
    return $x;
?>

So if i'm correct, if the $.ajax function is OK, the alert box should pop up. But it doesn't. i've also tried alert(x); but it didn't work.

Any idea what i'm doing wrong

2
  • 1
    The absolute first thing I'd check is whether the AJAX request is actually being sent. Use Firebug (for Firefox) or the Developer Tools in other browsers to do that (all accessed by hitting the F12 key). If it's not, you're probably trying to bind the submit event handler too early (before the form exists); if that's the case take a look at the .ready() function. Commented Jan 24, 2013 at 15:01
  • 1
    You don't return the value, you output it; as if you were outputting it to the user. Everything that is output on the page will be accessible through the data variable. Commented Jan 24, 2013 at 16:06

3 Answers 3

7

Try echo $x; instead of return $x;

Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

<?php
    $x = $_POST['email'];
    echo $x;
?>

Comments

1

Try this for better data manipulation. Use json_encode from the server side and json datatype to your ajax calls. Then to alert server response, just alert the key of the array like alert(data.value):

$.ajax({
 type: "POST",
 url: "processAjax.php",
 data: {email: emailVal},
 dataType: 'json'
 success: function(data) {
    alert(data.value);  
}

processAjax.php

$result['value'] = $_POST['email'];
echo json_encode($result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.