0

We have 5 inputs (type="text") on html page /edit_person.php:

<input id="name" name="name" value="" />
<input id="surname" name="surname" value="" />
<input id="age" name="age" value="" />
<input id="begin" name="begin" value="" />
<input id="end" name="end" value="" />

And a php file /scripts/db.php

If we open in browser /scripts/db.php?get=1 it will give something like (an array with values):

$data = Array(
[name]=>Mark,
[surname]=>Twain,
[age]=>74,
[begin]=>November 30, 1835,
[end]=>April 21, 1910
)

How can we request /scripts/db.php?get=1 by ajax on /edit_person.php and insert received data to the inputs?

jQuery last version is used and PHP 5.2.

If input currently has some value, it should be replaced.

Output format of db.php can be changed, you can request options which would be better.

Thanks.

3
  • 2
    That is a rather strange format what db.php outputs... $data = Array( is completely unnecessary, the line break is the data delimiter? Can you change it to... say, JSON? Commented Nov 22, 2010 at 12:10
  • @AndreKR, yes, output format can be changed. Linebreak is not good by the way some item inside array can be empty. Don't know how to use JSON. Or you mean to give a json format of an array by db.php? Please give some example. Commented Nov 22, 2010 at 12:16
  • 1
    Yes, convert strings to UTF-8, put them into an array, run json_encode on that array, echo it out and accept Pekka's answer. ;) Commented Nov 22, 2010 at 12:20

1 Answer 1

4

db.php seems to be outputting the array in some custom, PHP-like format. I wouldn't do that. Use json_encode() instead: jQuery's Ajax can handle JSON data natively.

  • Docs on jQuery.getJSON() with examples

  • If your JSON data is in a variable named data, the insertion into each input will be a simple $("#name").val(data.name);

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

6 Comments

I can change output type of db.php, so the ajax can handle it (which one would be better?). Trying to use this method, because of bad javascript knowledge.
@AndreKR true, true. Corrected
+1 Keep in mind that you need to feed strings in UTF-8 to json_encode, regardless of what charset your page uses.
so db.php should give data in format like { tags: "cat", tagmode: "any", format: "json" } ?
@Happy yes. jQuery's getJSON can then automatically parse it into a Javascript object
|

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.