PHP not returning Ajax Call - javascript

I'm trying to send over the data from my textarea using an ajax call to my PHP file, but we aren't getting any response back from the PHP file.
<textarea id="area" cols="70" rows="30"></textarea>
<button id="submit">Submit</button>
<script>
$('#submit').click(function (e) {
e.preventDefault();
var info = $('#area').val();
$.ajax({
type: "POST",
url: 'pages/assignments/response.php',
data: {area: info}
});
});
</script>
<?php
if (!empty($_POST['area'])) {
$success = json_encode('succes');
return $succes;
};
?>
-- # Answer # --
I thought I had already tried an echo in this piece of code, but I think I just missed the output on the webpage and thought it wasn't working.
<?php
if (!empty($_POST['area'])) {
echo "success";
};
?>

Thanks Mickael for the answer!
I completely forgot to add an echo to my code.
<?php
if (!empty($_POST['area'])) {
$succes = json_encode('succes');
echo $succes();
};
?>

Your ajax post :
$('#submit').click(function (e) {
e.preventDefault();
// information to be sent to the server
var info = $('#area').val();
$.ajax({
type: "POST",
url: 'pages/assignments/response.php?return=1',
data: {area: info},
dataType:'json',
success:function(r){
console.log(r);
}
});
});
and your php response will be like
Php file:
<?php
if ( $_GET['return'] == 1 && isset($_GET['return']) ) {
echo json_encode('succes');
exit;
};
?>

Related

refresh post user without refresh page ajax not working

