Welcome to WebmasterWorld Guest from 34.238.194.166

Forum Moderators: open

Jquery Ajax not posting values to PHP script

     
3:00 pm on Jun 23, 2019 (gmt 0)

New User

joined:June 23, 2019
posts: 5
votes: 0


Hi, my first post and first foray in to JQuery.
I've been trying to learn how to use JQuery and AJAX to update a select drop down in a form based on another select.
So far it all works fine. However the POST values defined in Ajax are not being parsed to my php script.
If I do a var_dump there are no POST values.
Relevant sections of the script are below. I'm still learning so explanations would be much appreciated Thanks

$(document).ready(function() {
$('select[name="CategoryID"]').change(function() {
var SelectedCategoryID = $('select[name="CategoryID"] option:selected').val();

$.ajax({
method: "POST",
url: 'phpProcessor.php',
data: { CategoryID: "SelectedCategoryID" },
cache: false
}).done(function(data) {
$('select[name="SubCategoryID"]').html(data);
})
});
});


PHP processor script
$_POST['CategoryID'] = trim($_POST['CategoryID']);
// Validation before using
if (ctype_digit($_POST['CategoryID'])) {// Fails as POST array is not set
print '<option>response has been validated</option>';
}

// This works and updates/changes the expected sub category select
print '<option value="55" selected="true">input failed validation</option>
<option value="955">input is not valid</option>';

var_dump($_POST);
8:51 pm on June 23, 2019 (gmt 0)

New User from US 

Top Contributors Of The Month

joined:June 21, 2019
posts: 29
votes: 2


I think your issue is related to the way you're setting your vars.

You cannot access javascript vars in php... but you can access your php variables and program your javascript vars with php code snippets in your javascripts.

For example you can program it like this >>>>> "var javavar = <?php $_POST["somefieldname"] ; ?>; "

Now when you pass it all back to the page, set your form field values with php, then your javascript can retrieve the updated form field data.

I hope this makes sense to you. Also I just outlined the steps... this is not meant to be a step by step procedure, just an outline of the process only.
9:05 pm on June 23, 2019 (gmt 0)

New User from US 

Top Contributors Of The Month

joined:June 21, 2019
posts: 29
votes: 2


Just wanted to add... by using php to set the $_POST vars your var_dump should now properly display the correct data.
3:22 am on June 24, 2019 (gmt 0)

New User

joined:June 23, 2019
posts: 5
votes: 0


Hi Kno OneSpecial, Thanks for your contribution, however the Javascript works fine. Except for the POST variables are not being set so that the PHPProcesser.php script can access the value of the first drop down onChange so I can query the DB to get the sub categorys.
What I am trying to do is to get JavaScript to POST the value of the CategoryID select onChange. Then PHP will be able to access the POST variables
At the moment the POST array is empty so the "if" statement fails and the second drop down changes from "select category first" to "failed validation" So as you can see everything else works fine I'm just not getting the variables set in the POST array
5:35 am on June 24, 2019 (gmt 0)

New User from US 

Top Contributors Of The Month

joined:June 21, 2019
posts: 29
votes: 2


I actually kinda of gave you faulty info... I forgot one thing about java....sorry..

I understand your javascript works, no problem there.. the issue you have is you are not setting the form fields. That is what $_POST points to. An array of form field values.

Here is the crux of the issues....
Ajax just updates the page in the browser only, one reason it is so quick. The page would have to be resubmitted to the server to update the $_POST array of form fields

The server has not been updated, it has no idea that java has updated the page since it was processed and sent to the user.

So you got some choices...
You update the page by resubmitting it. Then you can use var dump. It may be possible to do a unnoticeable refresh of the page, don't know, haven't see the page.

You could use Session variables here, but not var dump. <<< This may be your easiest solution.

The one other solution is to use a database so you can store the variables in it and retrieve them on demand. This is probably the most robust and least restrictive way. But a bit more complex

Again I apologize for the error.
.
5:53 pm on June 24, 2019 (gmt 0)

New User

joined:June 23, 2019
posts: 5
votes: 0


Hi Know One Special, not a problem.
Many of the online tutorials I have seen all say that once JavaScript via AJAX has sent a post request to the server, the variables it sets should be available to PHP in the $_POST array.
I would include a few links but I understand they are not encouraged on the forum.

I thought my included AJAX POST request would of updated the server
It means I'm no further along in understanding why my script does not seem to set the variable in the $_POST array as many examples online show.
12:42 am on June 25, 2019 (gmt 0)

New User from US 

Top Contributors Of The Month

joined:June 21, 2019
posts: 29
votes: 2


What you are doing is you send the Ajax request to the server, then you fill the forms with the Ajax data. Then you dump the vars. Which means the form data you updated is "null" you didn't fill the form before you executed the ajax call.

This is a dirty solution, but you will learn why things work the way the do.

Do your ajax request, then fill your form, then auto submit the page. This will update of the $_POST array of form data.

