Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
How can I upload data to database with AJAX, JSON and PHP?
Here is the code.
AJAX
function saveToTheDB(ratedIndex) {
$.ajax({
url: 'fetch.php',
method: 'POST',
cache: 'false',
dataType: 'json',
data: {
ratedIndex: ratedIndex
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
}
PHP
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
require_once 'includes\dbh.inc.php';
$rate = $_POST['ratedIndex'];
if(isset($_GET['userid'])){
if($db->query(" INSERT INTO `recipes_ratings` (`recipe_rating_id`, `recipe_id`, `user_id`, `rating`)
VALUES (null, 3 , 8, '".$rate."')
"))
}
echo json_encode($rate);
}
What have I done wrong?
Can some one help me to solve this problem? Thank you very much!
EDIT
ERROR
I get back a full object
As the response points you have syntax error, here I refactored your code in order to work.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once 'includes\dbh.inc.php';
$rate = $_POST['ratedIndex'];
if (isset($_GET['userid'])) {
if($db->query("INSERT INTO `recipes_ratings` (`recipe_rating_id`, `recipe_id`, `user_id`, `rating`) VALUES (null, 3 , 8, '".$rate."')")) {
// implementation if query is successful
}
}
echo json_encode($rate);
}
JFYI: Avoid directly placing the input variables into the query, you should use Prepared Statements.
Related
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 months ago.
The scenario is here I accept all button click that has ID starts with 'editbtn' like editbtn1/editbtn2 etc ; and get only the number to send via ajax to find data id based on the button id (number)
$(document).ready(function(){
$('[id^=editbtn]').click( function () {
noform=this.id.match(/\d+/);
event.preventDefault();
$.ajax({
'url': 'visitor_book_crud.php',
'data': {
'request': 'find_data',
'data_id': noform
},
'type': 'post',
'dataType': 'html',
'beforeSend': function () { }
})
.done( function (response) {
console.log(response);
})
.fail( function (code, status) { alert(code+' - '+status);
})
.always( function (xhr, status) { })
});
});
And In visitor_book_crud.php
if ($request=="find_data"){
$data_id = $_REQUEST['data_id'];
$mqdata = mysql_query("SELECT * FROM tb_visitorbook WHERE id_vb = '$data_id'") or die (mysql_error());
$mfadata = mysql_fetch_assoc($mqdata);
if($mfadata){
echo implode(",", $mfadata);
} else {
echo "failed";
}
}
I tried to directly send request to visitor_book.crud?request=find_data&data_id=1 and the output is like this, exactly same as what I want to be appeared in ajax response
1,2022-06-29,03:07:30,03:39:39,6,,A_NAME,3,,,SOME_NAME,,1,
But when I press edit button, it says
<br />
<b>Notice</b>: Array to string conversion in <b>C:\xampp\htdocs\security_editless\visitor_book_crud.php</b> on line <b>48</b><br /> //line 48 is in mysql_query("SELECT......
failed
I searched from many thread but still dont solve my problem, any help would be appreciated
First of all, you should do all the validation before sending the data from JS and also validate the data on the PHP side as well.
However noform = this.id.match(/\d+/); will give your an array. to get the number you'll have to use noform[0], also make sure you do the validation if any match found or not before using noform[0]
right now you're sending noform as data_id and your PHP is warning about it.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I've tried to look up different ways to get this json to output correctly but im not sure if im accessing the right variable in php/or the success function value.pTitle as well as how to I get the access to the other value out such as artTitle im failing somewhere not sure where or why.UPDATE fixed the php file added and an array $data[].
this is my php code.
$sqlPAQuery = "SELECT pTitle, GROUP_CONCAT(artTitle) AS
artTitle
FROM p
JOIN art ON art.pId = p.pId
GROUP BY pTitle";
if ($result=mysqli_query($conn,$sqlPAQuery))
{
$data = [];
while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
This is the outcome from the php encode of row:
[{"pTitle":"ent","artTitle":"11,12"},{"pTitle":"pro","artTitle":"10"},{"pTitle":"sports","artTitle":"1,13"}]
This is the html code:
<h3>Output: </h3>
<div id="output"></div>
<script id="source" language="javascript" type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: 'Data.php',
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function(index, value) {
var pageTitle = value.pTitle; //get name
$('#output').append("<b>pageTitle: </b>"+pageTitle+"<br/>");
}
});
});
Output should be:
pageTitle: ent
pageTitle: pro
pageTitle: sport
FIXED THE PHP FILE WORKS
If you want to proces the json like that this is what you need to do:
if ($result=mysqli_query($conn,$sqlPAQuery)) {
$data = [];
while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to access my data being sent through ajax and I am returning my echo statements, but not what I am passing, what am I doing wrong?
$.ajax({
url: 'http://www.example.php',
data : { 'foo' : 'bar', 'bar2' : 'foo2' },
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('success data '+data);
}
});
$data = $_POST['foo'];
$data2 = $_POST['bar2'];
echo('almost');
echo($data);
echo($data2);
echo('almost');
console reads success data almostalmost
Your ajax request is incorrect, you're telling jQuery.ajax not to process your data and send it as is, which wont work
$.ajax({
url: 'http://www.example.php',
data : { 'foo' : 'bar', 'bar2' : 'foo2' },
type: 'POST',
success: function(data){
console.log('success data '+data);
}
});
Your sever side script is expecting application/x-www-form-urlencoded content type this is what jQuery.ajax does by default, but not if you tell it not to process the data or set a content type.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've been stuck 2 days on the TutsPlus - jQuery in 30 Days exercises... lesson 26
Why does my ajax success function refuse to log the results to the console?
What happens instead is index.php simply echoes the text onto the webpage itself.
It's like some syntax problem is preventing the success callback from even running at all.
The rest of the code works (it does not rely on this particular callback), but I don't want to proceed until I find out what's wrong.
var Actors = {
init: function( config ) {
this.config = config;
this.bindEvents();
},
bindEvents: function() {
this.config.letterSelection.on('change', this.fetchActors);
},
fetchActors: function() {
var self = Actors;
$.ajax({
url: 'index.php',
type: 'POST',
data: self.config.form.serialize(),
dataType: 'json',
success: function(results) {
console.log(results);
}
});
}
};
Actors.init({
letterSelection: $('#q'),
form: $('#actor-selection')
})
and here's my index.php page...
<?php
require 'functions.php';
if ( isset($_POST['q']) ) {
connect();
$actors = get_actors_by_last_name( $_POST['q'] );
echo 'index returning your call with ' . $_POST['q'];
// echo json_encode($actors); return;
}
include 'views/index.tmpl.php';
?>
When specifying a dataType, such as 'json', the entire response needs to conform to that type.
By including additional output, such as:
echo 'index returning your call with ' . $_POST['q'];
The response won't be valid JSON and jQuery will error when attempting to parse it.
This question already has answers here:
Send values to $_GET using jQuery
(4 answers)
Closed 9 years ago.
HTML
Link1
Link1
Link1
jquery
function mainFunction() {
$(".leftPanel").click(function () {
$(".leftPanel").pageslide({
direction: "right",
modal: true
});
var linkId = $(this).attr('id');
var linkId2 = (linkId.substring(1, linkId.length));
console.log(linkId);
console.log(linkId2);
$.ajax({
type: 'GET',
url: 'my.php',
data: linkId2,
success: function (data) {
console.log(data);
}
});
return false;
});
}
And my PHP
<?php
$pageid = $_GET['linkId2'];
print_r($_GET);
?>
So this is my code but it seems not working..Had looked around dint found anything that can help.
Explain the script
I want to take ID of a link and assign it to $pageid
The console.log(data); Saying Access Denied
print_r($_GET); Saying array();
If any suggestion with code.
If need more details please ask I will explain everything that I can.
Will appreciate any help. Thank you a lot.
There is an error in your jquery.ajax function. You missed to pass an identifier for the data. Use this:
data: {"linkId2" : linkId2},