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.
Related
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.
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.
I want to know when will it be reasonable to pull data from a php page via ajax in form of json array.. Suppose I have this code :
$.ajax({
type: "get",
url: "assets/update_cart_user_fstore.php",
data: up,
cache: false,
success: function(r){
$(#item).html(r);
},
});
and in PHP page I am echoing a variable
$hello = "I am code!";
echo $hello;
And with JSON
$.ajax({
type: "get",
url: "assets/update_cart_user_fstore.php",
data: up,
cache: false,
success: function(r){
var obj = jQuery.parseJSON(r);
$('#item').html(obj.code);
},
});
and in PHP I'm echoing the JSON array
$hello = "I am code!";
$response = array();
$response['code'] = $hello;
echo json_encode($response);
Now I know that in case of echoing more than 1 variable JSON is appropriate...But is it necessary here? And am I using JSON properly..?
Please explain..
Is it necessary in this case? No, it isn't.
But using JSON has some advantages, for example
Your data has a strict, standardized structure. This means, less chance for errors.
You can scale it better.
You can debug it easier. For example, Tools like Firebug support JSON
Two good articles, which will go into more detail:
http://www.revillweb.com/articles/why-use-json/
http://blog.programmableweb.com/2013/11/07/xml-vs-json-a-primer/
I've rarely found a use case where I wouldn't prefer JSON.
I had a question before about implementing datepicker with jqgrid. I think that question was too specific. I would like to know, has anyone been able to implement a datepicker with a dynamic jqGrid? The colModel, colNames, and in my case, data are generated server-side via an ajax request, then displayed locally. On the server, in PHP, I create an array with the colModel structure, then JSON encode it before sending it back to client. Valid JSON puts quotes around the keys, but according to examples here, here, and (importantly) here, I'm not supposed to do that.
I tried to use regex to remove the quotes, but that just results in a javascript error because it can no longer parse the now-invalid JSON.
Is datepicker with dynamic colModel possible?
Here is the AJAX request:
$(document).ready(function(){
$.ajax({
type: "GET",
datatype: "json",
success: function(result){
try{
//alert(result);
result = jQuery.parseJSON(result);
}catch(err){
alert("error in success json " + err);
return;
}
var colN = result.colNames;
var colM = result.colModelList;
var colD = result.colDataList;
grid.jqGrid({
datatype: 'local',
colNames:colN, //column names
colModel:colM, //column options
data:colD, //table data
editurl: 'clientArray',//changes are not sent to server
cellEdit: true,
cellsubmit: 'clientArray',
});
}
});
});
and an example colModel:
{
"editable":true,
"name":"date",
"index":"date",
"sorttype":"date",
"editrules":{"date":true},
"editoptions":{"dataInit":"initDateEdit"}
}
Look at this answers. It should solve your problem.
I have the following object that gets created in my javascript application.
poll_data[active_question] = {
'question': $('div.question_wrap textarea').attr('value'),
'answers': [
$('div.answer_wrap input#0').attr('value'),
$('div.answer_wrap input#1').attr('value'),
$('div.answer_wrap input#2').attr('value'),
$('div.answer_wrap input#3').attr('value'),
$('div.answer_wrap input#4').attr('value'),
$('div.answer_wrap input#5').attr('value')
]
};
active_question is set to 'poll', 0, 1, 2, 3, 4, or 5 depending on the question being worked on at the moment. I am trying to post this object to a php script using the following JS code.
$.ajax({
url: '/somewebsite/poll/create?json=show',
type: 'POST',
// dataType: 'json',
data: poll_data,
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data);
}
});
My PHP code is very simple.
echo json_encode($_POST); exit;
When I run the script and click the button that triggers the submission of the data, I receive the alert (so the actual ajax code works), but the result from my PHP script is just an empty array. I think that this is an issue with the way the object is constructed, but I am not sure, and have not been able to find a work around.
Thanks in advance.
Okay, a few things:
poll_data is not a valid JSON object. You would have to use poll_data[active_question], which IS a valid JSON object. jQuery should serialize this correctly. Remove the contentType -- I am pretty sure that is for php (not positive) but your code wouldn't work for me until I removed it. Finally, the appending of json=show to the query string doesn't do anything..it will just be ignored.
A couple minor things too: you can use .val() instead of .attr('value'), and have you looked into .serialize() to create your post data for you?
do this on server
$data;
$data->question=$_POST['question']
$data->answer=$_POST['answers']
echo json_encode($data);
do this for ajax request
$.ajax({
url: '/somewebsite/poll/create?json=show',
type:'POST',
//modified data proprty
data:poll_data[active_question],
success: function(data) {
alert(data);
}
});