Here study this line of code, I think you will see and understand the code. Now this is what I was taking about when I said a unnoticeable refresh.. you may only see a flicker, no harm no foul in the user experience department. Now use your ajax call to fill the drop down, then auto select the first value to trigger the onchange event.

<select name="name-of-option" id="value-of-option" onchange="this.form.submit()">

There is another solution. You could use $_Sessions vars, don't know if you know how to use sessions.... you should look into it...Session variables are persistent across pages and you can use them just like form data if you program the usage correctly. Using session variables is / can be quite a bit more complex though,

Here is a primer for you... w3schools.com/php/php_sessions.asp

( don't know if I am allowed to post a live link, so I made it linkless )
8:23 am on June 25, 2019 (gmt 0)

New User

joined:June 25, 2019
posts: 1
votes: 1


Hi there!
May I clarify that code you've shared is the one you (to some degree) use right now? Cause there's at least one typo:
data: { CategoryID: "SelectedCategoryID" },

- which sends "SelectedCategoryID" as string, instead of read value. Which is a possible problem causing "input failed validation" erroneous response.

But there's a still problem of empty $_POST nonetheless, I might suggest few things to check:
1. your browser's developer console (usually access through F12 or Ctrl+Shift+I) network tab - does request to 'phpProcessor.php' goes through and carries neccesary data (request details -> headers -> scroll down, there should be Form Data section with "CategoryID: ...".
2. In case request itself is fine, try to output contents of PHP's input (all data that has been sent as special input header) via
var_dump( file_get_contents('php://input') );

3. If it's as empty like $_POST, but you see that request goes through fine, I'm unsure what could cause your problem, versions info could help - which version of jQuery and PHP are you using, etc.
4. You also could test whether usual HTML forms can send any data to PHP for example
<form method="POST" action="phpProcessor.php"><input name="CategoryID" value="375" /><button type="submit">test</button></form>
1:12 pm on June 25, 2019 (gmt 0)

New User

joined:June 23, 2019
posts: 5
votes: 0


Hey Know One Special, I think you are miss understanding me and my script.
I have a form with 2 select drop downs
1 contains a category with a value of "CategoryID"
the other a Sub Category drop down which is dependent on the value of "CategoryID from the first select
onChange of the "CategoryID" select it triggers my JQuery script
To POST the CategoryID select value using AJAX to the server
The PHPProcessor.php script then queeries the DB using the categoryID Value posted via AJAX to the server
to get the relevant sub categories and return a select list with the relevant sub categorys and their values.

Are you saying this is not possible to do? Nearly every tutorial I've seen says this is the way to do it...
1:57 pm on June 25, 2019 (gmt 0)

Senior Member

WebmasterWorld Senior Member Top Contributors Of The Month

joined:Nov 13, 2016
posts:1177
votes: 275


What is your version of Jquery? if version < 1.9.0 you need to use "type: 'POST'" instead of "method: 'POST'" . Just a thought.

You can also check the request method, by checking the value of $_SERVER['REQUEST_METHOD'] (in PHP of-course)
4:44 pm on June 25, 2019 (gmt 0)

New User

joined:June 23, 2019
posts: 5
votes: 0


Hi Dimitri, upgraded my jQuery to 3.3.1 I now get the $_POST populated with "CategoryID" however the value is empty when it should contain the value of the selected CategoryID
I did correct the data line to data: { CategoryID: SelectedCategoryID }
4:47 pm on June 25, 2019 (gmt 0)

Senior Member

WebmasterWorld Senior Member Top Contributors Of The Month

joined:Nov 13, 2016
posts:1177
votes: 275


Now, the remaining issue is Javascript / Jquery related. All depends how you retrieve the SelectedCategoryID, before the post, you can always try an "alert" (message box) to see the value of this variable, it might not be correctly retrieved. (I never used Jquery, so I am very limited in this domain).
4:48 pm on June 25, 2019 (gmt 0)

Senior Member

WebmasterWorld Senior Member Top Contributors Of The Month

joined:Apr 1, 2016
posts:2662
votes: 793


@code_Monkey
Follow what Askadar suggests, it is not the solution, but it will lead you to the source of the issue.

Specifically, what does browser show in regards to the server request?
1. your browser's developer console (usually access through F12 or Ctrl+Shift+I) network tab - does request to 'phpProcessor.php' goes through and carries neccesary data (request details -> headers -> scroll down, there should be Form Data section with "CategoryID: ...".
12:18 am on June 26, 2019 (gmt 0)

New User from US 

Top Contributors Of The Month

joined:June 21, 2019
posts: 29
votes: 2


No I am not say it's impossible to do... There is a flaw in your code or logic... one or the other.....

The simplest thing my be to run some debug lines echoing the data to the screen after each step.

You know what the data should be, so once you see incorrect data you know which of your code snippets has the issue.. Then you can fix the problem.