How to read a json file which contains an array from javascript - javascript

Please guys help me because i can't find out what i can do in order to read my javascript a json file which contains an array with one element.
My php file is working fine and the output is a .json file which contains this line: {"posts":[["30"]]}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
$sql= "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$response = array();
$posts = array();
$result=mysqli_query($link, $sql);
while($row=mysqli_fetch_assoc($result)) {
$site_id=$row['site_id'];
$posts[] = array($site_id);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
// Close connection
mysqli_close($link);
?>
Can anybody help me what i have to do (without using ajax) in order my javascript function reads that value? I want to rerad this value cause i want to manipulate this number.
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}
while(flag1!=false);
$("#user_id").val(selection)
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}
while(flag2!=false);
$("#book_id").val(selection2)
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}
while(flag3!=false);
$("#game_id").val(selection3)
//i do not want to do with ajax!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/PHP/loo.php',
data: $('#LoadGame').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
//alert('bingo!');
window.location.href='https://support.wwf.org.uk/';
//document.location.replace('https://developer.mozilla.org/en-US/docs/Web/API/Location.reload');
}
else {
alert('No!');
}
}
});
}
Thank you for your help!

Assuming this PHP code runs during your doc request,
You can read that json if you put it in a script tag
<script type="text/javascript">
window.myJson = <?php echo(json_encode($response)); ?>
</script
and it will be accessible as window.myJson in frontend

Related

How do I use Ajax to verify query results?

I have an HTML form and a JavaScript file that processes the form data (The event onsubmit=validate()). I am trying to use Ajax to send an ID to a PHP script. The PHP script should send back an array (JSON?). Each element in that array will be a column from a query, based on the ID that was sent. Then I want to compare the results found in the database with the one the user entered in the HTML form. My question are: Is this good practice? How can I implement this idea if it is, if not, what is the better approach?
I am putting what I have so far and will add to the morning. I have not been able to find what I am looking for on my own. Here is my code so far:
function validate() {
var first=document.getElementById("b1j").value;
var last=document.getElementById("b2j").value;
var password=document.getElementById("b3j").value;
var ID=document.getElementById("b4j").value;
var number=document.getElementById("b5j").value;
var email=document.getElementById("b6j").value;
var cbox=document.getElementById("check");
if(first.search(/^[aA-zZ]+[aA-zZ]$/) < 0) {
alert("Invalid first name.");
return;
}
if(last.search(/^[a-zA-Z]+[a-zA-Z]$/) < 0) {
alert("Invalid last name.");
return;
}
if(password.search(/(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*()_\-=+<>]).{3,10}/) < 0) {
alert("Invalid password.");
return;
}
if(ID.search(/[0-9]{4}/) < 0) {
alert("Invalid ID");
return;
}
if(number.search(/^(\d{3}[\s\-]){2}[0-9]{4}/) < 0) {
alert("Invalid phone number.");
return;
}
if(email.search(/^\w*#\w{2,5}\.com$/) < 0 && cbox.checked) {
alert("Invalid email.");
return;
}
verify(ID);
}
function verify(id) {
//communicate with the php script
//if not verfied, stay on same page and give an alert saying why the credentials are wrong.
//verfied? Go to the page that is being requested in the options (implement in the php script along with session info)
var xhr = new XMLHttpRequest();
xhr.onload = function () {
//Completely lost beyond here.
const result = JSON.parse(this.responseText);
if (result.found !== 0) {
}
else {
}
};
alert("sending");
xhr.open("GET", "../php/vmc4a4.php?id="+ID, false);
xhr.send();
alert(errorMsg);
}
<?php
//Server info hidden
$con = mysqli_connect($servername,$username,$password,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$id = $_GET['id'];
$query = "SELECT * FROM Stylists WHERE Stylists.id = '$id';";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($result);
}
?>

jQuery AJAX Getting json parseError in the console and responses goes to error function but php script runs fine

