PHP script not picking up variables through Ajax

Hi! I have a sign_up.php script pointing to POST variables like so:

include "index.php";

$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$email = $_POST["email"];
$password = password_hash($_POST["password"], PASSWORD_BCRYPT);

Where index.php contains actual markup and ajax code like so:

	<div id=form-div>
	<form method=POST action="" >
	First Name: <br> <input type=text name=first_name pattern="[a-z]{2,}" required /> <br> <br>
	Last Name: <br> <input type=text name=last_name pattern="[a-z]{2,}" required /> <br> <br>
	Email: <span id=emailReport></span> <br> <input type=email name=email id=email required /> <br> <br>
	Password: <br> <input type=password name=password required pattern=".{6,}" title="Password must be six or more characters" /> <br> <br>
	Confirm password: <br> <input type=password name=password required /> <br> <br>
	<input type=submit value='sign up' />
	</form>
	</div>
<script>
$('form input:last-child').click(function(e){
		e.preventDefault();
		$('#hidden').load("sign_up.php"); // hidden is a display:none div on the same page
</script>

However, the sign_up.php script eventually picks up no variables and returns notice level warnings undefined for all those fields. Is it impossible to pick the variables like that?

PS: The sign_up.php script contains no output on its own but just processing details for the variables being expected from the included scripts.
BONUS: The first two regex patterns fail to match two or more letters only. In fact it matches nothing whatsoever :cry:

Hi @nmeri17,

The problem here is that youā€™re not actually submitting the form.

$('#hidden').load("sign_up.php");

The load() function makes a GET request to the given URL, and inserts the response into the target element (#hidden).

If you want to submit the form via Ajax, you can do something like this:

$('form').on('submit', function(e) {
  e.preventDefault();
  var formData = $(this).serialize(); // get contents of form fields
  $.post('sign_up.php', formData, function(data) {
    // Display success msg to user here
  });
}

You probably want to use the pattern [A-Za-z]{2,}, otherwise itā€™ll only match names that are all lowercase.

1 Like

Hey! Sorry I couldnā€™t reply earlier. I got no mail notification thatā€™s why. I tried this using the .post method and in my console, I see the post request successful but the PHP script does not run. In my error log, it is supposed to show undefined indexes but it just stays stagnant. All the processing I placed in that script, nothing is ran at all. It just ā€œpostsā€ but the PHP script itself does nothing.

My PHP has both been wrapped in if (!empty($email)) { and stripped of that condition but still, running the post method does not affect the script. At least, using .load did run it and it logged errors. But this one just does nothing.

@fretburner my problem is most identical to this Stack overflow thread but I donā€™t understand the point in the accepted where it says I should json encode my form elements before sending. What then happens at the server side? Do I decode the json object before making use of the variables or just use it normally i.e $name = $_POST['name']?

Iā€™ve just noticed that the example I gave you earlier had a typo - it was missing the closing parenthesis and semi-colon, and wouldnā€™t have run:

$('form').on('submit', function(e) {
  // ...
}); // <-- Note closing parenthesis and semi-colon

You donā€™t need to worry about encoding/decoding JSON. In the example I gave, calling $(this).serialize() handles correctly serializing the form data, and the $.post() method knows how to submit that to the server in the correct way.

If, after correcting the typo, your code still doesnā€™t work, can you post your PHP code here please (removing any usernames/passwords or other sensitive data)?

I actually tried that .post method yesterday shortly after opening this thread and it didnā€™t work, that was why I kept searching online till I found the stack overflow thread I referred to in my last post and now intend to try the solution there since the OP of that post says it worked for him(i.e. the accepted answer that uses the .ajax method and encodes the serialized data).
That is why Iā€™m asking how to go about handling the encoded object server-side, although I doubt that would do me any good anyway since the problem is that the PHP script itself does not even run in the first place (not that it does not pick the variables). I know it does not run because it does not log undefined index after the post method returns successfully and does none of the processes I specified it should.

In other words, I think my problem is more of a server side-one but Iā€™ll like to see how the PHP script reacts when the form fields are encoded and sent to it as json (which is why Iā€™m asking how to handle it there)

If after doing the above, the script still refuses to run, then Iā€™ll resort to posting my PHP code (Note: the PHP code is gigantic and would lead you to asking a lot of questions concerning all the dependencies which are not on that page and you obviously wonā€™t know what they do since we didnā€™t write the code together. If the code were smaller, I would have posted it right away but nevertheless, if the encode option fails, I wonā€™t have a choice.)

This is the code youā€™re referring to, from the SO post, right?

var datastring = $("#contactForm").serialize();
$.ajax({
    type: "POST",
    url: "your url.php",
    data: datastring,
    dataType: "json",
    success: function(data) {
        //var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
        // do what ever you want with the server response
    },
    error: function() {
        alert('error handing here');
    }
});

This is submitting the data in exactly the same way as the code I gave you (if you look at the jQuery docs, youā€™ll see that $.post() is actually a shortcut method for calling $.ajax() with specific settings:

[quote]
This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
```[/quote]

The important difference with the SO example is that it's expecting a JSON _response_ from the server.

I'd recommend using your browser's dev tools to make sure that your JS code isn't throwing any errors, and that the POST request is being submitted to the server. If those things are both OK, that would point to an error with your PHP script.

It returns no errors. The page Iā€™m using it for is here.. Please indicate when you test it for yourself there so I can edit the post.

The path is /register/sign_up.php NOT just sign_up.php since that file is within a sub-directory (register).

@oddz is probably correct, I queried whether your URL was correct in the other post you were running about this yesterday.

Itā€™s not. My include file path doesnā€™t send me to the Root folder when I precede the file path with a forward slash. If I do that, it directs me to the current directory

If you couldnā€™t find the URL itā€™s likely I already moved the file or deleted it

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.