I am having an issue where i get a timeout if i run a certain php script with parameters sent from a Jquery Ajax reequest. However if i simply run this script with no parameters I.E just run it on its own its fine.
The php file the Ajax request is in is noteContent.php
noteContent.php:
<script type="text/javascript">
// Submit generalNote to the database
function submitNoteText()
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var notetext = $("#ta1").val();
var dataString = 'noteid1=' + noteid + '¬etext1=' + notetext;
if(noteid == ''||notetext == '')
{
alert("NoteID or Text is blank");
}
else
{
$.ajax({
type: "POST",
url: "submitNoteText.php",
dataType: 'json',
data: dataString,
cache: false,
success: function(result){
alert("Success");
}
});
}
return false;
};
</script>
The script its trying to run
submitNoteText.php:
<?php include 'connectionDetails.php'; ?>
<?php
if (isset($_POST['noteid1'], $_POST['notetext1']))
{
var_dump($_POST['notetext1']);
$noteid2 = $_POST['noteid1'];
$notetext2 = $_POST['notetext1'];
$stmt = "UPDATE Notes SET Note = '?' WHERE NoteID = ?";
$params = array($noteid2, $notetext2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
they are all connected with an include to
connectionDetails.php(which has never returned an error before):
<?php
$myServer = "Test";
$connectionInfo = array('Database' => 'Test', 'UID' => 'Test', 'PWD' => 'test');
//connection to the database
$conn = sqlsrv_connect($myServer, $connectionInfo)
or die("Couldn't connect to SQL Server on $myServer");
//Test connection to server
// if ($conn)
// {
// echo "connection successful"; # code...
// }
?>
<?php
//Defining my queries
$getNotes = "SELECT NoteID, NoteName, Note FROM Notes ORDER BY NoteName ASC";
$getTemplateNotes = "SELECT TemplateNoteID, TemplateNoteName, TemplateNote FROM TemplateNotes ORDER BY TemplateNoteName ASC";
$getReplaceVariables = "SELECT ReplaceVariableID, ReplaceVariableName, ReplaceVariableNote FROM ReplaceVariables ORDER BY ReplaceVariableName ASC";
$resultNotes = sqlsrv_query($conn, $getNotes);
$resultTemplate = sqlsrv_query($conn, $getTemplateNotes);
$resultVariables = sqlsrv_query($conn, $getReplaceVariables);
if( $resultNotes === false)
{
die( print_r( sqlsrv_errors(), true) );
}
if( $resultTemplate === false)
{
die( print_r( sqlsrv_errors(), true) );
}
if( $resultVariables === false)
{
die( print_r( sqlsrv_errors(), true) );
}
?>
When i click the button to run the request i get this:
All the text to be submitted is in the params:
Ajax data parameter should be an array :
$.ajax({
type: 'POST',
url: "your urls",
data: {
id: youridval,
anothervar: anothervalvalue
},
beforeSend: function() {
},
complete: function() {
},
success: function(_result) {
}
});
Related
I am passing the $place variable to a query in listplace.php using a ajax call. The ajax call works perfectly in php1.php code, but the $place value is not passed over the query. Please help!
listplace.php too works perfectly but when i try to pass $place in where condition it fails.
php1.php code
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<?php } ?>
listplace.php
<?php
//connect to the mysql
$db = #mysql_connect('localhost', 'root', 'password') or die("Could not connect database");
#mysql_select_db('test', $db) or die("Could not select database");
$place = $_POST['place'];
$sql = #mysql_query("select product_name from products_list where product_name = '$place'");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r['product_name'];
}
if (count($rows)) {
echo json_encode(['option'=> $rows]);
}else {
echo json_encode(['option'=> false]);
}
?>
An improvement will be to start using prepared statements. This is just an addition to Exprator's answer
This will prevent SQL injection attacks.
$sql_con = new mysqli('localhost', 'root', 'password', 'test');//get connection
$place = $_POST['place'];//posted variable
if($stmt = $sql_con->prepare("select product_name from products_list where product_name =?")) {//prepare returns true or false
$stmt->bind_param("s", $place); //bind the posted variable
$stmt->execute(); //execute query
$stmt->bind_result($product_name);//bind the result from query securely
$rows = array();//create result array
while ($stmt->fetch()) {//start loop
$rows[] = $product_name;//grab everything in array
}
if (count($rows)) {//check for number
echo json_encode(['option'=> $rows]);
} else {
echo json_encode(['option'=> false]);
}
change this line
data: {place: '<?= $_GET['place'] ?>'},
to
data: {place: '<?= $_GET["place"] ?>'},
I'm trying to convert a PHP variable to a JS variable so I can use it in a game I'm making. When I check the map code it is just undefined. Thanks in advance. FYI the PHP works.
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: $mapCode,
used: $used,
active: $active,
},
dataType: "text",
});
}
</script>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
?>
I understand that the PHP Code is hideous but it works and I'm going to 'pretty it up' later when the whole thing is working
If the file extension is .php and not .js then this should work
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: "<?php echo $mapCode; ?>",
used: "<?php echo $used; ?>",
active: "<?php echo $active; ?>",
},
dataType: "text",
});
}
</script>
If you have .js file then declare javascript variable before including your js in .php file
<script>
var mapCode = "<?php echo $mapCode; ?>";
var used = "<?php echo $used; ?>";
var active = "<?php echo $active; ?>";
</script>
then in .js file you will get easily
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: mapCode,
used: used,
active: active,
},
dataType: "text",
});
}
</script>
You only need to use <?php echo $mapCode;?> instead $mapCode. .... php variables can't be reed whithout open Php tag
My current project is actually dealing with lots of ajax calls,
here is the simplified version of what I use to communicate with server:
// php
// needed functions
function JSONE(array $array)
{
$json_str = json_encode( $array, JSON_NUMERIC_CHECK );
if (json_last_error() == JSON_ERROR_NONE)
{
return $json_str;
}
throw new Exception(__FUNCTION__.': bad $array.');
}
function output_array_as_json(array $array)
{
if (headers_sent()) throw new Exception(__FUNCTION__.': headers already sent.');
header('Content-Type: application/json');
print JSONE($array);
exit();
}
// pack all data
$json_output = array(
'mapCode' => $mapCode,
'used' => $used,
'active' => $active
);
// output/exit
output_array_as_json( $json_output );
// javascript
function _fetch()
{
return $.ajax({
url: 'getMapCode.php', // url copied from yours
type: 'POST',
dataType: 'json',
success: function(data, textStatus, req){
console.log('server respond:', data);
window.mydata = data;
},
error: function(req , textStatus, errorThrown){
console.log("jqXHR["+textStatus+"]: "+errorThrown);
console.log('jqXHR.data', req.responseText);
}
});
}
window.mydata = null;
_fetch();
I have not tested this, but let me know I'll fix it for you.
How did i get you, you need to get the result from ajax request, to do it, you should first setup your php outputs your results, so the ajax can get outputed results from php like this:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
// Outputing results:
echo json_encode(array('mapCode'=>$mapCode[0], 'used'=>$used[0], 'active'=>$active[0]));
?>
Then in ajax, use success for listening return message after ajax finished:
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
/** Your data to send to server **/
},
dataType: "text",
success: function(data) { /** Here is data returned by php echo **/
var temp = $.parseJSON(data);
mapCode = temp['mapCode'];
used = temp['used'];
active = temp['active'];
}
});
}
</script>
I want to POST data from form. It works fine.
In the other functionality i want to get data from database.
I don't know where is mistake. I suspect that AJAX call is fine.
My PHP code:
<?php
$uuid = $_POST['uuid'];
$minor = $_POST['minor'];
$mayor = $_POST['mayor'];
$lokalizacja = $_POST['lokalizacja'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO beacons (uuid, major, minor, lokalizacja)
VALUES ('$uuid', '$minor', '$mayor', '$lokalizacja')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlget = "SELECT uuid, major, minor, lokalizacja FROM beacons";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode(array("value" => "UUID: " . $row["uuid"]));
}
} else {
echo "Brak rekordów w bazie";
}
$conn->close();
?>
AJAX call:
$('#admin').submit(function(e){
e.preventDefault();
if( ($("input[name=uuid]").val().length) > 40 || ($("input[name=minor]").val().length) > 5 || ($("input[name=mayor]").val().length) > 5 || ($("input[name=lokalizacja]").val().length) > 20){
$(".error-pola").show();
} else{
$.post('administrator-connect.php', $(this).serialize() )
.done(function(){
$(".success-wyslanie").show();
})
.fail(function(){
$(".error-wyslanie").show();
});
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'administrator-connect.php',
dataType: 'json',
success: function(data)
{
alert("fsdfsd"+ data);
},
error: function(){
alert("not");
}
});
});
I am using:
echo json_encode(array("UUID" => $row["uuid"]));
and in ajax:
var jqxhr = $.get( "administrator-get.php", function(data) {
var jsonx = JSON.parse(JSON.stringify(data));
$( "#data-listing" ).html(jsonx);
});
But I get response:
{"UUID":"B9407F30-F5F8-466E-AFF9-25556B57FE6D"}
How to get only string ?
If you write this
dataType: 'json',
It expect for JSON value not string be sure to return only JSON.
You returns string value not JSON.
With like this code
echo "Polaczono";
Any echo would be the return value for ajax
At last you should return only one value like this.
echo json_encode($result);//an array result
You can check by string return. By removing dataType
How could I change the following php into ajax?
<?php
$selectMSGs = 'SELECT * FROM group_messages WHERE group_id="'.$_GET["id"].'" ORDER BY msg_id DESC';
$selectMSGs2 = $connect->query($selectMSGs);
while ($rowMSGs = $selectMSGs2->fetch_assoc()) {
echo "<div class='lead MessageOfPerson'>";
echo "<div class='NameOfPerson'>";
echo "<p>";
echo $rowMSGs['msg_sender'];
echo "</div>";
echo "<div class='MessageText'>";
echo nl2br($rowMSGs['group_msg']);
echo "</p>";
echo "</div>";
echo "</div>";
echo "<hr>";
}
?>
I already have some other ajax course (not my own) that is already being run on this page, could it be possible to combine this php together with my current ajax and php file? The files look like this:
ajax
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function updateChat(){
$.ajax({
//TODO set localhost to the strato livechat file
url: "http://localhost:8080/LiveChat/LiveChat/code/php/groups/liveChat.php",
type: "get",
data: "msg_id="+$('#msg_id').val(),
dataType: "json",
success: function(response, status, http){
$.each(response, function(index, item){
$('#msg_id').val(item.msg_id);
//TODO update messages
});
},
error: function(http, status, error){
alert( 'Error updating chat, ' + error);
}
});
}
//auto update chat
setInterval( updateChat, 2000 );
</script>
php
<?php
// Lets fetch the value of msg_id
$data = $_REQUEST;
$msg_id = $data['msg_id'];
// Connect to MySQL Server TODO change to strato
$con = mysqli_connect( "localhost" , "root" , "" , "db2723249" );
// If msg_sender and group_msg is available then
// add it in table chats
if(
isset( $data['msg_sender'] ) &&
isset( $data['group_msg'] )
) {
$insert = "
INSERT INTO group_messages (group_id, group_msg, msg_sender)
VALUES( '".$data['msg_sender']."' , '".$data['group_msg']."' )
";
$insert_result = mysqli_query( $con , $insert );
}
$select = "SELECT *
FROM group_messages
WHERE msg_id > '".$msg_id."'
";
$result = mysqli_query( $con , $select );
$arr = array();
$row_count = mysqli_num_rows( $result );
if( $row_count > 0 ) {
while( $row = mysqli_fetch_array( $result ) ) {
array_push( $arr , $row );
}
}
// Close the MySQL Connection
mysqli_close( $con );
// Return the response as JSON
echo json_encode( $arr );
?>
Okay, after working on this for about 20 hours, I finally found out how to do it (without help:)! I was able to merge the old and new ajax and php.
The new ajax became
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function updateChat(){
$.ajax({
//TODO set localhost to the strato livechat file
url: "http://localhost:8080/LiveChat/USB/code/php/groups/liveChat.php",
type: "get",
data: "msg_id="+$('#msg_id').val(),
dataType: "json",
success: function(response, status, http){
$.each(response, function(index, item){
$("#ChatBox").html("<div class='lead MessageOfPerson'> <div class='NameOfPerson'> <p>" + item.msg_sender + "</p> </div> </div> <div class='MessageText'> <p>" + item.group_msg + "</p> </div> <hr/>" + $('#ChatBox').html());
$('#msg_id').val(item.msg_id);
});
},
error: function(http, status, error){
alert( 'Error updating chat, ' + error);
}
});
}
//auto update chat
setInterval( updateChat, 2000 );
</script>
The php became:
<?php
// Lets fetch the value of msg_id
$data = $_REQUEST;
$msg_id = $data['msg_id'];
// Connect to MySQL Server TODO change to strato
$con = mysqli_connect( "localhost" , "root" , "" , "db2723249" );
// If msg_sender and group_msg is available then
// add it in table chats
if(
isset( $data['msg_sender'] ) &&
isset( $data['group_msg'] )
) {
$insert = "
INSERT INTO group_messages (group_id, group_msg, msg_sender)
VALUES( '".$data['msg_sender']."' , '".$data['group_msg']."' )
";
$insert_result = mysqli_query( $con , $insert );
}
$select = "SELECT * FROM group_messages WHERE msg_id > '".$msg_id."' ";
$result = mysqli_query( $con , $select );
$arr = array();
$row_count = mysqli_num_rows( $result );
if( $row_count > 0 ) {
while( $row = mysqli_fetch_array( $result ) ) {
array_push( $arr , $row );
}
}
// Close the MySQL Connection
mysqli_close( $con );
// Return the response as JSON
echo json_encode( $arr );
?>
I'm new using ajax and I have a code to display from wordpress some information from database columns.
I have this PHP code to connect with the database and create the JSON file:
<?php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
?>
In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()
<script type="text/javascript"> function doLogin(){
data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: "Mywebsiteurl.php",
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
} </script>
I need to show in <div id="forma"> a kind of list usign html, for example:
Id: VALUE ID
Name: VALUE NAME
and more information...
When i try to print in my website the required information using $('#forma').html(data); I obtain error or just an empty space.
How can I fix it? thanks.
In WordPress we need to hook the ajax hook to your check_user function here.
add_action('wp_ajax_your_action_from_js', 'your_function');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');
Check below code for how it is done regarding your context.
In functions.php
function check_user() {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
}
add_action('wp_ajax_check_user', 'check_user');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_check_user', 'check_user');
In your JS called file.
In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.
<script type="text/javascript">
function doLogin(){
data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: ajax_url,
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/
CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins
WordPress has specific methods to enable ajax requests.
// registering ajax request for Logged users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// registering ajax request also for public area
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback()
{
// Your code here
wp_die(); // this is required to terminate immediately and return a proper response
}
To call it:
jQuery(document).ready(function($) {
var data = {action: "my_action", username: jQuery("#user").val(), password: jQuery("#pass").val()}
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: data,
method: 'POST',
success: function(response) {
console.log(response);
},
error: function(a,b,c) {
}
});
});
Source: https://codex.wordpress.org/AJAX_in_Plugins