I'm developing a part of a website that upload the content of a textarea and of an input text to a remote database, but I have a problem in the AJAX request...
my JavaScript:
function pubblica(pubblicato){
htmlpuro = document.getElementById("htmlpuro").value;
oggetto = document.getElementById("oggetto").value;
$.ajax({
type: "POST",
url: "salva_doc_ajax.php",
data: "oggetto="+oggetto+"&html="+htmlpuro+"&pubblicato=0",
dataType: "html",
//Inizio visualizzazione errori
success: function(msg)
{
alert(msg);
},
error: function()
{
alert("Chiamata fallita, si prega di riprovare...");
}
});
}
my salva_doc_ajax.php:
<?php
if(isset($_POST['name']) && isset($_POST['html']) && isset($_POST['pubblicato'])){
$oggetto = $_POST['oggetto'];
$html = $_POST['html'];
$pubblicato = $_POST['pubblicato'];
$oggetto = addslashes(htmlentities($oggetto));
$html = addslashes(htmlentities($html));
echo "Oggetto: $oggetto";
echo "<br>HTML: $html";
echo "<br>Pubblicato: $pubblicato";
}else{
echo "Errore";
}
?>
I've tested that in 'htmlpure' and in 'oggetto' there is data...
everytime I run this js function I get "Errore" from the php page, like if I don't send $_POST variables...
I believe that in an ajax POST, your data should be an object. You are sending a query string for a GET request.
Also, as #Kaddath said, there is no name in your post.
See what you're getting by adding this line to the very top of salva_doc_ajax.php and comparing it to what you think you're getting:
die(print_r($_POST));
Related
I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);
I am trying to send information using AJAX from JavaScript in one file to PHP in another file. When I inspect the page on chrome after I have pressed the button, it shows the values under the form data sub section in networks, however, if I var_dump[$_POST] it shows it is empty.
Here is my JavaScript:
function details(id) {
var data = {"id" : id};
jQuery.ajax({
url: "/Example/includes/detail.php",
type: 'POST',
data: data,
success: function(data){
jQuery('body').append(data);
},
error: function(){
alert("Error");
}
});
}
Here is the PHP:
<?php
$id = $_POST['id'];
$id = (int)$id;
?>
Any help would be greatly appreciated. Thanks
So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. The $content is a card (similar to KickStarter) of topic data. What I'm trying to do is a pass the 'topic_id' of each topic-instance so that I can then use it in the success function, to then initiate ANOTHER AJAX request (but to Discourse).
With attempt 2), I get a null when viewing its value in the web inspector.
The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console):
$.post( "/wp-content/mu-plugins/topic-search.php", { topicID: $topicFilter, filterBy: $sortByFilter },
function( data ) {
console.log(topic_id);
data = data.trim();
if ( data !== "" ) {
//get the participants data for avatars
$.getJSON('http://ask.example.com/t/' + topic_id + '.json', function() {
The end of topic-search.php, which echoes out the built up card. Script is supposed to return the topic_id variable for use in the success function.
}
//One attempt: echo $content; //
//Another attempt: echo json_encode(array('data' => $content, 'topic_id' => $row['topicid']));//
}
?>
<script>
var topic_id = "<?php echo $row['topicid'] ?>";
</script>
Try this:
In php
$inputJson = file_get_contents('php://input');
$input = json_decode($inputJson, true); //Convert JSON into array
In javascript
var $url = '/wp-content/mu-plugins/topic-search.php';
var $json = JSON.stringify({topicID: $topicFilter, filterBy: $sortByFilter});
$.ajax({
url: $url,
type: "POST",
data: $json,
dataType: "json",
success: function(data){//you will have the body of the response in data
//do something
},
error: function(data){
//do something else
}
});
EDIT:
This will request $url with the $json data. You will have it available on $input on the server side as an array. You can then on the server prepare a response with a json body that you will have available on the success function as the data variable.
I'm trying I'm trying to send a specific section of my URL string, to my php file, to then populate my page accordingly. Everything is working fine, except for the AJAX POST method. I've tried doing var_dump of the POST variable in my PHP, and my array is empty (so I know nothing is getting through).
The success DOES return as being passed, so I don't know where the data is going. I'm testing locally on XAMPP, and I've combed through SoF and no luck on any of the fixes. My code is below.
Screen shot of page:
jQuery AJAX Request:
$(document).ready(function() {
str = window.location.href;
pos = str.search("pages/"); //42
send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
tom: send
},
success: function() {
$.get("retrieve.php", function(data, status) {
$("#main").html(data);
}) //ends GET function
},
error: function() {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
echo "<i>hello</i>";
echo var_dump($_POST);
$url = $_POST['tom'];
json_decode($url);
echo $url;
Try the below,
Also you don't need to json_decode unless you send a json request,And please make sure all the post values are passing.
Ajax:
$(document).ready(function() {
var str = window.location.href;
var pos = str.search("pages/"); //42
var send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
'tom': send//make sure this is not empty
},
success: function(data) {
console.log(data);
},
error: function(arguments) {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//echo "<i>hello</i>";
//echo var_dump($_POST);
$url = $_POST['tom'];
json_encode($url);
echo $url;
}
JS CODE:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
}
});
PHP CODE:
<?php
$username = "trainerapp";
$password = "password";
$hostname = "localhost";
$link = #mysql_connect($hostname, $username, $password);
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator where availability_status in (1,2)");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
$j = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$j]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$j]['firstname'] = $row1['firstname'];
$traineravaildetails[$j]['lastname'] = $row1['lastname'];
$traineravaildetails[$j]['emailidvalue'] = $row1['email_id'];
$j++;
}
echo json_encode(array('result1'=>$trainerdetails,'result2'=>$traineravaildetails));
}
?>
Please help me with the code in the ajax success function area. I've tried using initChart2 but I get an error which says initChart2 is not defined. I don't seem to understand of how to get two arrays from PHP in ajax since I'm a newbie ajax. If someone can help me with the code along with explanation, it'd be great. And I also need to know how to differentiate outputs in ajax which are sent from PHP.
You have two choices:
First one is to simply parse received (text) data to JSON:
var jsonData = JSON.parse(data);
// or simply data = JSON.parse(data);
But the best one in my oppinion is to specify json dataType to the $.ajax() request:
$.ajax(
data: {action:'test'},
type: 'post',
dataType: 'json',
success: function(data) {
...
}
});
This way, $.ajax() will also check for the validity of the received JSON data and error callback will be called instead of success one in case of wrong JSON data received.
...also is important to note you missed to send the json content-type header in your php with:
header("Content-Type: application/json");
Sending this header the dataType: 'json' parameter is no longer (strictly) necessary because $.ajax() guesses it by default attending to the received content-type. But, personally, I prefer to do both.
See $.ajax() documentation.
You forgot:
header("Content-Type: application/json");
… in your PHP.
While you are outputting JSON, you are telling the browser that it is HTML (which is the default for PHP) so jQuery isn't converting it to a useful data structure.
Add that and then you should be able to access data.result1 and data.result2.
To get ajax data:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
data.result1;
data.result2;
}
});
You can use console.log(data); to view data structure