Reputation:
I am trying to change the value of two textboxes based on the result of a MySQL query. I have the following error:
Uncaught RangeError: Maximum call stack size exceeded
<head>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
</head>
<body>
<form id="form">
<input class="form-control" type="text" id="userfname" name="frsname"
value="" />
<input class="form-control" type="text" id="userlname" name="lstname" value="" />
<input type="submit" name="submit" id="submit" value="Save" />
</form>
<script>
$('#submit').click(function () {
$.ajax({
type: "POST",
url: "index.php",
data: form,
dataType: "json",
success: function (data) {
$("#userfname").html(data[0]);
$("#userlname").html(data[1]);
}
});
});
</script>
</body>
PHP file:
<?php
if(!isset($_SESSION)){
session_start();
}
require 'config.php';
$stmt2 = mysqli_prepare($link, "SELECT firstname, lastname FROM users WHERE id=?");
if(!$stmt2) {
die($link->error);
}
$stmt2->bind_param("i", $_SESSION['id']);
if(!$stmt2->execute()) {
die($stmt2->error);
}
$stmt2->bind_result($fname, $lname);
$stmt2->fetch();
$stmt2->close();
$arr = array();
$arr[0] = $fname;
$arr[1] = $lname;
echo json_encode($arr);
$link->close();
?>
How can I solve this error? I would like to return the values from the select query and update the input values. Thank you.
Upvotes: 3
Views: 552
Reputation: 528
Also change this <input type="button" name="submit" id="submit" value="Save" />
Upvotes: 2
Reputation: 424
You're not posting any values so a $.getJSON should be used instead. Put your php in a file getUserDetails.php Also use val() jQuery method to update inputs values.
$('#submit').click(function () {
$.getJSON("getUserDetails.php").done(function(json) {
$("#userfname").val(json[0]);
$("#userlname").val(json[1]);
});
});
Upvotes: 0
Reputation: 780843
data: form
tries to convert the <for>
element to url-encoded data, which doesn't work. Since the PHP script doesn't use any POST parameters, you don't need that line.
You should also prevent the default form submission with event.preventDefault()
.
To fill in the <input>
fields, you need to use .val()
, not .html()
.
$('#submit').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "index.php",
dataType: "json",
success: function (data) {
$("#userfname").val(data[0]);
$("#userlname").val(data[1]);
}
});
});
Upvotes: 3