I tried researching a lot before posting here.
There are two files login.php and login-validation.php
Login.php file contains code including login form and jQuery AJAX script to call login.validation.php
--- Code of login.php ---
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
mobile_no = $('#mobile_no').val();
upassword = $('#upassword').val();
console.log(mobile_no, upassword);
$.ajax({
type: "POST",
url: "server/login-validation.php",
data: {
Mobile_no: mobile_no,
Password: upassword
},
cache: false,
dataType:'json',
success: function(response) {
console.log("Data gone successfully");
if(response["type"] == 'LoginSuccess'){
$('#success-message').text(response); // This works but not below ones
}
if(response["type"] == 'WrongCredentials'){
$('#success-message').text(response);
}
else{
$('#success-message').text(response);
}
},
error: function(xhr, textStatus, errorThrown){
console.log(xhr.responseText); Shows my echo message i.e. Wrong credentials for wrong credentials
console.log(textStatus); // Shows parseError
console.log(errorThrown); // Shows SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
}
});
});
});
</script>
---Code of login.validation.php---
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
echo "Wrong credentials". $mysqlconnect->error;
}
}
else{
$message["type"] = 'WrongMobile';
echo "Mobile number doesn't exists";
}
header('Content-type: application/json');
echo json_encode($message);
?>
Tried dataType: 'json' - Didn't work
Tried without dataType - Didn't work
Php script is running properly with right error messages for different "if" statements but AJAX responses goes to error:function() rather than success: function()
In the network tab - The response type is JSON and it displays [type] i.e [WrongCredentials]
Not understanding what is wrong here. Any help would be appreciated.
You need to parse the JSON response using jQuery.parseJSON()
var data = jQuery.parseJSON(response);
Now, you can check it
if(data.type == "LoginSuccess"){
// do something
}elseif(data.type == "Wrong Password"){
// do something else
}
And remove echo from your php code
session_start();
$message = array(); //Creating array variable to display custom messages depending on [TYPE]
//Require DB
require_once('db.php');
//Get values from the login form
$Mobile_number = $mysqlconnect->real_escape_string(trim($_POST['Mobile_no']));
$Password = $mysqlconnect->real_escape_string(trim($_POST['Password']));
//Query database for valid input match
$validation = "SELECT * from team_captain WHERE Mobile_Number = '$Mobile_number'";
$query = $mysqlconnect->query($validation);
$result = mysqli_num_rows($query);
if($result > 0){
$fetch_pass = mysqli_fetch_array($query);
$password_hash = $fetch_pass['User_Password'];
if(password_verify($Password,$password_hash))
{
$message["type"] = 'LoginSuccess';
$_SESSION['sess_username'] = $fetch_pass['Full_Name'];
}
else{
$message["type"] = 'WrongCredentials';
}
}
else{
$message["type"] = 'WrongMobile';
}
header('Content-type: application/json');
echo json_encode($message);
?>

How to update chat room with PHP and Javascript

