AJAX response from PHP script not working - javascript

I am searching this and other sites for hours now, so I'm getting pretty desperate. No code from many questions with the same topic here works.
I need to insert data into the database and display a message after it is done. Also, I am using AJAX with jQuery so it would be asynchronous. It works just fine, the data gets inserted, but no response message shows.
I am a beginner at PHP and can't understend why this won't work. Relevant code below.
PHP function call:
if(isset($_POST["function"]) && !empty($_POST["function"]) && $_POST["function"] == "cl-add") {
$dbb->addMember("MyUsername", $_POST["name"]);
//$dbb is a DataBaseBroker instance
}
PHP function from the Broker:
function addMember($username, $ime) {
$query = "INSERT INTO clan";
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";
$result = $this->mysqli->query($query);
if ($result) {
echo("You added a member: ".$ime);
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: ".mysqli_error($connection);
echo $response;
}
}
JQuery function declarations:
var addMember = function(name, responseFn) {
if (name === "") {
alert("Please enter a name");
return;
}
$.ajax({
type : 'POST',
url: '../includes/layout/cl.php',
dataType : 'json',
data : {
'name' : name,
'function' : 'cl-add'
},
success : function(data) {
responseFn(data); //not working, should alert
}
});
}
var responseCallback = function(data) {
alert(data);
}
And inside $(document).ready():
$(document).on('click', '#cl-add', function(evt) {
var name = $("#cl_frm input").val();
addMember(name, responseCallback);
});

On your code:
dataType : 'json',
The Ajax request is waiting for a JSON response but you are giving a text response.
You should change the dataType: to text or html depending on your needs.
dataType : 'html',
or
dataType : 'text',
PHP changes:
<?php
function addMember($username, $ime)
{
$query = "INSERT INTO clan";
$query .= " (username, ime) ";
$query .= "VALUES ('" . $username . "','" . $ime . "');";
$result = $this->mysqli->query($query);
$response = null;
if ($result) {
$response = "You added a member: " . $ime;
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: " . mysqli_error($connection);
}
echo $response;
exit;
}

Change dataType parameter to 'text'. Also you can alert an object in JavaScript, actually you are not trying to alert an object but i just wanted to mention it.

Related

Display data from a PHP query returning Json data, via Ajax

When I run the code shown below on my website, I have the following error in my Chrome console: Uncaught SyntaxError: Unexpected end of JSON input.
jQuery:
$('#SearchBtn').click(function() {
$.ajax({
type: 'POST',
url: 'request.administration.php',
data: {id: $("#InputId").val()},
cache: false,
success: function(data) {
if (data == 1) {
console.log("not found");
} else {
$("#InputFirstname").val(data[0]);
$("#InputLastname").val(data[1]);
$("#InputPhone").val(data[2]);
}
}
});
});
PHP:
$sql = "SELECT * FROM User WHERE id=" . $_POST["id"];
if ($result = mysqli_query($link, $sql)) {
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
$firstname = $row["firstname"];
$lastname = $row["lastname"];
$phone = $row["phone"];
$values = array(
$firstname,
$lastname,
$phone
);
json_encode($values);
} else {
echo "1";
}
}
As a matter of fact, I don't know how to display my firstname, lastname and phone number, from a Json function. I've read similar topics but I didn't get the answer to my question.
I did some checking before I came to you for help:
-the input ids are correct.
-the PHP creates the array correctly.
-when I run a console.log(data), nothing happens.
Thank you in advance to those who will be able to help me.

Error (net::ERR_EMPTY_RESPONSE) on AJAX call

