Ajax success return - javascript

Can someone help me with this
I have this php file for insert data into my database and all is sent by ajax function
<?php
header('Content-type: application/json');
ini_set('max_execution_time', 300);
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
$mysqli = new mysqli('localhost', 'root', '', 'ebspma');
// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
$num= $_POST['num'];
$dia = $_POST['dia'];
$sala = $_POST['sala'];
$hora = explode(",", $_POST['hora']);
$a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
$c = array_fill_keys(array_keys(array_diff($a,$hora)),null) + $a;
ksort($c);
for ($i=0; $i<17; $i++){
$horas = $c[$i];
$stmt = $mysqli->prepare("INSERT INTO `ebspma`.`sala_ocupacao` (id_dia, id_sala, id_tempo) VALUES (?, ?, ?);")or die(mysql_error($mysqli));
$stmt->bind_param('ssi', $dia, $sala, $horas);
if(!$stmt->execute()){
echo json_encode(array('status' => 'error','message'=> 'Opppss...Os Registo(s) não foram gravado(s)'));
}
else{
echo json_encode(array('status' => 'success','message'=> 'Registo(s) gravado(s) com sucesso'));
}
$stmt->close();
}
$mysqli->close();
?>
And this my ajax function
function postData(){
var dia = document.getElementById('dia').value;
var sala = document.getElementById('sala').value;
var tempos = [];
var s = document.getElementById('hora');
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var valores = s.options[i].value;
tempos.push(valores);
}
}
console.log(tempos);
var num = document.getElementById('num').value;
var data = 'dia='+ dia + '&sala='+ sala + '&hora='+ tempos + '&num='+ num;
$.ajax({
type: "POST",
dataType: "html",
url: "registerBd.php",
data: data,
success: function (response) {
console.log(response);
$('#ajaxDivOk').css("display", "block");
$('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
alert(response);
},
error:function(response){
console.log("Aqui 2");
alert("something went wrong");
}});
return false;
}
Called by my form like this
<form method="post" id="salas" name="salas" onsubmit="postData()" >
But i have always error in my function even my data is inserted into dabase
New update
New insert php named registerBd.php
<?php
header('Content-type: application/json');
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
$mysqli = new mysqli('localhost', 'root', '', 'ebspma');
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
$num = $_POST['num'];
$dia = $_POST['dia'];
$sala = $_POST['sala'];
$hora = $_POST['hora'];
$a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
$c = array_fill_keys(array_keys(array_diff($a, $hora)), null) + $a;
ksort($c);
for ($i = 0; $i < 17; $i++) {
$horas = $c[$i];
$stmt = $mysqli->prepare("INSERT INTO `ebspma`.`sala_ocupacao` (id_dia, id_sala, id_tempo) VALUES (?, ?, ?);")or die(json_encode(mysqli_error($mysqli)));
$stmt->bind_param('ssi', $dia, $sala, $horas);
if (!$stmt->execute()) {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...Os Registo(s) não foram gravado(s)'));
}
}
echo json_encode(array('status' => 'success', 'message' => 'Registo(s) gravado(s) com sucesso'));
$stmt->close();
unset($stmt);
?>
And modification to ajax
<script>
function postData(){
var dia = document.getElementById('dia').value;
var sala = document.getElementById('sala').value;
var tempos = [];
var s = document.getElementById('hora');
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var valores = s.options[i].value;
tempos.push(valores);
}
}
console.log(tempos);
var num = document.getElementById('num').value;
$.ajax({
type: "POST",
dataType: "json",
url: "registerBd.php",
data : {'dia': dia, 'sala': sala, 'hora': tempos, 'num': num},
success: function (response) {
console.log(response);
$('#ajaxDivOk').css("display", "block");
$('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
alert(response);
},
error: function(jq,status,message) {
console.log( message );
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
return false;
}
</script>
But still have the same problem, and in chrome console the registerBd.php is red after the insert, so i think the problem should be here even if everything is recorded into database
New Update...this is getting really strange
Removed 2 lines in registerDb.php
unset($smtp);
?>
With debug and without
i get this
check image
http://postimg.org/image/8wtwxod3r/
Without debuger
http://postimg.org/image/5nctzrjkv/
Check at the bottom it seems that the registerBd.php is canceled...why?
So now i'm lost
Update 3
Where i call my ajax function
<form method="post" id="salas" name="salas" onsubmit="postData()" >
My ajax function
<script>
function postData(){
var dia = document.getElementById('dia').value;
var sala = document.getElementById('sala').value;
var tempos = [];
var s = document.getElementById('hora');
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var valores = s.options[i].value;
tempos.push(valores);
}
}
console.log(tempos);
var num = document.getElementById('num').value;
$.ajax({
type: "POST",
dataType: "json",
url: "registerBd.php",
data : {'dia': dia, 'sala': sala, 'hora': tempos, 'num': num},
success: function (response) {
console.log(response);
$('#ajaxDivOk').css("display", "block");
$('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
alert(response);
},
error: function(jq,status,message) {
console.log( message );
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
return false;
}
</script>
and my registerBd.php
<?php
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
$mysqli = new mysqli('localhost', 'root', '', 'ebspma');
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
$num = $_POST['num'];
$dia = $_POST['dia'];
$sala = $_POST['sala'];
$hora = $_POST['hora'];
$a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
$c = array_fill_keys(array_keys(array_diff($a, $hora)), null) + $a;
ksort($c);
for ($i = 0; $i < 17; $i++) {
$horas = $c[$i];
$stmt = $mysqli->prepare("INSERT INTO `ebspma`.`sala_ocupacao` (id_dia, id_sala, id_tempo) VALUES (?, ?, ?);")or die(json_encode(mysqli_error($mysqli)));
$stmt->bind_param('ssi', $dia, $sala, $horas);
if (!$stmt->execute()) {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...Os Registo(s) não foram gravado(s)'));
}
}
$response = "Registo(s) gravado(s) com sucesso";
echo json_encode($response);
$stmt->close();
In real mode i have this
Request URL: http://localhost/multiple/registerBd.php
Method: POST
Status: Request was cancelled.
Request Headers
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Origin: http://localhost
Referer: http://localhost/multiple/registo_salas.php
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.44 (KHTML, like Gecko) JavaFX/8.0 Safari/537.44
X-Requested-With: XMLHttpRequest
Request data
dia=2&sala=5&hora%5B%5D=1&hora%5B%5D=2&hora%5B%5D=3&num=3
CallStack
send ([native code]:0:0)
send (https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js:4:25552)
ajax (https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js:4:21305)
postData (registo_salas.php:104:26)
onsubmit (registo_salas.php:116:27)
Update 4
I don't know if if this what you mean...but i don't think it is (my fault...)
<script>
$('#salas').on('submit', function(event) {
event.preventDefault();
function postData(){
var dia = document.getElementById('dia').value;
var sala = document.getElementById('sala').value;
var tempos = [];
var s = document.getElementById('hora');
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var valores = s.options[i].value;
tempos.push(valores);
}
}
console.log(tempos);
var num = document.getElementById('num').value;
event.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
url: "registerBd.php",
data : {'dia': dia, 'sala': sala, 'hora': tempos, 'num': num},
success: function (response) {
console.log(response);
$('#ajaxDivOk').css("display", "block");
$('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
alert(response);
},
error: function(jq,status,message) {
console.log( message );
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
return false;
}
});
i get
Uncaught ReferenceError: postData is not definedonsubmit # registo_salas.php:120

I see a few problems here:
You are sending back json but you specify dataType: "html", in your ajax call. You should change that to dataType: "json",
You are mixing mysql apis:or die(mysql_error($mysqli));You cannot use any mysql_* function as you are using mysqli_*. You need something like: or die(mysqli_error($mysqli));
If you do return json, you need to make sure your error messages are valid json as well, so the second should really be (applies to the other instances too):
or die(json_encode(mysqli_error($mysqli)));
A potential problem is that you are not encoding your query string correctly in your ajax call. You can let jQuery take care of that by using an object:var data = {'dia': dia, 'sala': sala, etc.};
Edit: Based on your last update, it seems that you are not cancelling the default submit event. You do return false from your function, but you don't do anything with that value.
You should change:
<form method="post" id="salas" name="salas" onsubmit="postData()" >
to:
<form method="post" id="salas" name="salas" onsubmit="return postData();" >
Although, as you are using jQuery, a better solution would be to remove the inline javascript and move it to your script section:
$('form').on('submit', function(event) {
event.preventDefault();
// the rest of your javascript that is now in your `postData()` function
});

Related

How to use multiple locations' data from for loop as leaflet markers to use in click event

I have a leaflet map that has markers showing the top cities in a chosen country.
locationList is an array of objects, each one containing info per city (lat, lng, cityName). These values are being used to add markers onto the map, and are also stringified for use in a PHP call to a weather API cURL routine.
I've added popups displaying each city name onto the map successfully through a for loop, however I would like to be able to add functionality to each marker so that when you click on any $cityMarker the weather data for that particular location pops up in a modal (after AJAX call).
At the moment this is only working for the final object in the locationList array, as the click event and subsequent AJAX call is only being fired from the last item of the loop before the click event handler.
Is there an easy way to get around this so that the click event fires for all locations, depending on which one is clicked? I can't figure out how to get all data out of the loop to use individually in $cityMarker.
Thank you !
var locationList = [];
citiesArray.forEach(city => {
locationList.push({
lat: city.lat,
lng: city.lng,
cityName: city.toponymName
});
});
console.log(locationList)
for (var i=0; i < locationList.length; i++) {
console.log(locationList[i])
$cityMarker = L.marker(new L.latLng([locationList[i]['lat'], locationList[i]['lng']]))
.addTo($layers)
.bindPopup('Name: ' + locationList[i]['cityName'])
}
$($cityMarker).on('click', () => {
$.ajax({
url: "getInfo.php",
type: 'POST',
data: {
locationList: JSON.stringify(locationList)
},
success: function(result) {
console.log(result);
for (let i=0; i < result.data.length; i++) {
$('.modal').modal('show');
$('#openWeatherResult').html(result['data'][i]['openWeather']['weather'][0]['description'])
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
console.log(jqXHR);
}
});
});
PHP:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true) / 1000;
$locationList = json_decode($_POST['locationList'], true);
$locationArray = [];
foreach ($locationList as $location){
$data['lat'] = $location['lat'];
$data['lng'] = $location['lng'];
array_push($locationArray, $data);
}
// openweather routine
foreach ($locationArray as $location){
$lat = $location['lat'];
$lng = $location['lng'];
$openWeatherUrl='api.openweathermap.org/data/2.5/weather?lat=' . $lat . '&lon=' . $lng . '&units=metric&appid=demo';
$openWeatherch = curl_init();
curl_setopt($openWeatherch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($openWeatherch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($openWeatherch, CURLOPT_URL,$openWeatherUrl);
$openWeatherResult = curl_exec($openWeatherch);
curl_close($openWeatherch);
$openWeather = json_decode($openWeatherResult, true);
$output['data'][] = ['location' => $location, 'openWeather' => $openWeather];
}
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "mission saved";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
?>
Move the click listener in the loop:
for (var i = 0; i < locationList.length; i++) {
console.log(locationList[i])
const $cityMarker = L.marker(new L.latLng([locationList[i]['lat'], locationList[i]['lng']]))
.addTo($layers)
.bindPopup('Name: ' + locationList[i]['cityName'])
$($cityMarker).on('click', () => {
$.ajax({
url: "getInfo.php",
type: 'POST',
data: {
locationList: JSON.stringify(locationList)
},
success: function(result) {
console.log(result);
for (let i = 0; i < result.data.length; i++) {
$('.modal').modal('show');
$('#openWeatherResult').html(result['data'][i]['openWeather']['weather'][0]['description'])
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus);
console.log(jqXHR);
}
});
});
}
Edit
Your problem is that you always load all weather data and the loop through the data. In the next step you change the html / text of $('#openWeatherResult'), but it can't have multiple htmls / texts so it always overwrides the text before ... so it will always display the last entry of the loop.
I suggest you to overwrite / create new php file for loading the data of a single entry: getSingleInfo.php
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true) / 1000;
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$openWeatherUrl='api.openweathermap.org/data/2.5/weather?lat=' . $lat . '&lon=' . $lng . '&units=metric&appid=demo';
$openWeatherch = curl_init();
curl_setopt($openWeatherch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($openWeatherch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($openWeatherch, CURLOPT_URL,$openWeatherUrl);
$openWeatherResult = curl_exec($openWeatherch);
curl_close($openWeatherch);
$openWeather = json_decode($openWeatherResult, true);
$output['data'][] = ['location' => $location, 'openWeather' => $openWeather];
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "mission saved";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
?>
And then change your ajax call to:
$($cityMarker).on('click', (e) => {
var marker = e.target;
$.ajax({
url: "getSingleInfo.php",
type: 'POST',
data: {
lat: marker.getLatLng().lat,
lng: marker.getLatLng().lng,
},
success: function(result) {

Uncaught SyntaxError: Unexpected token < in JSON at position 0 at Function.parse [as parseJSON] (<anonymous>) at Object.success (script.js:14) [duplicate]

This question already has answers here:
Uncaught SyntaxError: Unexpected token :
(26 answers)
"SyntaxError: Unexpected token < in JSON at position 0"
(40 answers)
Closed 3 years ago.
i am tying to search user search from database database include varchar and image every time i type in search box this error appears in console Uncaught SyntaxError: Unexpected token < in JSON at position 0
Here is my js code
$(function(){
$('#q').keyup(function(){
var q = $(this).val();
var html = '';
$('.form-wrapper').find('.result-wrapper').remove();
if (q !== '' && q !== null) {
$.ajax({
url: 'suggestions.php',
data: {q: q},
success: function (response){
/*var reader = new FileReader();*/
response = $.parseJSON(response);
html = generateDOM(response);
$('.form-wrapper').append(html);
},
error: function(response){
console.log(response);
}
});
}
});
});
function generateDOM(response){
var html = '<div class="result-wrapper"/>';
html += '<ul>';
$.each(response, function(index, value){
html += '<li><img src="'+value.q_links+'"/>'+value.q_title+'</li>';
});
html += '</ul>';
html += '</div>';
return html;
}
and connection to db code
<?php
function connect(){
$connection = mysqli_connect('localhost', 'root', '', 'img');
if (!$connection){
die('Error: Failed to connect DB!!');
}
return $connection;
}
function get_suggestions( $q ){
$connection = connect();
$sql = "SELECT `id`, `q_image`, `q_title`, `q_links` FROM `users` WHERE (`q_title` LIKE '%$q%')";
$result = mysqli_query($connection, $sql);
if ( mysqli_num_rows($result) ){
return mysqli_fetch_all($result, MYSQLI_ASSOC);
}
return false;
}
function debug($arg){
echo '<pre>';
print_r($arg);
echo '</pre>';
exit;
}
?>
please help me to solve this problem
error screenshot
https://drive.google.com/file/d/1S72_AmxILPZHA7nZZ0g4ZZhx0OxD9wjp/view?usp=sharing
Change your php function to
function get_suggestions( $q ){
$connection = connect();
$sql = "SELECT `id`, `q_image`, `q_title`, `q_links` FROM `users` WHERE (`q_title` LIKE '%$q%')";
$result = mysqli_query($connection, $sql);
if ( mysqli_num_rows($result) ){
return json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));
}
return false;
}
And you ajax code to
$(function(){
$('#q').keyup(function(){
var q = $(this).val();
var html = '';
$('.form-wrapper').find('.result-wrapper').remove();
if (q !== '' && q !== null) {
$.ajax({
url: 'suggestions.php',
data: {q: q},
dataType: 'json',
success: function (response){
/*var reader = new FileReader();*/
/*response = $.parseJSON(response);*/
html = generateDOM(response);
$('.form-wrapper').append(html);
},
error: function(response){
console.log(response);
}
});
}
});

How to show the errors through ajax and Jquery in codeigniter

This is my ajax call
function exportCSV(){
var sampleid = $("#sampleid").val();
var scheme = $("#scheme").val();
var v = $("#v").val();
var date = $("#date").val();
var assignedvalue = $("#assignedvalue").val();
var units = $("#units").val();
var assayvalue = $("#assayvalue").val();
var analyte = $("#analyte").val();
var filename=$("#filename").val();
var sample_error=$("#sample_error").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "import/validate_file",
dataType: 'json',
data: {
sampleid: sampleid,
scheme: scheme,
v: v,
date: date,
assignedvalue: assignedvalue,
units: units,
assayvalue: assayvalue,
analyte: analyte,
filename:filename,
sample_error: sample_error
},
success: function (data) {
console.log(data); //as a debugging message.
}
});
}
and this is my controller
<?php
if (!empty($unit_check) and !empty($analyt) and !empty($sch) and count($sample_id) == count(array_unique($sample_id)) and $assigned_check == '1' and $assay_check == '1') {
for ($row = 2; $row <= $lastRow; $row++) {
$data['sample_id'] = $worksheet->getCell($sampleid . $row)->getValue();
$data['scheme'] = $worksheet->getCell($scheme . $row)->getValue();
$data['v'] = $worksheet->getCell($v . $row)->getValue();
$data['units'] = $worksheet->getCell($unit . $row)->getValue();
$data['date'] = $worksheet->getCell($date . $row)->getFormattedValue();
$data['assay_value'] = $worksheet->getCell($assayvalue . $row)->getValue();
$data['assigned_value'] = $worksheet->getCell($assignedvalue . $row)->getValue();
$data['analyte'] = $worksheet->getCell($analyte . $row)->getValue();
$data['trace_id'] = $insert_id;
$this->import_model->insert_data($data);
$response['success'] = true;
}
} else {
$data['sample_id'] = '';
$data['analyte'] = '';
$data['unit_check'] = '';
$data['sch'] = '';
$data['assigned_value'] = '';
$data['assay_value'] = '';
if (count($sample_id) != count(array_unique($sample_id))) {
$data['sample_id'] = '1';
}
if (empty($analyt)) {
$data['analyte'] = '1';
}
if (empty($unit_check)) {
$data['unit_check'] = '1';
}
if (empty($sch)) {
$data['sch'] = '1';
}
if ($assigned_check == '') {
$data['assigned_value'] = '1';
}
if ($assay_check == '') {
$data['assay_value'] = '1';
}
$data['file_name'] = '';
}
?>
I have to show the errors and success message on ajax call.
Right now I'm succeeded in valuating the data and putting it in the database.
But I want to show the success message at the end of the page by clicking the submit button.
And if there is validations error it must shows the errors in that fields at the end of the page
Any help would be appreciated.
Here inside your success method of ajax
success: function (data) {
$("#resultDiv").html(data)
}
Return some real data from your controller in both case success and failed. and based on your data inside success method show your message.
Like:
success: function (data) {
$("#resultDiv").html(data.success) //this requires string to convert your result in string if neccessary
//But you should return a JSON data as msg from your controller
}
You should put a result HTML element for example:
<div id='resultDiv'></div> <!-- to match with #resultDiv -->
Put response data in both condition if success=true and else success=false
In your controller
if(.....){
//what ever check you wanna do
..........
..........
$response['msg']='success';
header('Content-Type', 'application/json');
echo json_encode($response);
}
else{
$response['msg']='failed';
header('Content-Type', 'application/json');
echo json_encode($response);
}
In your ajax
success: function (data) {
$("#resultDiv").html(data.msg)
}
Try something like:
$response = array(
'errCode' = 0,
'errMsg' = 'msg'
);
return this kind of array by json_encode() from php to ajax() call and use it in ajax() success like:
var data = JSON.parse(response);
alert(data.errMsg);
You can also put a check on errCode like:
if(errCode == 0) { something }
if(errCode == 1) { something }

How to stop return undefined for json_encode

I am sent many dynamic post ids from a page and a php server side page(server.php) make a query with those id to find out newly added data in mysql.
If it not found any newly added data in mysql, it's return a undefined value. So as per my script, It's append a undefined one after one at a time interval.
How to stop this undefined value?
my javascript:
var CID = []; // Get all dynamic ids of posts (works well)
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});
function addrep(type, msg){
CID.forEach(function(id){
$("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul><div class='cdomment_text'>"+ msg.detail +"</ul></div>");
});
}
function waitForRep(){
$.ajax({
type: "GET",
url: "server.php",
cache: false,
contentType: "application/json; charset=utf-8",
data: {
// this way array containing all ID's can be sent:
CID : CID
},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(
waitForRep,
15000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(
waitForRep,
15000);
}
});
}
$(document).ready(function(){
waitForRep();
});
server.php
while (true) {
if($_REQUEST['CID']){ //cid got all dynamic post id as: 1,2,3,4 etc.
foreach($_REQUEST['CID'] as $key => $value){
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"SELECT * FROM reply WHERE qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
$data = array();
while($rows = mysqli_fetch_assoc($res)){
$data[]=$rows;
$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
$data['username'] = $rows['username'];
$data['description'] = $rows['description'];
$data['date'] = $rows['date'];
//etc. all
$id = $rows['id'];
$qazi_id = $rows['qazi_id'];
$username = $rows['username'];
$description = $rows['description'];
//etc. all
} //foreach close
} //foreach close
if ($description=="") {$detail .= '';}
else {$detail .=''.$description.'';}
$data['detail'] = $detail;
// do somethig
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} //request close
sleep(5);
} //while close
Edit your addrep function to not insert if it's undefined:
function addrep(type, msg){
CID.forEach(function(id){
if(msg.detail != "undefined") {
$("#newreply"+id).append("+ msg.detail +");
}
});
}
Or just break it if undefined:
function addrep(type, msg){
CID.forEach(function(id){
if(msg.detail == "undefined")
break;
$("#newreply"+id).append("+ msg.detail +");
});
}

How to cross check if data is present in the database using ajax method?

This is the JavaScript code which checks for the validation of the mobile number data (with other data) and forwards it to validate_user.php which stores the mobile number.
But I want to store the data of only those users whose mobile number exists in another table or else I want to display an error message saying 'User not present in the database'.
I need help. What do I do?
Thanks in advance.
JavaScript
$(document).ready(function() {
$("#user_submit_form").submit(function() {
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
if (mobile.length != 10 || !(mobile[0] == 7 || mobile[0] == 8 || mobile[0] == 9)) {
alert('Please enter a valid mobile number');
} else {
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
}); // End ajax method
alert('Thank You');
window.location.reload();
}
});
});
This is the server side PHP code:
<?php
session_start();
require("config/config.php");
if(isset($_POST['user_submit']))
$mobile =mysql_real_escape_string ($_POST['mobile']);
$dob = mysql_real_escape_string($_POST['dob']);
$hostname = '';
$database = '';
$username = '';
$password = '';
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
die("Unable to Connect server!".mysql_error());
}
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT mobile FROM mobile_db WHERE mobile="'.$mobile.'"');
if(mysql_num_rows($sql) == 1)
{
$query = 'INSERT INTO taj_contact_info (chassis,pin,title,fname,lname,email,mobile,dob,anniversary,company,designation,home_business,add1,add2,city,state,pincode,timestamp) VALUES("'.$mobile.'","'.$dob.'",'.strval(time()).')';
$sql1= mysql_query($query);
}
else
{
return true;
}
?>
$(document).ready(function() {
$("#user_submit_form").submit(function() {
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
if (mobile.length != 10 || !(mobile[0] == 7 || mobile[0] == 8 || mobile[0] == 9)) {
alert('Please enter a valid mobile number');
} else {
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success: function(json){
if(json.error){
alert(json.error)// or do whatever you want
}
else{
alert(json.success) // there your made a success call the do your staff
}
}
}); // End ajax method
alert('Thank You');
window.location.reload();
}
});
});
**The Server Side php**
<?php
session_start();
require("config/config.php");
if(isset($_POST['user_submit']))
$mobile =mysql_real_escape_string ($_POST['mobile']);
$dob = mysql_real_escape_string($_POST['dob']);
$hostname = '';
$database = '';
$username = '';
$password = '';
$json = array();
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
$json['error'] = "Unable to Connect server!".mysql_error();
}
if(empty($json)){
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT mobile FROM mobile_db WHERE mobile="'.$mobile.'"');
if(mysql_num_rows($sql) == 1)
{
$query = 'INSERT INTO taj_contact_info (chassis,pin,title,fname,lname,email,mobile,dob,anniversary,company,designation,home_business,add1,add2,city,state,pincode,timestamp) VALUES("'.$mobile.'","'.$dob.'",'.strval(time()).')';
$sql1= mysql_query($query);
$json['success'] = "Successfully inserted";
}
else
{
$json['error'] = 'A Fake Number';
}
}
echo json_encode($json);
You can verify this using success response
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success:(function(result){
if(empty(result)){
return false;
}else{
return true;
}
}));
});

Categories