This question already has answers here:
Make jQuery AJAX Call to Specific PHP Functions
(3 answers)
Closed 6 years ago.
I've read all the topics about my question but cannot solve my problem. I want to get php function result using jQuery AJAX.
function fetch_select(){
val_name = $('#name').val();
$.ajax({
type: 'POST',
url: 'include/get_db.inc.php',
data: {
name: val_name,
},
success: function (response) {
document.getElementById('higtchart_medie_gen').innerHTML=response;
columnChart( JSON.parse(response));
}
});
}
function columnChart(data_v){
if(data_v.length >0){
$(function () {
$('#higtchart_medie_gen').highcharts({
chart: {
type: 'column'
},
......
#name is id for select tag.
My code for get_db.inc.php is:
<?php
function test_name () {
$ret = [];
if(isset($_POST['name'])){
$name = $_POST['name'];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'], floatval($row['AVGG'])];
}
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
?>
How can I call test_name function from Ajax code?
Thank you very much!
You do almost correct but only one mistake is you forget to invoke the function. What you do is just send the data to this file.
So, to fixed this. Just add test_name() to your get_db.inc.php
<?php
function test_name () {
$ret = [];
if(isset($_POST['name'])){
$name = $_POST['name'];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'],floatval($row['AVGG'])];
}
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
test_name()
?>
Also it will be better to check isset outside the function.
function test_name ($name) {
$ret = [];
$sql = "SELECT
......
WHERE ID = $name ";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$ret [] = [$row['NAME'] . ' ' . $row['LASTN'],floatval($row['AVGG'])];
}
}
if(count($ret) >1) echo json_encode($ret);
else echo 'Not working';
}
if(isset($_POST['name'])){
test_name($_POST['name'])
}
This will make your function to be pure. It will easier to debug later and it will not invoke if you don't have $_POST['name'].
Related
I'm currently working on a Facebook like chat, with 3 different chat boxes that should work simultaneously. I can send and read messages from my database, but I'm having difficulty displaying this information in the right place. In chat.php I have this snippet of code:
$.ajax({
url: "fetch_user_chat_history.php",
method: "POST",
data: jQuery.param({receiver_id:receiver_id, num:num}),
success: function(data) {
$('$chat_history_'+receiver_id).html(data);
}
});
Now I am able to read the data from my database correctly in fetch_user_chat_history.php, but when I iterate over my messages I'm unable to output them correctly back to chat.php. Here is my fetch_user_chat_history.php:
<?php
include "opendb.php";
session_start();
$output1 = '';
$output2 = '';
$increment = 0;
$sender = $_SESSION['user_id'];
$receiver_id = $_POST['receiver_id'];
$chatboxnum = $_POST['num'];
$query = 'SELECT content, timestamp_chat, sender_id FROM messages WHERE (sender_id = '.$sender.' AND receiver_id = '.$receiver_id.' OR (sender_id = '.$receiver_id.' AND receiver_id = '.$sender.'))';
$statement = $db->prepare($query);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
switch ($chatboxnum) {
case 1:
foreach ($result as $row) {
if ($row['sender_id']==$sender) {
echo '<script>var para = document.createElement("div");';
echo 'para.innerHTML = '.$row["content"].';';
echo 'var att = document.createAttribute("class");';
echo 'att.value = "msg-send";';
echo 'para.setAttributeNode(att);';
echo 'document.getElementById("sendbox-1").appendChild(para);';
echo 'document.body.appendChild(para); </script>';
}
else {
echo "var element = document.getElementById('receivebox-1'); element.classList.add('msg-receive');";
}
$increment += 1;
}
break;
}
?>
None of my echo statements add anything to chat.php. I'm sure there's a very easy fix as I have done this before but I can't seem to get it working. I apologise for the long post.
when one record then show data when multiple record come then not show data other site.
ajaxx.php
<?php
include 'database.php';
session_start();
$post = $_POST;
$search = $post['search'];
$searchType = $post['searchType'];
if ($searchType == 'all')
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND (type='Bukhari' OR type='Muslim') ";}
else
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND type='$searchType' ";}
$result = mysqli_query($db,$sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row['title'];
echo json_encode($row);
}
} else
{ echo "Not Found Result" ; }
?>
when data record is one then append the data successfully when multiple record come then not show data and append not work
javascript code
function searchh()
{
var type = $("input[name='type']:checked").val();
var searchhh = $( ".myButton option:selected" ).text();
debugger;
$.ajax({
url: 'ajaxx.php',
type: "POST",
data: {'searchType':type, 'search':searchhh},
success: function (data) {
var duce = jQuery.parseJSON(data);
alert(duce.title);
}
});
}
I think your issue is in the while loop. You don't want to encode each row one-by-one, but as a whole like this.
$myResults = [];
while($row = $result->fetch_assoc()) {
$row['title'];
$myResults[] = $row;
}
echo json_encode($myResults);
You are producing invalid JSON by using echo json_encode($row); within a loop.
Try to craft an array of rows, and then display it.
if($result->num_rows > 0)
{
$output = array();
while($row = $result->fetch_assoc())
{
output[] = $row;
}
if($searchType == 'all')
{
echo json_encode($output);
}
else
{
echo json_encode(current($output)); // print just one
}
}
I am trying to work out why my alert in the 'function processResponse(data)' part of the code, is not being displayed. I have tried various return; options, but still, refuses to display.
I would be grateful if someone could point out my error. Many thanks.
PS. I am aware of security issues in the code posted such as mysql_escape_string, but all security issues will be inserted before the site goes live.
jQuery code
<script type="text/javascript">
$(function() {
$('#srcsubmit').click(function(e) {
e.preventDefault();
if ($('#srcBox').val() == '') {
notif({
type: "error",
msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click anywhere to close</p>",
height: 99,
multiline: true,
position: "middle,center",
fade: true,
timeout: 3000
});
return false;
}
$("#submit").prop("disabled", true);
$("#submit2").prop("disabled", true);
$("#submit3").prop("disabled", true);
var value = $('#srcBox').val();
var dept = '<?php echo $_GET['dept ']; ?>';
var qString = 'sub=' + encodeURIComponent(value) + '&dept=' + encodeURIComponent(dept);
$.post('sub_db_handler.php', qString, processResponse);
});
function processResponse(data) {
if (data === 'true') {
alert('That box is not on the system'); <--- this is the problem
return;
}
$('#srcBoxRslt').val(data);
};
});
</script>
PHP backend
<?php session_start(); ?>
<?php
$con = mysql_connect("localhost","root","");
if(!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("sample", $con);
$dept = trim($_POST['dept']);
$custref = trim($_POST['sub']);
$result = mysql_query("SELECT * FROM boxes WHERE custref = '".$custref."'");
$found = mysql_num_rows($result);
if ($found == 0)
{
echo trim('true');
} else {
$query = "SELECT * FROM boxes WHERE department = '".$dept."' AND status = 1 AND custref = '".$custref."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
$r = $row['custref'];
$str = json_encode($r);
echo trim($str, '"');
}
?>
The data value is not equal to true because of extra space to get rid of extra use .trim()
I am writing a program that send bulk email to our registered users via ajax.
I want echo every loop response when it is completed and it goes to next condition.
For Example:-
I have list of 100 Emails in database. When i submitted the request to program it will start sending emails.
Prog. works something like :
<?php
foreach($emails as $email){
$status = $this->sendMail($email);
if($status == true)
{
echo "Mail Sent";
}else{
echo "Not Sent";
}
}
?>
Now i want to print "Mail Sent"/"Not Sent" again and again for every loop.
Output:-
Mail Sent
Mail Sent
Mail Sent
Not Sent
Mail Sent
Sending..
EDIT
My PHP Code is:-
<?php
public function send_message() {
$sendTo = $this->input->post('send_to');
$template = $this->input->post('template');
$subject = $this->input->post('subject');
switch ($sendTo) {
case 1:
$users = $this->getAllEmails();
break;
case 2:
$users = $this->getRegisteredUsersEmails();
break;
case 3:
$users = $this->getTemproryUsersEmails();
break;
case 4:
$users = $this->getSubscribersEmails();
break;
}
$status = $this->sendMail($users, $template, $subject);
echo "Mail Sent";
}
private function sendMail($users, $template, $subject) {
$this->load->library('parser');
$status = array();
$i = 0;
foreach ($users as $user) {
$message = $this->parser->parse('email_templates/' . $template, array('email' => $user->email, 'name' => ($user->name != '') ? "Hi " . $user->name : "Hello"), TRUE);
$response = $this->mail->send(config_item('sender_mail'), config_item('sender_name'), $user->email, $subject, $message);
$status[$i]['email'] = $user->email;
$status[$i]['status'] = ($response == 1) ? 1 : 0;
$i++;
}
return $status;
}
?>
My Ajax Code :-
<script type="text/javascript">
$("#send_mail").submit(function(){
$.ajax{
url:"<?php echo base_url('promotion/send_message'); ?>",
type:"post",
data:$(this).serialize(),
success:function(data){
$("#status").html(data);
}
}
});
</script>
You have to do your loop with javascript/jquery rather than PHP. To have no overflow on server-side you should probably only call the function on success by using recursion. This way it will be synchronous.
jQuery
var emails = [
'lorem#stackoverflow.com',
'ipsum#stackoverflow.com',
'foo#stackoverflow.com'
];
index = 0;
var sendMail = function(email){
$.ajax({
url:"sendMail.php",
type: "POST"
data: { emailId: email}
success:function(response) {
index++;
document.write(response);
if(emails[index] != undefined){
sendMail(emails[index]);
}
}
});
}
sendMail(emails[index]);
PHP
$status = $this->sendMail($$_POST['email']);
$msg = $status ? "Mail Sent" : "Not Sent";
echo $msg;
I want to print the response when each time "$this->mail->send" function is called in "sendMail()"
As your code above, $status should be return in ajax function like a json object array.so I try this one ...
private function sendMail($users, $template, $subject) {
$this->load->library('parser');
$status = array();
$i = 0;
foreach ($users as $user) {
$message = $this->parser->parse('email_templates/' . $template, array('email' => $user->email, 'name' => ($user->name != '') ? "Hi " . $user->name : "Hello"), TRUE);
$response = $this->mail->send(config_item('sender_mail'), config_item('sender_name'), $user->email, $subject, $message);
$status[$i]['email'] = $user->email;
$status[$i]['status'] = ($response == 1) ? 1 : 0;
$i++;
}
echo json_encode($status);
}
Ajax Code
<script type="text/javascript">
$("#send_mail").submit(function(){
$.ajax{
url:"<?php echo base_url('promotion/send_message'); ?>",
type:"post",
dataType : "json",
data:$(this).serialize(),
success:function(data){
$.each(data,function(i,v){
$("#status").append(v.status);
}
}
}
});
</script>
var phpCode = '<?php
$sql = "SELECT Name,Surname,id_room FROM timatable.professors WHERE p.id_professor = '".mysqli_real_escape_string($_POST['hiddenProfId'])."'";
$resutl = mysqli_query($db,$sql);
if ($result == 1 ) {
$row = mysqli_fetch_array($result);
$professorName = $row['Name'];
$professorSurname = $row['Surname'];
} else echo "Error";
?>';
alert(phpCode);
this is my code. how to make it work ????
Try this.
First initialize, variables to null.
$professorName = "";
$professorSurname = "";
This is because, if php code enters else part, you will not get any error in javascript part.
<?php
$sql = "SELECT Name,Surname,id_room FROM timatable.professors WHERE p.id_professor = '".mysqli_real_escape_string($_POST['hiddenProfId'])."'";
$resutl = mysqli_query($db,$sql);
if ($result == 1 ) {
$row = mysqli_fetch_array($result);
$professorName = $row['Name'];
$professorSurname = $row['Surname'];
} else echo "Error";
?>
<script>
var professorName = "<?php echo $professorName ?>";
var professorSurname = "<?php echo $professorSurname ?>";
alert(professorName);
alert(professorSurname);
</script>
PHP is a server-side language. So it is processed on a server. Therefore you cannot have a PHP code in javascript.
If you want to have javascript managed some editing in database, you can use AJAX to do it without reloading the page.