how to check whether request is made or not - javascript

i am using contenteditable property in p tag .. the code is
<p contenteditable="true" id="Option1_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px "><?php echo ' '.'A.'.' &nbsp'.$question1['Option1'];?></p>
<p contenteditable="true" id="Option2_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px "><?php echo ' '.'B.'.' &nbsp'.$question1['Option2'];?></P>
and jquery to make a request to make request
document).ready(function(){
$("p[contenteditable=true]").blur(function(){
var msg = $(".alert");
var newvalue = $(this).text();
var field = $(this).attr("id");
$.post("ajax.php",field+"="+newvalue,function(d){
var data = JSON.parse(d);
msg.removeClass("hide");
if(data.status == '200'){
msg.addClass("alert-success").removeClass("alert-danger");
}else{
msg.addClass("alert-danger").removeClass("alert-success");
}
msg.text(data.response);
setTimeout(function(){msg.addClass("hide");},3000);//It will add hide class after 3 seconds
});
});
});
and then php to update my mysql database on receiving the request
<?php
$response = NULL;
$status = http_response_code(406);
if(!empty($_POST)){
session_start();
$mock_test_name=$_SESSION['mock_test_name'];
$num_of_sections = $_SESSION['num_of_sections'];
$school_name = $_SESSION['school_name'];
$class_name = $_SESSION['class_name'];
$section_name = $_SESSION['section_name'];
$con = mysqli_connect("localhost","root","","onlinetest");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$table_space = "$school_name $class_name $section_name $mock_test_name";
$table = str_replace(" ", "_", $table_space);
$table_space1 = "$school_name $class_name $section_name";
$table1 = str_replace(" ", "_", $table_space1);
$table_space2 = "$table1 $table";
$table2 = str_replace(" ", "_", $table_space2);
$table2 = strtolower($table2);
foreach($_POST as $key=>$value){
$key = strip_tags(trim($key));
$value = strip_tags(trim($value));
$explode = explode("_",$key);
$user_id = $explode[1];
$field_name = $explode[0];
if(isset($user_id)){
$update = false;
$selectData = mysqli_query($con,"SELECT " + $field_name + " FROM " + $table2 + " WHERE question_id='" + $user_id + "'"); //Selecting data from MySql
$result = mysqli_fetch_assoc($selectData); //Fetching Data
if($result[$field_name]!==$value){ //Checking if the Value is modified
$update = mysqli_query($con,"UPDATE" + $table2+ "SET" + $field_name+"="+$value+ "WHERE question_id='"+$user_id+"'"); //Updating MySQL if value is Modifie
}
//Update the users Table
if($update){
$response = "User Details Updated";
http_response_code(200); //Setting HTTP Code to 200 i.e OK
}else{
$response = "Not Modified";
http_response_code(304); //Setting HTTP Code to 304 i.e Not Modified
}
}else{
$response = "Not Acceptable";
}
}
}
echo json_encode(array(
"status"=>$status,
"response"=>$response
));
?>
But i think the request is not made properly as the database is not getting updated.. Please tell me how to check if a request has been made... or am i making error somewhere in writing code ??

Your mysqli_query function is formed incorrectly. You have to escape out of the parentheses in order to drop in variables.
You need to do something like
mysqli_connect($con, "SELECT " + var1 + " FROM " + var2);
or you'll end up making a query for
EDIT:
For a more apt example, the line
$selectData = mysqli_query($con,"SELECT $field_name FROM $table2 WHERE question_id='$user_id'");
should be
$selectData = mysqli_query($con,"SELECT " + $field_name + " FROM " + $table2 + " WHERE question_id='" + $user_id + "'");
You'll notice the main difference, especially in coloring between the two, signifying that in the first one, the variables $field_name, $table2, and $user_id are all being interpreted as part of the query. You don't want the NAME of the variable, you want the VALUE of it instead, so you need to concatenate the strings together.
This is just one of the multiple similar fixes you'll need to do for your multiple queries. Every place the editor is marking the thing you're trying to use as a variable as part of the string, take the same steps to concat the strings.

