if (isset($_POST["getCanvas"]) ) {
$projectName= mysqli_real_escape_string($db2, $_POST['whichProject']);
$query = "SELECT objectsList FROM projectObjectstable WHERE projectName='$projectName'";
// $query = "SELECT objectsList,backgroundImage FROM projectObjectstable WHERE projectName='$projectName'";
$jsonCanvas= mysqli_query($db2,$query);
$row = mysqli_fetch_row($jsonCanvas);
$myLine=$row['0'];
echo $myLine;
}
With code above i get one column from table. I need two columns. I woud like to try next:
$query = "SELECT objectsList FROM projectObjectstable WHERE projectName='$projectName'";
$jsonCanvas= mysqli_query($db2,$query);
$row = mysqli_fetch_row($jsonCanvas);
$myLine=$row['0'];
echo $myLine;
$query2 = "SELECT backgroundImage FROM projectObjectstable WHERE projectName='$projectName'";
$jsonBackground= mysqli_query($db2,$query2);
$row2 = mysqli_fetch_row($jsonBackground);
$myLine2=$row['0'];
echo $myLine2;
}
For it I need next solution here. How to modificate ajax success function to get two variables (projectList and backgroundImage) on canvas?
$.ajax({
method:"POST",
url: '/wp-content/themes/mypage3/PgetJson.php',
data: {
"getCanvas":1,
"whichProject":whichProjectToSave
},
datatype: "text",
success: function(strdate){
canvas.loadFromJSON(strdate, function() {
canvas.renderAll();
});
}
});
An extra information would e appreciated. What options exists to debug php code in browser, as it is possible to do with js ?
Thank you
As it was said before, you need to use json_encode function to send parameters in JSON format to your JS. You have to put your variables inside an array before calling to echo. As it's used below.
$query = "SELECT objectsList FROM projectObjectstable
WHERE projectName='$projectName'";
$_row= mysqli_query($db2,$query);
$row = mysqli_fetch_row($_row);
$jsonCanvas=$row['0'];
$query2 = "SELECT backgroundImage FROM projectObjectstable
WHERE projectName='.$projectName.'";
$_row2= mysqli_query($db2,$query2);
$row2 = mysqli_fetch_row($_row2);
$jsonBackground=$row['0'];
$to_json['jsonCanvas'] = $jsonCanvas;
$to_json['jsonBackground'] = $jsonBackground;
echo json_encode($to_json);
exit();
And in your JS, you collect your information in the success function:
$.ajax({
method:"POST",
url: '/wp-content/themes/mypage3/PgetJson.php',
data: {
"getCanvas":1,
"whichProject":whichProjectToSave
},
datatype: "json",
success: function(strdate){
/*Here on data you will receive
strdate['jsonCanvas'] & strdate['jsonBackground']
*/
});
}
});
I would also recommend making your sql calls in one query if your calling to the same table and passing the same variable as an argument.
Related
So here I want to get an ID for the specific user, using a php page, and then perform database insert using a function defined in a file named 'functions.php'. So basically, I am capturing values from a page using jQuery ajax() method and sending the data to a php page named 'follow_school.php'. The rest of what's happening would be clear from the code, I provide below:
jQuery code:
jQuery(document).ready(function() {
var school_name = jQuery('#school-name').text();
var session_var = jQuery('#session').text();
// console.log(session_var);
var button_text_onload =
localStorage.getItem("btnText_"+school_name+"_for_"+session_var);
console.log(button_text_onload);
if (button_text_onload !== null) {
jQuery('#follow-button').html(button_text_onload);
} else {
jQuery('#follow-button').html('Follow');
}
jQuery('#follow-button').click(function() {
// alert (session_var);
// console.log(session_var);
var button_text = jQuery('#follow-button').text();
// alert(button_text);
if (button_text === 'Follow') {
jQuery.ajax({
type: 'POST',
url:
'https://mim-insider.com/wp-content/themes/Divi/follow_school.php',
data: {name : school_name,
email : session_var
},
success: function(result) {
console.log(result);
var key = "btnText_" + school_name +"_for_" +
session_var;
console.log(key);
localStorage.setItem(key, "Unfollow");
jQuery('#follow-button').html('Unfollow');
}});
} else {
jQuery.ajax({
type: 'POST',
url:
'https://mim-insider.com/wp-content/themes/Divi/unfollow_school.php',
data: {name : school_name,
email : session_var,
},
success: function(result) {
console.log(result);
var key = "btnText_" + school_name +"_for_" +
session_var;
console.log(key);
localStorage.setItem(key, "Follow");
jQuery('#follow-button').html("Follow");
}});
}
});
});
follow_school.php
<?php
include_once "includes/db.php";
include_once "includes/functions.php";
$name = $_POST['name'];
$email = $_POST['email'];
$id = get_id($email);
/* for debugging purpose */
if ($id == null) {
var_dump($id);
} else {
echo $id;
}
echo $email;
/* insert operation */
insert_school($id, $name);
?>
functions.php
function get_id($email) {
global $conn;
$sql = "SELECT id FROM member WHERE email = '$email'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
return $row["id"];
}
function insert_school($id, $name) {
global $conn;
$sql = "INSERT INTO user_schools (user_id, school_name)
VALUES ('$id', '$name')";
$conn->query($sql);
}
NOTE: Here the database connection is perfectly fine, and these codes worked for some pages earlier. But apparently, other pages don't seem to run the code, or to be precise, returns "null" as id. Also, I would like to mention that, the table entries and fields are not null, or unspecified. They are perfectly fine, as I said, it worked for some pages.
Please can anyone guide me, as to what's going wrong here, because after dedicating so much of my time on this, i still am not able to understand the issue.
Thank you.
By defaut, when my system loads some data is filtered in my db and shown to the user. But my doubt is how can I call AJAX to filter some new data, and return it, changing the default values that are already set on my variables.
This is my AJAX call:
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
data: {rede: $("#dropdown-parceria").val()},
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And this is what I got from trying to filter some data to return it,
but nothing worked:
<?php
require_once('../../includes/conecta.php');
$rede = $_POST['rede'];
function buscaDados($conexao){
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
}
Any idea?
Thanks!
You should add echo at the end :
echo json_encode($dados);
So the $dados array will be sent back to the ajax request as JSON response.
Parse the response to json uisng $.parseJSON() :
.done(function(resposta){
resposta = $.parseJSON(resposta);
console.log(resposta);
})
Hope this helps.
in your ajax code u add a success.
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
dataType: 'json',
data: {rede: $("#dropdown-parceria").val()},
success: function (data) {
//You do not need to use $.parseJSON(data). You can immediately process data as array.
console.log(data)
//if you have a array you use the following loop
for (var j =0;j < data.length;j++) {
console.log(data[j]);
// u can use data[j] and write to any fields u want.
// e.g.
$('.somediv').html(data[j].myarraykey);
}
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And for the php codes (i did not check whether your code is valid or not), you need to add the echo and a die to end the call.
$rede = $_POST['rede'];
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
echo json_encode($dados);
die();
When call php from jquery via ajax ,have any response .I changed the dataTypeand put jsoninstead html.I´m thinking the issue is that,for the ajax call never trigger the php code,it seems $_POST['retriveForm'] never carries a value.
PHP:
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
and jQuery :
$(document.body).on('click', '.edit', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {
retriveForm: id
},
dataType: "json",
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
Code is all in the same page if that may be important.
Since the AJAX code is in the same script, make sure you don't output any of the normal HTML in this case. Your PHP code should be at the very beginning of the script, before any HTML is output. And you should exit the script after echoing the JSON. Otherwise your JSON will be mixed together with HTML, and jQuery won't be able to parse the response.
Also, you're not correctly adding to $data_json in your loop. You're overwriting the variable each time instead of pushing onto it.
<?php
// code here to set up database connection
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json[] = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
exit();
}
?>
<html>
<head>
...
Then in the success function, you'll need to index the elements of response, since it's an array, not a single object.
In my index.php file, I have the following code snippets. Can someone provide an explanation how this process occur ? I found this somewhere and it somehow matches what I intend to do on a work.
case 'option1':
$final['a']['b'] = queryDatabase($conn, $id, 'customer');
echo json_encode($final);
I have a function queryDatabase that contains an SQL query.
function queryDatabase($conn, $id, $searchType) {
$query = "SELECT .....
Then it sets the variable $rows as follows:
$rows = query($conn, $query);
The variable $query contains the SQL query.
Then I have another function as follows:
function query($conn, $query) {
$rows = [];
$result = mysqli_query($conn, $query);
if($result) {
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$rows[] = $row;
}
}
return $rows;
}
Now in my global.js file, I have created and ajax request as follows:
$.ajax({
type: "POST",
url: "index.php",
dataType: "json",
data: {
action: 'option1',
id: id,
},
success:
function(data) {
Also, in the function(data), does the data contains all the result retrieved from the database? How can I access individual data from the database here?
Please help. Thanks.
First, the data should include the result, however, you need to echo back the data to be accessible,
Moreover, you need to encode the result in json, so your last line of code should be something like
echo json_encode($rows);
After that you can edit your javascript in the success part to log the returned result, something like:
console.log(data);
This will show you exactly how to access your data.
I'm trying to do a Jquery Ajax search with multiple conditions, and this is my first time. I did some research and found ways to send data to a php file, however it's only with one variable. I'm not sure how to implement all of my 6 variables into data: data.
here they are:
var FromDate
var ToDate
var MusicStyles
var Locations
var FromPrice
var ToPrice
Now here is where I got stuck, I should do a post with some data. When I have multiple variavbles, can I do data: dataFromDate, dataToDate, dataMusicStyles,?
$("#SearchButton").click(function() {
var dataFromDate = 'dataFromDate='+ FromDate;
var dataToDate = 'dataToDate='+ ToDate;
var dataMusicStyles = 'dataMusicStyles='+ MusicStyles;
var dataLocations = 'dataLocations='+ Locations;
var dataFromPrice = 'dataFromPrice='+ FromPrice;
var dataToPrice = 'dataToPrice='+ ToPrice;
$.ajax({
type: "POST",
url: "do_search.php",
data: dataFromDate, dataToDate, dataMusicStyles, dataLocations, dataFromPrice, dataToPrice,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
});
Where the MySQL would look like this:
<?php
//if we got something through $_POST
if (isset($_POST['dataFromDate'])) {
include('db.php');
$db = new db();
// never trust what user wrote! We must ALWAYS sanitize user input
$word = mysql_real_escape_string($_POST['search']);
$word = htmlentities($word);
// build your search query to the database
$sql = "SELECT
events.ID,
events.EVENT_NAME,
events.start_datetime,
events.end_datetime,
events.VENUE_LOCATION,
events.ENTRANCE_PRICE,
venues.VENUE_NAME,
GROUP_CONCAT(music_styles.MUSIC_STYLE_NAME) AS MUSIC_STYLE_NAME
FROM events
INNER JOIN venues
ON events.VENUE_LOCATION = venues.ID
INNER JOIN events_music_styles
ON events.ID = events_music_styles.event_id
INNER JOIN music_styles
ON events_music_styles.music_style_id = music_styles.id
WHERE start_datetime >= '$phpFromDate'
AND end_datetime <= '$phpToDate'
AND ENTRANCE_PRICE >= '$phpFromPrice'
AND ENTRANCE_PRICE <= '$phpToPrice'
GROUP BY events.ID";
// get results
$row = $db->select_list($sql);
if(count($row)) {
$end_result = '';
foreach($row as $r) {
$result = $r['title'];
// we will use this to bold the search word in result
$bold = '<span class="found">' . $word . '</span>';
$end_result .= '<li>' . str_ireplace($word, $bold, $result) . '</li>';
}
echo $end_result;
} else {
echo '<li>No results found</li>';
}
}
?>
I am 100% certain that it doesn't work like this, but I think I got it almost right. I would love it if someone could at least please let me know what I could do to fix the code.
Thanks!
You send it as an object, like so:
$.ajax({
type: "POST",
url: "do_search.php",
data: {dataFromDate : FromDate,
dataToDate : ToDate,
dataMusicStyles : MusicStyles,
dataLocations : Locations,
dataFromPrice : FromPrice,
dataToPrice : ToPrice
},
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html) { // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
Where the firs value is the key, and the second is the value, so {key: value} would be accessed on the server as $_POST['key'], which your values would be accessed the way you seem to want :
$_POST['dataFromDate']
Also, you don't need all those variables at the start, just use them directly in the object.
Try to concatenate your strings with a "," and explode them on the server.