2

I'm aware of the difference between the client side javascript and server side PHP and that it's necessary to send the javascript back to the server to be retrieved again but I'm not sure how to do this.

Assuming some trivial javascript code that a variable is created based on some dynamic client side activity from the user:

var teststring = some selection

How would I be able to send and use this teststring in PHP to echo its contents (possibly using ajax or something else) and is it possible to do this on the same PHP page that the javascript is operating on?

I've tried something like this in javascript:

$.ajax({
  url: "originalpage.php",
  type: "POST",
  data: {
    teststring
  }
})

and in the originalpage.php which is the same page the js is operating on:

var_dump($_POST['teststring']);

Which outputs NULL. an echo returns nothing.

2 Answers 2

3

POST parameters require key name and key value, what you need is the following:

$.ajax({
   url: "originalpage.php",
   type: "POST",
   data: {
       'teststring': teststring
   }
)};
Sign up to request clarification or add additional context in comments.

4 Comments

This returns a NULL for the var_dump and nothing for an echo. Update code -> jsfiddle.net/2hGcs, can you see anything wrong with that?
I think there is a confusion , when you load that php file for the first time, the js code has not been fired, thats why you dont get any POST value, then the js fires and will in the background do the request with the parameters the page will be formed correctly and replied to the javascript call correctly. You could log the POST param to your app logger and see how the parameters get logged the second time around or just alert your response in the ajax call
I see, thanks for the explanation. How would I log the POST param the second time round to see if the string has been received correctly?
you can log it in the client by adding the follwing parameter to the ajax call: 'success: function(data) { console.log(data) ; alert(data)}. This will log the response in the javascript console and will alert the response
0

Try this code, tested on my pc and all works ok. You can read the PHP response (the 'echo') only inside success or error.

$.ajax({
  url: "originalpage.php",
  type: "POST",
  data: "teststring="+teststring,
  success: function(response) {
    alert(response);
  }
});

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.