You need to change your code like this,
ajax code
$.ajax({
type:"post",
url:"ajax.php",
data: "your data",
success:function(d){
console.log(d);
}
});
php code:
$table_space = $school_name." ".$class_name." ".$section_name." ".$mock_test_name;
$table = str_replace(" ", "_", $table_space);
$table_space1 = $school_name." ".$class_name." ".$section_name;
$table1 = str_replace(" ", "_", $table_space1);
$table_space2 = $table1." ".$table;
$table2 = str_replace(" ", "_", $table_space2);
$table2 = strtolower($table2);

Related

How to handle PHP session variables on AJAX call?

When I try to get a Session variable into a php script called with AJAX to make a MySQL query it gives me ""
I've tried passing the id using a hidden_input filled with php at the loading of my web page and the function worked! but when I try to catch the session variable directly from the script called by the AJAX it stops working again :(
This is the code where I set my php variables, I call this script directly from a html form.
<?php
if(isset($_POST['empresa']))
{
if(isset($_POST['usuario']))
{
if(isset($_POST['password']))
{
$empresa = $_POST["empresa"];
$usuario = $_POST["usuario"];
$password = $_POST["password"];
$host = "localhost";
$bd = "nominet_Directorio_Web_Beta";
$us = "nominet_Marvin2";
$pas = "NominetBD2019!";
error_reporting(0);
$con = new mysqli($host, $us, $pas, $bd);
if($con->connect_errno)
{
echo "Error de conexión al servidor de base de datos...";
exit();
}
mysqli_set_charset('utf8');
$query = "SELECT `Tbl_Usuarios`.`Id`, `Tbl_Usuarios`.`Fk_Empresa`, `Tbl_Usuarios`.`Tipo_Usuario` FROM `Tbl_Usuarios` INNER JOIN `Tbl_Empresas` ON `Tbl_Usuarios`.`Fk_Empresa` = `Tbl_Empresas`.`Id` WHERE `Tbl_Usuarios`.`Usuario` = '" . $usuario . "' AND `Tbl_Usuarios`.`Password` = '" . $password . "' AND `Tbl_Empresas`.`Razon_Social` = '" . $empresa . "'";
//$query = "SELECT `Tbl_Administradores`.`Id` FROM `Tbl_Administradores` WHERE `Tbl_Administradores`.`Usuario` = '" . $usuario . "' AND `Tbl_Administradores`.`Password` = '" . $password . "'";
$resultado = mysqli_query($con, $query);
$res= mysqli_fetch_array($resultado);
if($res["Id"] > 0)
{
session_start();
$_SESSION["Id"] = $res["Id"];
$_SESSION["Empresa"] = $res["Fk_Empresa"];
$_SESSION["Usuario"] = $usuario;
$_SESSION["Tipo_Usuario"] = $res["Tipo_Usuario"];
header("Location: ../SISTEMA/");
}
else
{
header("Location: ../?error=0");
}
}
else
{
header("Location: ../?resp=error1");
}
}
else
{
header("Location: ../?error=2");
}
}
else
{
header("Location: ../?error=3");
}
?>
The code below it's my JavaSCript (JQuery) function where I call my php script.
function contactosGeneral(){
//var empresa = $('#hidden1').val();
var funcion = "contactosGeneral";
$.ajax({
url: "/PHP/PRUEBA.PHP",
type: "POST",
data: {funcion: funcion},
error: function(xhr){
window.location.href = "../REPORTES/?resp=0";
},
success: function(respuesta) {
var arreglo = JSON.parse(respuesta);
$('#p_contactos').html(arreglo[0]["resp"]);
}
});
}
this is my php script, here I call the DataBase.
<?php
$funcion = $_POST['funcion'];
switch($funcion){
case 'contactosGeneral':
break;
}
function contactosGeneral(){
require("../../ABRIR_CON.php");
//$empresa = $_POST['empresa'];
session_start();
$empresa = $_SESSION["Empresa"];
$sql = 'SELECT COUNT(`Tbl_Contactos`.`Id`) AS "resp" FROM `Tbl_Contactos` WHERE `Tbl_Contactos`.`Fk_Empresa` = ' . $empresa;
$query = mysqli_query($con, $sql);
$json = array();
while($row = mysqli_fetch_array($query))
{
$json[]=array('resp'=>$row['resp']);
}
$resources_JSON_array = json_encode($json);
echo $resources_JSON_array;
require("../../CERRAR_CON.php");
}
?>
I know there's a lot I can improve in my code, but i'm not here for that reason, just help my with my question. thanks :)
As #Barman said, I never called my php function contactosGeneral() into my switch(){} code :B

