Hello I´m very frustated because I can´t connect to my database to retrieve some files.
I have my normal html code (index.html) which adds a javascript:
<script src="js/connection.js"></script>
The javascript (connection.js) looks something like this, which detects from a grid of elements the selected element and gets it´s text:
var texto="";
function getData($dia){
//Variable $dia is set up correctly, no problem
var dia=$dia;
/* Send the data using post*/
$.ajax({
url: "php/setup.php",
type: "post",
data: {'fecha':dia},
contentType: "application/json",
datatype: "json",
success: function(){
alert("Exito");
},
error:function(){
alert("failure");
}
});
}
//Get the desired text upon click on the grid item
$(document).ready(function(){
$(".grid__item").click(function(){
$texto=$(this).html().substring(($(this).html().indexOf(">"),($(this).html().indexOf(">")+1)),$(this).html().indexOf("</h2>"));
getData($texto);
});
});
Finally using Ajax I pass the variable 'fecha', the problem is that I think it´s not making a proper connection with my php file since nothing is printing (I have a method which prints to console)
I set the post method like this (PHP file starts here):
debug_to_console("Print Something");
$fecha = mysql_real_escape_string($_POST['fecha']);
getPageData($fecha);
Which calls this method:
function getPageData($dia){
$sql = ("SELECT * FROM Comentarios WHERE dia='$dia'");
$result = mysqli_query(connectToDb(),$sql);
$num_rows = mysqli_num_rows($result);
$html="";
$boolean=true;
if($num_rows>0) {
while($row = $result->fetch_assoc()) {
if($boolean==true){
$html.='<div class="gray"><div class="comentario">'.$row["comment"].'</div><div class="timestamp">'.$row["dia"].'</div></div>';
$boolean=false;
}else{
$html.='<div class="white"><div class="comentario">'.$row["comment"].'</div><div class="timestamp">'.$row["dia"].'</div></div>';
$boolean=true;
}
}
echo json_encode(array('html'=>($html.'<br>'.'<div class="fondo_gen"> div></div></div>'),'texto'=>$dia));
} else {
echo json_encode(array('html'=>'<div class="transparent"><div class="nada">No hay comentarios aun :(</div></div>','texto'=>$dia));
}
}
PHP file ends here
I know that it's connecting to the database since a made a "dummy.php" file which connects to the same database and table and adds a record, without problem. I´m not really sure which is the problem, I could really appreciate it if you could help me.
PS:
My folders are setup like this:
index.html
js (folder)
a. connection.js
php (folder)
a. setup.php
.
Thanks and sorry for my crappy english
Never mind, I got it fixed, I replaced the Ajax part with:
$.post("php/setup.php",
{
fecha: dia
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
and received the variable using
if (isset($_POST["fecha"])){
$fecha = $_POST["fecha"];
getPageData($fecha);
}else{
echo "Got nothing";
}
Thanks anyway, I appreciate the help
Related
JAVASCRIPT
$(document).ready(function() {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id);
$.ajax({
url: "m/a/a.class.php",
method: "POST",
data: {pId: p_id},
success: function (data)
{
console.log(data); //<------ this gives me an empty output
alert("success!");
}
});
});
});
I am trying to get a the id of a selected value out of the selectpicker, when i change the selectpicker, i get the alert "success!" and in the console it shows the result, which is correct. When i want to use this result in PHP, which i am using ajax for, it gives me an odd output so i can't use the variable for the following sql statement.
What am i doing wrong? For you to understand i want to get the post input for product, so i can filter the next selectpicker by the id of "product", so i want to get dependant selectpicker "onchange". I already read many other questions, and it works in other examples when i use something like this in the success function:
success: function (data)
{
$('#state').html(data);
}
But this isn't working for my example here, because when i use the "$_POST['produkt_id']" it either gives me an empty query or it has a mistake in it, since it passes the data from my screenshot. Thanks in advance and feel free to ask questions.
UPDATE:
This is where I am trying to get the previous input.
case 'linie':
if(isset($_POST['pId'])) {
$t = $_POST['pId'];
$sql = 'SELECT id, bezeichnung '
. 'FROM l "
. 'LEFT JOIN ' .produkte p ON p.id=l.p_id '
. 'WHERE l.p_id =' . "$t" . 'AND l.deleted=0 AND p.deleted=0 '
. 'ORDER BY l.bezeichnung ';
break;
}
the error says it. PHP you're using is calling "include_once" and the file which you're trying to include, doesn't exist.
that makes the PHP to return a response with error in it, and the response - because of that error text - is not a valid JSON anymore.
In your ajax code you should put your url route path for file request it hink you put the file path of your project system that's why your ajax file could not find and include your file for ajax request execution
$.ajax({
url: "modules/ausschuss/ausschuss.class.php", //remove this
url: "full url for your file execution"
method: "POST",
data: {produkt_id: produkt_id},
success: function (data)
{
alert("success!");
}
});
I have a very simple jquery function that sends an Ajax call to a php file that should echo out an alert, but for the life of me, cannot get it to run. For now, I'm just trying to trigger the php to run. Here is the javascript:
function getObdDescription(){
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if($length == 5){
window.confirm($length);
$.ajax({ url: '/new.php',
data: {action: 'test'},
type: 'post',
success:function(result)//we got the response
{
alert('Successfully called');
},
error:function(exception){alert('Exception:'+exception);}
});
}
return false;
}
Here is new.php
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
?>
I'm testing in Chrome, and have the network tab up, and can see that the call is successful, as well, I get the 'Successfully called' message that pops up, so the jquery is running, and the Ajax call is successful. I also know that the url: '/new.php is correct, because when I delete new.php from my server, I get a status "404 (Not Found)" from the console and network tab. I've even test without the conditional if($length ==... and still no luck. Of course, I know that's not the problem though, because I get the 'Successfully called' response. Any ideas?
This isnt the way it works if you need to alert the text, you should do it at the front-end in your ajax success function, follow KISS (Keep It Simple Stupid) and in the php just echo the text . that is the right way to do it.
You should do this:
function getObdDescription() {
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if ($length == 5) {
window.confirm($length);
$.ajax({
url: '/new.php',
data: {
action: 'test'
},
type: 'post',
success: function (result) //we got the response
{
alert(result);
},
error: function (exception) {
alert('Exception:' + exception);
}
});
}
return false;
}
In your php
<?php
echo 'message successfully sent';
?>
You are exactly right Muhammad. It was not going to work the way I was expecting it. I wasn't really trying to do an Ajax call, but just to get an alert box to pop up; I just wanted confirmation that the call was working, and the PHP was running. Changing the alert('Successfully called'); to alert(result); and reading the text from the php definitely confirmed that the php was running all along.
I want to stay on topic, so will post another topic if that's what's needed, but have a follow-up question. To elaborate a bit more on what I'm trying to do, I am trying to run a function in my php file, that will in turn, update a template variable. As an example, here is one such function:
function get_vehicle_makes()
{
$sql = 'SELECT DISTINCT make FROM phpbb_vehicles
WHERE year = ' . $select_vehicle_year;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
$template->assign_block_vars('vehicle_makes', array(
'MAKE' => $row['make'],
));
}
$db->sql_freeresult($result);
}
Now, I know that this function works. I can then access this function in my Javascript with:
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
This is a block loop, and will loop through the block variable set in the php function. This work upon loading the page because the page that loads, is the new.php that I'm trying to do an Ajax call to, and all of the php runs in that file upon loading. However, I need the function to run again, to update that block variable, since it will change based on a selection change in the html. I don't know if this type of block loop is common. I'm learning about them since they are used with a forum I've installed on my site, phpBB. (I've looked in their support forums for help on this.). I think another possible solution would be to return an array, but I would like to stick to the block variable if possible for the sake of consistency.
I'm using this conditional and switch to call the function:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
//Get vehicle vars - $select_vehicle_model is used right now, but what the heck.
$select_vehicle_year = utf8_normalize_nfc(request_var('vehicle_year', '', true));
$select_vehicle_make = utf8_normalize_nfc(request_var('vehicle_make', '', true));
$select_vehicle_model = utf8_normalize_nfc(request_var('vehicle_model', '', true));
switch($action) {
case 'get_vehicle_makes' :
get_vehicle_makes();
break;
case 'get_vehicle_models' :
get_vehicle_models();
break;
// ...etc...
}
}
And this is the javascript to run the Ajax:
function updateMakes(pageLoaded) {
var yearSelect = document.getElementById("vehicle_year");
var makeSelect = document.getElementById("vehicle_make");
var modelSelect = document.getElementById("vehicle_model");
$('#vehicle_make').html('');
$.ajax({ url: '/posting.php',
data: {action: 'get_vehicle_makes'},
type: 'post',
success:function(result)//we got the response
{
alert(result);
},
error:function(exception){alert('Exception:'+exception);}
});
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
if(pageLoaded){
makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
updateModels(true);
}else{
makeSelect.selectedIndex = -1;
updateModels(false);
}
}
The javascript will run, and the ajax will be successful. It appears that the block variable is not being set.
I would like to use the 'sID' in the first HTML form to retrieve data from the database and then use the data retrieved from the database on the second HTML page. I can do this with just php, but I just can't figure out how to do it using ajax.
I'm really new to javascript/ajax so please be gentle with your answers :)
HTML 1
<div class="moreR">
<form action="moreR_2.0.php" method="GET">
<input type="hidden" name="sID[]" value="a_certain_ID"/>
<input type="image" src="Icons/PNG/greater_than.png" alt="submit"/>
</form>
</div>
PHP (moreR_2.0.php)
<?php
include ('session_start.php');
include ('db_connect_mO.php');
if (isset($_GET['sID'])) {
foreach($_GET['sID'] as $sID) {
}
}
$sql = mysqli_query($con, "SELECT * FROM mo WHERE sID=$sID");
$row = mysqli_fetch_array($sql);
while ($row = mysqli_fetch_assoc($sql))
{
$test[]= array(
'pZero'=> $row['pZero'],
'pZero_Gname'=> $row['gZero_key'],
);
}
header('Content-Type: application/json');
echo json_encode ($test);
//detailed error reporting
if (!$sql)
{
echo 'MySQL Error: ' . mysqli_error($db);
exit;
}
?>
JavaScript
$(document).ready(function() {
"use strict";
function connect2mR() {
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:'sID',
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
} //end of function
if (window.attachEvent) {window.attachEvent('onload', connect2mR);}
else if (window.addEventListener) {window.addEventListener('load', connect2mR, false);}
else {document.addEventListener('load', connect2mR, false);}
});
HTML 2
<section class="moreR_section">
<div style="width:20%;"><div id="pZero"></div></div>
<div class="moreR_g" style="margin-left:26%" id="pZero_keys"></div>
</section>
What i'm trying to do is; start from HTML 1, collect sID -> then PHP/JS use sID from HTML 1 to get data from database -> then use the result from database on HTML 2. At the moment i'm struggling on how to make this process work. Can't figure out how to start from HTML 1 and end up in HTML 2.
You are not fetching the data from the input element at all.. change your ajax code to below.
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:{sID: $('input[name="sID[]"]').val()}, // this is the change
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
Edit 1: you can use localstorage to save data and retrieve from there when ever required. So you can do as below
In your HTML 1 write this.
localStorage.setItem('sID', JSON.stringify( $('input[name="sID[]"]').val()));
And in HTML 2 you can access the value by reading it from the local storage like below,
var sIDofHTML1 = JSON.parse(localStorage.getItem('sID'));
You will have to update the ajax as below.
data:'sID', // this has to change to data:'sID='+sID,
$.ajax({
url:"moreR_2.0.php",
type: "GET",
data:'sID', // this has to change to data:'sID='+sID,
dataType:"json",
//async:false,
success:function(data)
{
$('#pZero').html('<img src="rPlanets/' + this.gZero + '.png" alt=""/>');
$('#pZero_keys').html(this.gZero_key);
}, //success
}); //end of ajax
i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).
I have a script which grabs another JavaScript which is made using PHP, it all works fine, but im trying to build in some error handling incase there is an issue. At the moment the error works if it cannot find the file, but I would like it to display a message from the PHP code if there is an error. I thought using JSON would work, but im very new to it, and admit to not knowing what im doing.
If someone could help me get this working, as at the moment I am not getting the message response message appear in the alert.
I have the following JQuery code:
graphURL = 'functions/ICP_summary_graph.php';
graphData = '?ICP=' + ICPSet;
$.ajaxSetup({
type: 'get',
URL: graphURL,
data: graphData,
success: function (data) {
var reponse = jQuery.parseJSON(data.response);
alert("response : "+reponse);
//$('#expconchart').html(data.response);
},
error: function(data) {
$('#meterloader').hide();
$('#meterbox').html("<div><p class='textcentre bold red'>There was an error loading the chart.</p>");
}
});
$.getScript(graphURL + graphData);
and this PHP:
//GENERATE GRAPH
//SET RESULT ARRAY
$result = array();
//CONNECT TO DATABASE
if(!require('../../connect.php')){
$result['response'] = "Unable to aquire connection";
header("content-type: application/json");
exit(json_encode($result));
} else {
...
Any help greatly appreciated. :)