Error in $.ajax call - javascript

I have an $.ajax call in one of my pages that links to a simple php page.
I am getting my alert for the error: property. I am not getting anything back in the errorThrown variable or in the jqXHR variable. I have never done this kind of thing before and i am not seeing what is wrong with my page.
JQuery $.ajax call :
function jsonSync(json) {
$.ajax({
type: 'POST',
url: 'http://www.cubiclesandwashrooms.com/areaUpdate.php',
dataType: 'json',
data: json,
context: this,
success: function () {
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error has occured! \n ERR.INDEX: Sync failed, ' + jqXHR.responseText + ';' + textStatus + ';' + errorThrown.message);
return false;
}
});
And this is my PHP Page :
$JSON = file_get_contents('php://input');
$JSON_Data = json_decode($JSON);
//handle on specific item in JSON Object
$insc_area = $JSON_Data->{'insc_area'};
//mysqlite connection.open() equivilent
$insc_db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($insc_db)) {
die('Could not connect: ' . mysql_error());
echo "Failed to connect to MySql: " . mysqli_connect_error();
//mysqli_close($insc_db);
}
//$insc_area.length equivilent
$insc_area_size = sizeof($insc_area);
//cycle through reult set
for ($i = 0; $i < $insc_area_size; $i++) {
//assign row to DataRow Equivilent
$rec = $insc_area[$i];
//get specific column values
$area = $rec->{'area'};
$id = $rec->{'srecid'};
//sqlcommand equivilent
$query = "SELECT * FROM insc_products WHERE id='$id' LIMIT 1";
$result = mysqli_query($insc_db, $query);
$num = mysqli_num_rows($result);
//dataReader.Read equivilent
while ($row = $result->fetch_array()) {
$query = "UPDATE insc_products SET area='$area' where id = '$id'";
$res = mysqli_query($insc_db, $query);
//checking if update was successful
if ($res) {
// good
error_log('user update done');
echo 'update was successful';
} else {
error_log('user update failed');
echo 'error in update';
}
}
}
echo 'testing php';

dataType: 'json'
means: give me json back. your PHP file isn't returning json formatted data
similar question: jQuery ajax call returns empty error if the content is empty
to buid a json response fill an array in the php file with the return information and use echo json_encode($array); at the end of the file. if you are using dataType:'json' because the code is copy/pasted, and you won't need the response to be in json format, simply remove this option...

Add following line in php file, $JSON_Data encode then it will work.
echo json_encode($JSON_Data);

Related

Returning an itterable object to Ajax from php

How can I iterate through the object sent back from the php script below in my jquery/ajax call?
I tried result[0] whiche gave me back c. That means that I'm being returned a string.What code should I write to be returned company1 etc. ?
DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;
CREATE TABLE company(
name VARCHAR(255),
id INT PRIMARY KEY AUTO_INCREMENT
);
INSERT INTO company(name) VALUES( 'company1');
INSERT INTO company(name) VALUES( 'company2');
INSERT INTO company(name) VALUES( 'company2');
$.ajax({
type: "GET",
url: "manager-get-company.php",
success: function (response) {
//iterate through response here
//console.log(response[0]; -> log Company1
//console.log(response[1]; -> log Company2
}
});
<?php
//manager-get-company.php
$hostname = 'localhost';
$username = 'root';
$password = '';
$database_name = 'test';
$con = mysqli_connect($hostname,$username,$password,$database_name);
//Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
echo $row['name'];
}
In ajax add dataType : "json",
$.ajax({
type: "GET",
dataType : "json",
url: "manager-get-company.php",
success: function (response) {
//iterate through response here
if(!response.error){
console.log(response[0]);
}
}
});
In php
$result = [];
//Check connection
if (mysqli_connect_errno()) {
$result['error'] = "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
$sql= mysqli_query($con, 'SELECT name FROM company');
while($row = mysqli_fetch_array($sql)){
$result[] = $row['name'];
}
}
echo json_encode($result);
Edited : use $result['error'] not result['error']

Ajax MySQL query does not return current data