When the AJAX is called I always get these errors:
net::ERR_EMPTY_RESPONSE or net::ERR_CONNECTION_RESET
I also tryed different browsers (Chrome and Edge) but it is only working on localhost.
Thanks for all your help and support.
My PHP code (register.php):
require_once 'mysql_conn.php';
// username and password sent from form
$myUsername = mysqli_real_escape_string($db,$_POST['username']);
$myPassword = mysqli_real_escape_string($db,$_POST['password']);
$myRepPassword = mysqli_real_escape_string($db,$_POST['rep_password']);
if($myPassword == $myRepPassword && strlen($myUsername) >= 3 && strlen($myPassword) >= 8)
{
$userCheck = "SELECT id FROM users WHERE username = '$myUsername'";
$result = mysqli_query($db,$userCheck);
$count = mysqli_num_rows($result);
if($count > 0)
{
echo "This user already exists";
}
else
{
$sql = "INSERT INTO users (username, password) VALUES ('$myUsername', '$myPassword')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
}
}
else
{
echo "Please check the values you inserted";
}
and the AJAX call:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'register.php',
data: {username:username, password:password, rep_password:rep_password},
success: function (data) {
errorHandling(data);
}
});
});
});
I don't know how, but I solved it by deleting and re-creating the register.php file

ajax get Excel form php

I am tryinh to get excel form php through ajax call when i load url of specific php gives me the output but when the same php is called via ajax with some ajax value nothing shows up.. am not sure what to do
ajax:
var fromdate= $("#fromdate").val();
var ToDate= $("#ToDate").val();
var Year= $('#Year').val();
var Category=$('#Category_1').val();
$.ajax({
url: "http://localhost/demo.php",
type: "post",
data: {
fromdate:fromdate,ToDate:ToDate,Year:Year,Category:Category
},
success: function(responsecon) {
window.open('http://YOUR_URL','_blank' );
}
});
PHP:
<?php
$conn=mysqli_connect('localhost','root','0000','xxxxx');
$filename = "users_export";
$fromdate = mysqli_real_escape_string($mysqli,trim($_POST["fromdate"]));
$ToDate = mysqli_real_escape_string($mysqli,trim($_POST["ToDate"]));
$Year = mysqli_real_escape_string($mysqli,trim($_POST["Year"]));
$Category = mysqli_real_escape_string($mysqli,trim($_POST["Category"]));
$sql = "Select * from xxxxxxxxxxx where category='$Category'";
$result = mysqli_query($conn,$sql) or die("Couldn't execute query:<br>" . mysqli_error(). "<br>" . mysqli_errno());
$file_ending = "xls";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
$sep = "\t";
$names = mysqli_fetch_fields($result) ;
foreach($names as $name){
}
print ("dasd" . $sep."dasd1" . $sep);
print("\n");
while($row = mysqli_fetch_row($result)) {
$schema_insert = "";
for($j=0; $j<mysqli_num_fields($result);$j++) {
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
Basically there are two problems in your jQuery ajax request:
Sice you are specifying a content-type in your PHP script you have to tell jQuery what to expect from your ajax request using dataType: application/xls in your ajax object.
This is why you don't get any response, because it fails and you have not specified an error callback function to handle the error.
Moreover, in case of success you have to print somehow the content returned from the PHP script with something like $("#selector").html(responsecon);
Here is the updated ajax request:
$.ajax({
url: "http://localhost/demo.php",
type: "post",
dataType: "application/xls", // Tell what content-type to expect from server
data: {
fromdate:fromdate,
ToDate:ToDate,
Year:Year,
Category:Category
},
success: function(responsecon) {
window.open('http://YOUR_URL','_blank' );
$(#"some-container").html(responsecon); // Print the content
},
error: function() {
alert("error");
}
});

parse return data from html to ajax

I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.

Textbox and AJAX data from mySQL

Hello I have a textbox and when I type something in it should update the page with the mySQL data via AJAX.
So Im trying to get live updated database results whenever you type something in the textbox. The goal is to get a textbox that is getting data from the mySQL database.
I have written the code so far, hopefully someone can advise me in this mather, thank you.
$select = 'SELECT *';
$from = ' FROM overboekingen';
$where2 = ' WHERE naam_klant LIKE % . $val . % ';
$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
$val = (isset($_POST['txt']) ? $_POST['txt'] : FALSE);
if (is_array($opts) || $val) {
$where = ' WHERE FALSE';
if (in_array("naam_klant", $val)){
$where2.val;
}
}
else {
$where = false;
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
AJAX
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {text: val},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
You must define the PHP $val variable before.
The correct sytax:
$where2 = " WHERE naam_klant LIKE %$val% ";

Categories