First of all, im sorry because im new on ajax and still learning it. I’m using google translate on my website page and i want to translate student_name from original text/string to arabic string. It is from table and i want to pass it to edit-student-data.php page. I have successfully get the arabic string and declare it to variable. And then, when i want to pass this variable to edit page the variable i cant get ajax value. Anyone can help me?
PHP
<table>
<thead>
<th>Student name</th>
</thead>
<tbody>
<tr>
<td class="student_name"><?php echo $take['student_name'] ?></td>
<td>
<a class="btn btn-warning editButton" href="index.php?page=edit-student-data&student_id=<?=$take['student_id'] ?>"> <i class="fas fa-pencil-alt" style=""></i> Edit</a>
</td>
</tr>
</tbody>
</table>
<script>
$(document).on('click', '.editButton', function(e) {
var tr = $(this).closest("tr");
var student_name_arabic = tr.find(".student_name").text();
alert(student_name_arabic); //SUCCESS
$.ajax({
type: 'POST',
url: 'edit-student-data.php',
data: { ar_name: student_name_arabic },
success: function(data)
{
$('#form-control').html(data);
}
});
});
</script>
Another PHP Page (edit student data page)
<div class="form-group">
<label for="exampleFormControlInput1">Student Name</label>
<input type="text" class="form-control" name="student_name" value="<?= $take['student_name'] ?>">
<?php
$ar_name = $_POST['ar_name'];
echo"<script>alert('$ar_name');</script>";
//I can't get arabic name value on alert. please help me:(
?>
</div>
2
Answers
Your jQuery selector here:
is for an
id
, so placeinto your first code after the table, which gives the AJAX return data somewhere to go.
If you meant to use
.form-control
for a class, that won’t work because you reference the element before it exists.You need to get more understanding about GET & POST, how we need to pass the values from one file to another file.
First, from this code you are trying to pass the values to the PHP file "edit-student-data.php", GET as well POST.
From this line, you are trying to pass values to the file via the URL (It’s know as GET call)
From this AJAX code, you are trying to pass the value to through the POST call, as the type you mentioned in the code
javascript:void(0)
.edit-student-data.php
, you have used the variable$take['student_name']
. This is undefined index for that page. If you want to use the student_name in that file. You need to$_POST['ar_name']
, this is the name you have specified in the ajax paramsNote: Instead of static value for name & id, You can specify the dynamic value
PHP code:
File: edit-student-data.php
I hope this would useful.