I want to write an Ajax request that Returns data from a MySQL-database. But it does not work properly, because the Ajax request does not return the current values of the mysql database, if data has changed. Instead it always returns the old data of the database. The php-file is working properly, if I open it in a browser, it shows the correct current data values. I found out, that the Ajax request only shows the correct current data values, if I first open the php-file manually in a browser. If I then again use the ajax request, it returns the correct current data. What am I doing wrong?
This is the code for the Ajax request:
var scannedTubes = (function() {
var tmp = null;
$.ajax({
async: false,
url: "ajaxtest.php",
success: function(response) {
alert("RESPONSE: " + response);
tmp = response;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
return tmp;
})();
The code of the ajaxtest.php file is the following:
<?php
$con = mysqli_connect("", "root");
if(mysqli_connect_errno()){
echo "FAIL: " . mysqli_connect_error();
}
mysqli_select_db($con, "multitubescan");
$queryStr = "SELECT code FROM scan WHERE row = 0 AND code <> 'EMPTY'";
$res = mysqli_query($con, $queryStr);
$num = mysqli_num_rows($res);
$scannedTubes = "";
while($data = mysqli_fetch_assoc($res)){
$scannedTubes = $scannedTubes . " " . $data["code"];
}
$scannedTubes = $num . " " . $scannedTubes;
mysqli_close($con);
echo $scannedTubes;
?>
I suppose data is cached by your browser.
Make the url unique:
url: "ajaxtest.php",
to
url: "ajaxtest.php?rnd=" + Math.random() ,

Ajax returns success but doesn't change the database

I'm developing a small script of js to edit a profile in the way facebook used to be (click a button, edit and save without reloading the page). The problem is that when I run it, the ajax function returns sucess but akes no changes on the database. The function os js is this:
$('.savebtn').click(function(){
var editdata = $(".editbox").val();
var parameter = $(this).closest("td").find("#parameter").text();
var datastring = "data="+editdata+"&parameter="+parameter;
var $t = $(this);
console.log(datastring);
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function()
{
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
});
});
(Ignore the $t thing, somehow this works like this, but not if I use $(this))
Ajax executes the code for sucess but doesn't update anything on the database.
The PHP code for the database is:
<?php
include_once("../../config/connect_db.php");
include_once("../../database/cliente.php");
$parameter = $_POST['parameter'];
$data = $_POST['data'];
$id = $_SESSION['id'];
var_dump($_POST);
try {
updateProfile($parameter, $data, $id);
}
catch (PDOException $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users
SET ? = ?
WHERE id = ?");
$stmt->execute(array($parameter, $data. $id));
}
EDIT: As pointed out, this could be a problem with trying to pass a column name as a parameter. Changed the code to the following, but with no sucess:
function updateProfile($parameter, $data, $id)
{
global $conn;
$query = "UPDATE biofood.users
SET $parameter = $data
WHERE id = $id";
$stmt = $conn->prepare($query);
$stmt->execute();
}
This line:
$stmt->execute(array($parameter, $data. $id));
I think should be
$stmt->execute(array($parameter, $data, $id));
(notice the comma after $data)
This might not solve your problem, but it might give you a better indication on where your problem is.
First, you are not checking whether it works or not as your updateProfile function returns nothing.
Modify your updateProfile function, so that it returns the number of rows affected. (BTW this is a safer way to write your function. If you can check or limit the value of $parameter prior to calling this function, it will be less prone to SQL injection.)
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users SET $parameter = ? WHERE id = ?");
$stmt->execute(array($data, $id));
return $stmt->rowCount(); // # of rows affected
}
In the script that calls this function, get the value and send it back as a response. We'll send back a JSON.
$response = array();
try {
$response['success'] = updateProfile($parameter, $data, $id);
} catch (PDOException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
header('Content-Type: application/json');
echo json_encode($response);
In your JavaScript file, make the following change:
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function (data) {
if (data.success) {
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
},
dataType: 'json'
});

php ajax jquery responseText not returned

I am trying to write an insert query with jquery, ajax and php. The record is getting inserted but returns a status error. First I tried to echo the message in php as it didn't work I tried it with print json_encode but both returned the status as error. Why doesn't it return the responseText?
{readyState: 0, responseText: "", status: 0, statusText: "error"}
This is the addmember.php file
<?php
require '../database.php';
function random_password( $length = 8 ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!##$%^&*()_-=+;:,.?";
$password = substr( str_shuffle( $chars ), 0, $length );
return $password;
}
$password = random_password(8);
//$regno=$_POST['regNo'];
$adminno=$_POST['adminNo'];
$batch=$_POST['batchText'];
$type=$_POST["memberType"];
$initials=$_POST["initialName"];
$fullname=$_POST["fullName"];
$address=$_POST["address"];
$telephone=$_POST["contact"];
$email=$_POST["email"];
$nic=$_POST["nic"];
$dob=$_POST["birthDate"];
$priv=$_POST["memberType"];
$userid="";
$sql="select username from memberinfo where username='$adminno'";
$result=mysqli_query($con,$sql);
if(mysqli_num_rows($result)==0){
$sql="insert into memberinfo(username,nic_no,class,name_initial,full_name,address,telephone,email,date_of_birth) VALUES ('$adminno','$nic','$batch','$initials', '$fullname', '$address', '$telephone','$email','$dob')";
$result1=mysqli_query($con,$sql);
$sql = "select * from memberinfo where username='$adminno'";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$userid = $row['user_id'];
}
}
$sql="insert into userlogin(user_id,username,privilege,password) VALUES ('$userid','$adminno','$priv','$password')";
$result2=mysqli_query($con,$sql);
if ($result1 && $result2) {
$message = "<p>New record created successfully</p>";
} else {
$message = "<p>Error: " . $sql . "<br>" . $con->error.".</p>";
}
} else{
$message = "<p>Admission no already exists.</p>";
}
print json_encode($message);
$con->close()
?>
This is the .js file with the ajax function
$(document).ready(function(){
$('#addmember').click(function(){
console.log("addmember");
var adminno=$("#adminNo").val();
var nic=$("#nic").val();
var batch=$("#batchText").val();
var initials=$("#initialName").val();
var fullname=$("#fullName").val();
var address=$("#address").val();
var telephone=$("#contact").val();
var email=$("#email").val();
var dob=$("#birthDate").val();
var priv=$("#memberType").val();
//$("#result").html("<img alt='ajax search' src='ajax-loader.gif'/>");
$.ajax({
type:"POST",
url:"../ajax/addmember.php",
dataType: "json",
data:{'adminNo':adminno, 'nic':nic,'batchText':batch,'initialName':initials, 'fullName':fullname, 'address':address, 'contact':telephone,'email':email,'birthDate':dob,'memberType':priv},
success:function(response){
console.log(response);
$("#result").append(response);
},
error:function(response){
console.log(response);
}
});
});
});
Status zero normally means the page is navigating away. Stop it from happening.
$('#addmember').click(function(evt){ //<--add the evt
evt.preventDefault(); //cancel the click
You are not returning valid JSON from the server. You're json encoding a string, but valid JSON requires an object, or array to encapsulate the day coming back.
So at the very least:
echo json_encode(array($message));
No need for the JSON response. Simply return the message from your PHP script as shown below (note the use of echo and the semicolon following close()):
PHP
$con->close();
echo $message;
Also, remove the JSON filetype from your AJAX call and instead append response.responseText rather than response:
JS
$.ajax({
type:"POST",
url:"../ajax/addmember.php",
data:{'adminNo':adminno,'nic':nic,'batchText':batch,'initialName':initials, 'fullName':fullname, 'address':address, 'contact':telephone,'email':email,'birthDate':dob,'memberType':priv},
success:function(response){
console.log(response);
$("#result").append(response.responseText);
},
error:function(response){
console.log(response);
}
});

PHP json_encode() - SQL limit and AJAX js

I have this PHP:
function getList() {
$sql = " SELECT * FROM list ";
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(array('result' => $result));
$db = null;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
and this javascript:
$.ajax({
type: 'GET',
url: rootURL + '/' + myAPI,
dataType: "json",
success: function(list) {
var list = list.result;
console.log (list);
}
error: function( jqXHR, textStatus, errorThrown ) {
console.log (" errors: " );
console.log (jqXHR);
console.log (textStatus);
console.log (errorThrown);
}
});
now everything was working fine until I added some rows in the list table of my DB.
So now the js list result from AJAX is empty:
{"result": }
The error I receive from AJAX is:
Object { readyState=4, status=200, statusText="OK", more elements...}
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
so I tried to remove: dataType: "json", but result is still empty.
the only way to make it works is to limit the SQL query like this:
$sql = " SELECT * FROM list LIMIT 9 ";
and it works:
{"result":
[
{"ID":"1","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"2","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"3","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"4","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"5","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"6","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"7","name":"...","year":"0","description":"...","image_URL":...","state":"..."},
{"ID":"8","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
{"ID":"9","name":"...","year":"0","description":"...","image_URL":"...","state":"..."},
]
}
I don't understand why there is such a limit. I also tried:
$sql = " SELECT * FROM list LIMIT 10 ";
and so on, but the result is still empty:
{"result": }
Can you help me please?
Thanks
Read the manual at http://php.net/json_encode. It says:
All string data must be UTF-8 encoded.
Make sure your data is in UTF-8 encoding in the database. If not you have to convert it first.
If it is working with LIMIT 9 and not working with LIMIT 10 so problem is in your records after 9th row so please check your 10th row It may have any 'special character', 'new line character' which is creating problem.
There are 2 points I'd like to point out in your code to have a look at. First of all, the construction of the error should be using the json_encode function, which will ensure valid format, so instead of doing echo '{"error":{"text":'. $e->getMessage() .'}}'; you should do
$response = new stdClass();
$response->error = new stdClass();
$response->error->text = $e->getMessage();
echo json_encode($response);
Note, that it looks overly complex, but I tried to retain the format you specified in your example.
The other thing is that Javascript will not like type: 'json' if the correct headers are not set. So what I suggest your PHP function should look like is this:
function getList() {
$response = new stdClass();
$sql = " SELECT * FROM list ";
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$response->result = $result;
unset($db);
} catch(PDOException $e) {
$response->error = new stdClass();
$response->error->text = $e->getMessage();
}
header("Content-Type: application/json");
echo json_encode($response);
exit();
}
I hope this helps!

Categories

Resources