Unable to send data from JavaScript to PHP file using ajax

I'm unable to retrieve the q parameter sent from the PHP.
When I run my code, null values get inserted in my database.
Here are the concerning parts of my code:
My JavaScript function:
function load_now(str){
//alert(str);
var id = str.split("+")[0];
var r = confirm("Start load process for scooter " + str + "?");
if (r == true) {
var xmlhttp = new XMLHttpRequest();
//console.log(str);
xmlhttp.open("GET", "load_scooter_action.php?q=" + str, true);
xmlhttp.send();
}
}
and my load_scooter_action.php file:
<?php
require "checkUserModel.php";
require "databaseController.php";
$databaseController = new DatabaseController();
$databaseController->startConnexionToDatabase();
$conn = $databaseController->getConn();
$dateObject = new DateTime();
$startTime = $dateObject->format('Y-m-d H:i:s');
$user = $_SESSION['user-id'];
// get the q parameter from URL
$q = $_REQUEST["q"];
//forme:(scooter, lat, lng, chg);
$val = explode("+",$q);
$scooter = val[0];
$lat = val[1];
$lng = val[2];
$chg = val[3];
echo "<script type='text/javascript'> console.log(".$q.")</script>";
$sql = "UPDATE `scooters` SET `disponible` = '0' WHERE `scooters`.`numero` = '$scooter';";
if ($conn->query($sql) === TRUE) {
$add = "\nScooter Taken";
} else {
$add = "Error Taking scooter" . $conn->error;
}
$sql = "
INSERT
INTO Reloads(scooter, user, initialLoad, finalLoad, sourceX, sourceY,destinationX, destinationY, startTime,endTime)
VALUES ('$scooter','$user','$chg',null,'$lat','$lng',null ,null, '$startTime', null)";
if ($conn->query($sql) === TRUE) {
//echo "\nNew record created successfully";
//echo '<script>window.location.href = "../php/scooterMapIndex.php";</script>';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Could you help me have a clear understanding of my mistake?
Thanks in advance.
EDIT
str is has the following form 599+50.8037+4.32782+4
Two mistakes:
The first one is a quick fix. Replace val with $val
The second one is that, although str is of the form 599+50.8037+4.32782+4 in the .js file, $q gets retrieved without the + characters in the .php file. Therefore it has to be split appropriately.
Can you show me that what is passed in str or which value is passed in str load_now function. Do you get value when you alert(str)?
If yes then try below function
$.ajax({
type: 'GET',
url: 'follow_user.php?user_id='.urlencode($user_id),
success: function(data) {
alert('done');
}
});
Thanks

Unwanted JSON Response

I'm using this small JSON function with a database.
<script>
$(document).ready(function () {
var url = "Database.php";
$("#jsondata tbody").html("");
$.getJSON(url, function (data) {
$.each(data.users, function (i, user) {
var songdetails = "<p>"
+ "<p>" + user.Title + "</p>"
+ "<p>" + user.ArtistNumber + "</p>"
+ "<p>" + user.TrackTime + "</p>"
+ "<p>" + user.Composer + "</p>"
+ "<p>" + user.Lyricist + "</p>"
+ "</p>";
$(songdetails).appendTo("songlist");
});
});
});
</script>
This produces this in the browser, which I don't want/need.
{"users":[{"Title":"Anyway","ArtistNumber":"2","TrackTime":"167","Composer":"John
Glaze","Lyricist":"Kellee
Maize","FileLocation":"public/Anyway.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"One
Way Heartbeats","ArtistNumber":"4","TrackTime":"187","Composer":"Bill
Bobs","Lyricist":"Michael
McEachern","FileLocation":"public/OneWayHeartbeats.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Parallel
Me","ArtistNumber":"3","TrackTime":"192","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"private/ParallelMe.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"1"},{"Title":"Poisoned
Oxygen","ArtistNumber":"3","TrackTime":"177","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"public/PoisonedOxygen.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Xmas
Prison Blues","ArtistNumber":"1","TrackTime":"192","Composer":"Steve
Perry","Lyricist":"Steve
Perry","FileLocation":"private/XmasPrisonBlues.wma","rated":"0","scores":"[0,0,0,0,0]","free":"1"}]}
Any ideas on how to hide it or remove it from coming up?
Thanks
This is the Database.php:
<?php
$Hostserver = "localhost";
$databUser = "ee2800";
$databPass = "secret";
$databDatabase = "ee2800";
$database = new mysqli ($Hostserver, $databUser, $databPass, $databDatabase);
if ($database) {
mysqli_select_db($database, "ee2800");
//echo ("Successfully connected to database!");
} else {
die ("<strong>Error:</strong> Failed to connect to the database.");
}
$var = array();
$sql = "SELECT * FROM songs";
$result = mysqli_query($database, $sql);
while ($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"users":' . json_encode($var) . '}';
?>
Using jQuery 1.10.2
The songlist element is found here
<?php
// The system queries the database to obtain a result set containing no more than 10 artists //
if ($result = $database->query( "SELECT * FROM `artist` ORDER BY `artist`.`ArtistNumber` ASC LIMIT 10")) {
while ($row = $result->fetch_row()) {
echo "<div id='artist{$row[2]}'>";
echo "<p>Artist: {$row[0]} {$row[1]}</p>";
echo '<p><div id= songlist> </div> </p>';
//div tag 'songlist' adds all data from json and pastes into this div id //
// echo '<p>Songs</p>';
//onlick function echo'd anchor tag//
echo "</div>";
// Songs dont display onclick however retrieved data using jSON can't seem to target where to put the information //
}
}
$database->close();
?>
And basically whenever I run these files, I get that long string I stated at the beginning as a response in my browser everytime.
Well your PHP appears to be returning a valid json string, but it is not being coverted automatically to a json object so that it can be processed by javascript as an object.
You could try forcing the parse to a json object like this
$.getJSON(url, function (data) {
data = $.parseJSON(data);
$.each(data.users, function (i, user) {

Getting javascript response from a PHP login function

public function login($username,$password) {
$linkingcon = $this->getConnection();
$sqlquery = "SELECT ac.userID,ac.name,us.usertype FROM users us JOIN accounts ac ON us.userID = ac.userID WHERE us.username='$username' AND us.password='$password';";
$result = mysql_query($sqlquery , $linkingcon);
$this->throwMySQLExceptionOnError($linkingcon);
$row = mysql_fetch_array($result);
$survey = new stdClass();
if($row) {
$res->userID = (int)$row['userID'];
$res->name = $row['name'];
$res->usertype = (int)$row['usertype'];
$string = rand() . 'SurveyLand' . rand() . $username. $password;
$_SESSION['SURVEYLAND_KEY'] = md5($string);
} else {
$res = false;
}
return $res;
}
Hi everyone,
im in a spot of bother regarding a conversion, I need to get a Javascript response from the above php function by calling that php function from another script(HTML)...
P.S
i saw an example in the internet like the below, cant i use method like below get the call
client.sendRequest('hello', null, { 'async': false }, function(rtn) {
if (rtn.isError())
document.write('<li>Request hello error: ' + rtn.getErrorMessage() + "</li>");
else
document.write('<li>Request hello result: ' + rtn.getResult() + "</li>");
});
If you are using ajax return response in json format
return json_encode($res);
Or just print response in script tag
<script>
var res = <?php echo json_encode(login('username','password')); ?>
</script>

How to properly load one ajax request after another

I am creating a messaging system for a website that I am making. Basically, it consists of clicking one button and two Ajax Requests afterwards. I am not even sure I am going about this the right way. On click of the button the first Ajax starts to call. The first ajax request loads a file that loads the style of the messages and retrieves them from a database. The problem I am having is that the first request sometimes takes to long to finish and the other request does not get complete. Another problem I am having is that if I put an "animation delay" type thing on it then it will look like the page it running slow. You can run an example at "http://www.linkmesocial.com/linkme.php?activeTab=mes" you must type or copy and past the whole length for it to work otherwise you will redirect to the login page. Any advice would be AWESOME! If there is some easier way to set up a messaging system please feel free to give me some advice or direct me to a tutorial. THANK YOU SO MUCH!
I would also like the know if this is a good practice. Please :)
My Original file. On click of class "mes_tab" a form is submitted. also the function mes_main() is called.
session_start();
$username = $_SESSION['user'];
$messages = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username'");
echo "<div id=\"mes_main-bar_top\" class=\"center\">Messages</div>";
echo "<div id=\"mes_main\">";
echo "<table id=\"mes_main-allView\" class=\"left\">";
echo "<td class=\"mes_tab-change\" >^</td>";
$from=array("","","", "", "", "", "", "");
for ($msgCount = 0; $msgCount < 8; $msgCount++){
$row = mysqli_fetch_array($messages);
$from[$msgCount] = $row['sender'];
for ($prev = 0; $prev < $msgCount; $prev++)
{
if ($from[$msgCount] == $from[$prev] )
{
$cont = true;
break;
}
}
if ($cont)
{
$cont = false;
continue;
}
if ($row['message'] == ""){
break;
}
echo "<tr><td class=\"mes_tab\" onclick=\"mes_main('" . $row['sender'] . "')\">";
echo "<h3 class=\"center\">" . $row['sender'] . "</h3>";
echo "<form id=\"" . $row['sender'] . "\" >";
echo "<input name=\"sender\" value=\"" . $row['sender'] . "\" hidden/>";
echo "<input name=\"id\" value=\"" . $row['id'] . "\" hidden/>";
echo "</form>";
echo "</td></tr>";
}
if ($msgCount == 8)
{
echo "<td id=\"mes_tab-change_bottom\" class=\"mes_tab-change\">V</td>";
}
echo "</table> <!-- end mes_main-allView -->";
echo "<div id=\"mes_main-mesView\" class=\"right\">";
echo "</div> <!-- end mes_main-mesView -->";
echo "</div> <!-- end mes_main -->";
mes_main() function from above. The two ajax functions inside are what I am referring to in the post above.
function mes_main(x)
{
var sender = x;
$( sender ).submit(function( event ) {
event.preventDefault();
});
ajax_req_mes("scripts/home/php/mes_load.php?" + sender , "mes_main-mesView");
ajax_req_mes("scripts/home/php/mes_content.php?" + sender ,"mes_content");
}
mes_load.php
the $sender var is created by passing the sender username through the URL. That is why I do php explode on the url.
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<div id=\"mes_content\"></div>";
echo "<div id=\"mes_field\" class=\"right\"></div>";
mes_content.php
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<table id=\"mesView-table\">";
$REC = array();
$SENT = array();
$ID = array();
for ($i = 0; $i < 25; $i++)
{
$rec = mysqli_fetch_array($recieved);
$sent = mysqli_fetch_array($sent);
if ($rec['id'] > 0)
{
$REC[$i] = $rec['id'];
}
if ($sent['id'] > 0)
{
$SENT[$i] = $sent['id'];
}
}
$ID = array_merge($SENT, $REC);
sort($ID);
for ($x = 0; $x < count($ID); $x++)
{
$key = $ID[$x];
$result = mysqli_query($con, "SELECT * FROM messages WHERE id = '$key'");
$res = mysqli_fetch_array($result);
if (in_array($key, $REC))
{
echo "<tr><td class='mes_recieved'>";
echo $res['message'];
echo "</tr></td>";
}
elseif (in_array($key, $SENT))
{
echo "<tr><td class='mes_sent'>";
echo $res['message'];
echo "</tr></td>";
}
}
echo "</table>";
Set async to false in your ajax requests!That's how the second one will wait for completing the first one and then start.
Also you can catch the on success and on error for the purposes you have.
Just use the "success" and "error" callbacks.
Also you could use the "done" callback
But, IMO, for that kind of problem I think a better alternative would be using Websockets
EDIT:
Here is some example of how you could do it:
jQuery.ajax({
type : "POST",
data : {msg:"your message"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
}).done(secondCall());
function secondCall(){
jQuery.ajax({
type : "POST",
data : {data:"data"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
});
}
EDIT2:
For visibility, here is a tutorial using websockets: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

Categories