I have an issue displaying messages from my database. My site has a simple chat room which was working perfectly when reading/writing to a textfile. I am now trying to link it to a database with a table called messages. Whilst I am writing to the table OK, messages are not being displayed on the screen.
By using POSTMAN, I know that I am successfully talking to the backend because when I run a request - {"state":1,"text":["Welcome all users!"]} is returned, which is the last message I had typed, and the json echo ($log) is working.
Apart from an updateChat() function (posted below) I have a function titled getState() which gets the current state of the chat (number of lines, whether new lines added).
Since my SQL queries seem to be working fine, is there an issue with my updateChat() or ()getState function?
Admittedly, I have never built a chatroom before and I am a bit stuck on where to go next.
Thanks for any help or advice!
****chat.js****
//Updates the chat
function updateChat() {
if (!instanse) {
instanse = true;
$.ajax({
type: "POST",
url: "process.php",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function (data) {
if (data.text) {
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($( data.text[i] + "</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
}
});
} else {
setTimeout(updateChat, 1500);
}
}
process.php
case('getState'):
$lines = "SELECT messageBody, timeSent, nickname FROM message ORDER BY timeSent";
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
$lines = "SELECT messageBody, timeSent, nickname FROM message ORDER BY timeSent";
$result = mysqli_query($conn, $lines);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$message = $row['messageBody'];
$time = $row['timeSent'];
$nickname = $row['nickname'];
}
}
$count = count($lines);
if ($state == $count) {
$log['state'] = $state;
$log['text'] = false;
} else {
$text = array();
$log['state'] = $state + count($lines) - $state;
$text[] = $message = str_replace("\n", "", $message);
}
$log['text'] = $message;
break;
Try catching errors with ajax, if there are, show us.
regardless,
$('#chat-area').append($( data.text[i] + "</p>"));
this will not work. try this:
$('#chat-area').append("<p>" + data.text[i] + "</p>");

How to parse large data via POST query

I am creating a webpage having Excel like features to create a Plan.For this i need to fill an initial form and click on submit button , then submit the form using ajax to a server side PHP script which inserts these records to a Mysql table.
But the issue is i can only transfer 1-2 records of table using the POST Query as there is a limit to it.What should i do in this case?Is there any other way of doing it without expanding the POST query limit?
My Front end code(.js)
</script>
buttons.save.addEventListener('click', function() {
var r1 = hot.countRows() - hot.countEmptyRows() - 1;
var c1 = hot.countCols()- 1 ;
var data = String(hot.getData(0,0,r1,c1));
data = data.replace(/,/g,'');
document.getElementById('all_data').value= JSON.stringify(hot.getData(0,0,r1,c1));
document.getElementById('colheaders').value=JSON.stringify(hot.getColHeader());
console.log(hot.getInstance());
var testplan_name = document.getElementById('feature_name').value;
var product = document.getElementById('product').value;
var release = document.getElementById('release').value;
var pv_engg = document.getElementById('pv_engg').value;
var pe_engg = document.getElementById('pe_engg').value;
var rd_engg = document.getElementById('rd_engg').value;
var tp_completion = document.getElementById('tp_completion').value;
var at_completion = document.getElementById('at_completion').value;
var all_headers = document.getElementById('colheaders').value;
var all_data = document.getElementById('all_data').value;
var maker = document.getElementById('maker').innerHTML;
var datastring = 'testplan_name='+testplan_name+'&product='+product+'&release='+release+'&pv_engg='+pv_engg+'&pe_engg='+pe
_engg+'&rd_engg='+rd_engg+'&tp_completion='+tp_completion+'&at_completion='+at_completion+'&headers='+all_headers+'&all_data='
+all_data+'&maker='+maker;
if(testplan_name=="" || pv_engg =='' || pe_engg== '' || rd_engg== '' || product=='' || release=='') {
else if(data=="") {
alert("For creating a testplan , you need to fill this table.");
}
else {
alert(datastring);
$.ajax({
url :"save_create_pro.php",
type :"POST",
data : datastring,
cache : false,
success :function(result) {
console.log(result);
alert(result);
alert("Form Submitted successfully");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
return false;
});
});
</script>
My Backend php code:
<?php
$dbh=mysql_connect('noiwebfarmo','abc','xyz');
if(! $dbh ) {
die('Could not connect: ' . mysql_error());
}
$database=mysql_select_db('testmohit');
$testplan_name=$_POST['testplan_name'];
$product=$_POST['product'];
$release=$_POST['release'];
$pv_engg=$_POST['pe_engg'];
$pe_engg=$_POST['pe_engg'];
$rd_engg=$_POST['rd_engg'];
$tp_completion=$_POST['tp_completion'];
$at_completion=$_POST['at_completion'];
$maker=$_POST['maker'];
$headers=stripslashes($_POST['headers']);
$all_data = stripslashes($_POST['all_data']);# to remove \ before " that occur when parsed through ajax
$headers=preg_replace('/\["/','',$headers);
$headers=preg_replace('/"\]/','',$headers);
$headers=split('","',$headers);
for($j=0;$j<count($headers);$j++) {
$headers[$j]= str_replace(' ','_',strtolower("$headers[$j]"));
}
$date=date('Y-m-d');
$all_data=preg_replace('/\[\["/','',$all_data);
$all_data=preg_replace('/"\]]/','',$all_data);
$rows_data=split('"\],\["',$all_data);
or($i=0;$i<count($rows_data);$i++) {
$data[$i] = split('","',$rows_data[$i]);
}
$result = array();
foreach($data as $key => $val){
$temp = array();
foreach($val as $k => $v){
$temp[$headers[$k]] = $v;
}
$result[] = $temp;
}
#print $all_data;
print count($result);
print_r($result);
for($i=0;$i < count($result);$i++) {
$temp = $result[$i];
$query = "INSERT INTO testplans (testplan_name,product,pro_release,percent_tpcompletion,percent_atcompletion,pv_engineer,rnd_engg,pe_engg,tc_name,cell_name,customer_name,flops,title,status,mfix_ccr,test_scenerio,expected_results,ccr_no,ccr_status,remarks,create_date,maker) VALUES ('$testplan_name','$product','$release','$tp_completion','$at_completion','$pv_engg','$rd_engg','$pe_engg','$temp[testcase_name]','$temp[cell_name]','$temp[customer]','$temp[flops]','$temp[title]','$temp[status]','$temp[mfix_ccr]','$temp[scenerio_brief_description]','$temp[expected_results]','$temp[ccr_no]','$temp[ccr_status]','$temp[remarks]','$date','$maker')";
mysql_select_db('testmohit');
$enter=mysql_query($query,$dbh);
if(! $enter) {
die('Could not enter data: ' . mysql_error());
}
}
# echo "$query Entered data successfully";
mysql_close($dbh);
?>
Please provide a solution to insert large no. of rows of handson table without expanding the size of query string .What can be the solution of this problem.
Thanks in advance.

EOF / Failed to load error when calling PHP file with AJAX

Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.

Categories