i don't know , not working !
-i have table post for user
i want display post without refresh page used ajax
<form class="posting" method="POST" autocomplete="off"
action="createpost.php">
<textarea name="text" class="textarea" ></textarea>
<button class="btn-ajouter" type="submit" name="ajouter" value="ajouter">ajouter</button>
</form>
// code mysql the same page
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
while($row=$stmt->fetch() )
{
?>
<div class="allpost">
<?php
echo $row['post'].'<br>' ;
?>
</div>
<?php
}
?>
(jquery exist in page index ) ( )
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'createpost.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
- but not working
Change this button. Since you want to run an AJAX call It shouldn't be a SUBMIT.
<button class="btn-ajouter" type="submit" name="ajouter" value="ajouter">ajouter</button>
to this
<button class="btn-ajouter" id="ajouter" name="ajouter" value="ajouter">ajouter</button>
and change your JQuery from
$('form').on('submit', function (e) {
to
$('#ajouter').on('click', function (e) {
Also, you won't need to e.preventDefault();
Seems like that you are trying to display the information on the same page where the user submits the form. I would advise you to put the php code in a separate file and then print it somewhere on the page with javascript. A sample code for that would be something like this:
Javascript code on your current page
<script>
$(function () {
// I actually agree with Lawrence Cherone's suggestions here, so i'm including them
$('form.posting').on('submit', function (e) {
form_data = $(this).serialize()
e.preventDefault();
$.ajax({
type: 'post',
url: 'separate.php',
data: form_data,
success: function (response) {
//then you can have the server output as an object
response = JSON.parse(response);
//And print it somewhere, for example:
$('#someDiv').html(response.whatever);
}
});
});
});
</script>
Code for php in a separate file
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
$row = $stmt->fetch();
echo json_encode($row['post']);
Change this form,
<form class="posting" method="POST" autocomplete="off" onSubmit="return false">
<textarea name="text" id="text" class="textarea" ></textarea>
<button class="btn-ajouter" type="submit" id="ajouter" name="ajouter" value="ajouter">ajouter</button>
</form>
Ajax Goes Here,
$(function(){
$("#ajouter").click(function(){
var text=$("#text").val();
$.ajax({
url:"createpost.php",
method:"POST",
data:{text:text},
cache:false,
success:function(data){
$("#result").load(location.href+ "#result");
}
});
});
});
PHP & HTML Code goes here
<div id="result">
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
while($row=$stmt->fetch() )
{
?>
<div class="allpost">
<?php
echo $row['post'].'<br>' ;
?>
</div>
<?php
}
?>
</div>

Using AJAX to check variables in database, if true, header to a certain page, PHP, JAVASCRIPT

I'm trying to use AJAX to check variables in the database, and if it's true, then it should make it header to a certain page, except in this testing phrase, I'm not checking any variables. I'm just testing if it'll header off to that certain page if I call the function. I started at test1.php, but it should've called the ajax function, and immediately header off to test3.php, but it didn't. I'm not sure what I did wrong. Please take a look:
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function nopassAjax(url,timeout) {
$.ajax({
type: "POST",
url: url,
error: function(xhr,status,error){alert(error);},
success:function(data) {
setTimeout(function() { timeoutAjax(url,timeout); }, timeout);
}
});
}
</script>
test1.php
<?php
include('ajax.php');
echo "<script>";
echo "nopassAjax('test2.php',1000);";
echo "</script>";
?>
test2.php
<?php
//checks some stuff in the database
//if true, header off to test3.php
header("Location: test3.php");
?>
test3.php
<?php
echo "Hello";
?>
From your question I'm assuming you want to redirect to the page that's returned from your AJAX call. You can't do this from PHP alone.
Javascript:
$.ajax({
method: "POST",
url: someUrl
}).fail( function( error ) {
alert( error );
}).done( function( response ) {
window.location = response;
});
PHP:
<?php
echo "test3.php";
?>

Always get empty result when call a ajax in my jquery

i'm creating a plugin for WooCommerce
in my plugin php file when i call a php file with jquery ajax i get empty result
this is my ajax code:
jQuery(function() {
jQuery.ajax({
url: '<?php echo RAKHSH_WC_QUICK_VIEW_URL ?>/rakhsh-data-for-pop.php',
success: function(output) {
alert(output);
}
});
});
and this is my php file:
<?php
$output = 'test';
return $output;
?>
You should change this:
<?php
$output = 'test';
return $output;
?>
To this:
<?php
$output = 'test';
die($output); // or echo or print
?>
Returning a variable will not return it as a response to an ajax call.
try this
<?php
$output = 'test';
echo $output;
?>
You can try this:
create a empty variable and insert your data to this.
var response = '';
$.ajax({ type: "GET",
url: '<?php echo RAKHSH_WC_QUICK_VIEW_URL ?>/rakhsh-data-for-pop.php',
async: false,
success : function(text)
{
response = text;
}
return response;
});

Passing value to php script via Ajax

I have a problem to pass value to my php script via Ajax, there is my code :
I send value to ajax via a href link :
After scan directory i get links of my files on href :
<?php echo $file; ?>
My js function to receive value :
function getfilename(content) {
alert(content); // i can see my value here
$.ajax({ //not work
type: 'POST',
url: 'script.php',
data:{song: content},
async: false,
success: function(response) {
alert(response); //nothing
});
}
My script.php
$album = $_POST['song'];
echo $album;
I dont understand why it does not work.
Thank you for your help!
Try changing
<?php echo $file; ?>
To this
<?php echo $file; ?>
Maybe your page is refreshing before the ajax data loads.
When you use the link element it will automatically go to the location in the href after it executes the onclick event. Leaving it empty will reload the page.
I would recommend you to add a "return false;" as the last instruction of the onclick.
<?php echo $file?>
Hope this helps.
Looking to your js code your success callback is missing a "}" in the end of function.
// $file = 'teste';
<?php echo $file?>
function getfilename(content) {
alert(content);
$.ajax({
type: 'POST',
url: 'script.php',
data:{song: content},
async: false,
success: function(response) {
alert('Response: ' + response); //Alerts Result
}
});
}
// Script.php
<?php
echo $_POST['song']
?>

Send array from javascript to php then write it to file

i cant seem to get this to work, i'm trying to send a variable to php so it can write it to file but its just not working..
var jsonString = JSON.stringify(vars);
$.ajax({
type: "POST",
url: "woepanel.php",
data: {data : jsonString},
cache: false,
success: function(){
$('#sent').attr("bgcolor", "#00FF00");
$('#notsent').attr("bgcolor", "#FFFFFF");
}
});
it seems to be sending ok because the success works but php wont pick it up
<?php
$vars=json_decode($_POST['jsondata']);
?>
<?php
$fp = fopen('vars.txt', 'w');
fwrite($fp, $_POST["jsondata"]);
fclose($fp);
?>
Try this code:
<?php
$vars=json_decode($_POST['data']);
$string_data = serialize($vars);
file_put_contents('vars.txt', $string_data);
?>
you have this
data: {data : jsonString}
in your ajax call which means you should use
$_POST['data']
to extract the value

Categories