return php variable to jquery ajax - php

I have an ajax function in jquery calling a php file to perform some operation on my database, but the result may vary. I want to output a different message whether it succeeded or not
i have this :
echo '<button id="remove_dir" onclick="removed('.$dir_id.')">remove directory</button>';
<script type="text/javascript">
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
if(rmd==0)
alert("deleted");
else
alert("not empty");
window.location.reload(true);
}
});
}
</script>
and this
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if(isset($_POST['dir_id'])){
$rmd=remove_dir($_POST['dir_id'],$bdd);
}
?>
my question is, how to return $rmd so in the $.ajax, i can alert the correct message ?
thank you for your answers

PHP
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if (isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
?>
JS
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did}
}).done(function(rmd) {
if (rmd===0) {
alert("deleted");
}else{
alert("not empty");
window.location.reload(true);
}
});
}

i advice to use json or :
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}

You need your php file to send something back, then you need the ajax call on the original page to behave based on the response.
php:
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo "{'rmd':$rmd}";
}
which will output one of two things: {"rmd": 0} or {"rmd": 1}
We can simulate this return on jsBin
Then use jquery to get the value and do something based on the response in our callback:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://jsbin.com/iwokag/3",
success: function(data){
alert('rmd = ' + data.rmd)
}
});
View the code, then watch it run.
Only I didn't send any data here, my example page always returns the same response.

Just try echoing $rmd in your ajax file, and then watching the console (try console.log(rmd) in your ajax response block)
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
console.log(rmd);
}
});
You can then act accordingly based on the response

Try echo the $rmd out in the php code, as an return to the ajax.
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
//if $rmd = 1 alert('directory not empty');
//if $rmd = 0 alert('directory deleted');
echo $rmd;
}
Your "rmd" in success: function(rmd) should receive the callabck.

Related

Returning php variable from jQuery ajax call

Im sure this is a simple solution, however I have had no success in my attempts as my jQuery & ajax is not the greatest. I am making an ajax call to my php script which is doing error checking for a form. If there are errors, I am showing a hidden div and displaying the error messages no problem. However if there are no error messages, I would like an alert to appear. The issue is the alert does not display when there are no errors
Javacript
$.ajax({
url: '../assets/inc/process.php',
type: 'post',
data: formData,
dataType: 'html'
})
.always(function(data){
if (data == 'success'){
alert('it worked!');
}
else{
$('#responsediv').show();
$('#responsediv').html(data);
}
});
});
I have also tried
if (data.success == 'success'){
alert('it worked!');
}
else{
$('#responsediv').show();
$('#responsediv').html(data);
}
PHP
if ($result_new_row){
$success = 'success';
echo $success;
}
I know for sure that the new row is being inserted as I can see it in the database.
Any help is appreciated. Thanks!
Pass the data back from PHP as an array (PS data type should be json)
PHP
if ($result_new_row){
$return['result'] = 'success';
//comment this out when you are positive it's working
echo "hello";
} else {
$return['result'] = 'error';
}
print(json_encode( $return);
jQuery
$.ajax({
url: '../assets/inc/process.php',
type: 'post',
data: formData,
dataType: 'json'
})
.always(function(data){
if (data.result == 'success'){
alert('it worked!');
} else {
$('#responsediv').show();
$('#responsediv').html(data);
}
});
});
If this isn't returning correctly make sure your PHP function is actually working right first.
If you use Chrome you can see your AJAX calls by bringing up the inspector and changing to the network tab, then clicking XHR will show you each AJAX request, what is being sent and the response.

How to use ajax to pass a variable to a php file using POST method?

I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});

Send data from Javascript to PHP and use PHP's response as variable in JS

I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3

Forms/PHP/Ajax load?

I'm currently learning PHP. I've made a simple script # http://hash.techho.me, only thing is, I want the form to submit then load the results via AJAX, without the user leaving the page. Possible?
post the form using ajax
$.ajax({
url:'yoururl',
data:$("form").serialize(),
type:'POST',
success:function(data){
alert("success");
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
jQuery.ajax() – jQuery API
Posting to the same page should do the trick. No need to use ajax for that
> <?php
>
> //do stuff with $_POST
> ?>
>
> <html> <body> <form method="post">
>
> <?php echo $result ?>
>
> </form>
> </body>
Fike
use ajax for this, lets suppose try this one for your practice
var string = $("#string").val();
var dataString = 'string=' + string ;
if(string==''){
alert('enter any string');
}
else{
$.ajax({
type: "POST",
url: "path of php file",
data: dataString,
suceess: function(){
//do something
},
error: function(){
//do something
}
});
}
You can use jQuery or Prototype JS libraries to make an easy AJAX call. Example using jQuery would be:
$.ajax({
url:'hashed.php',
data:$("form").serialize(),
type:'POST',
success: function(data){
$('hashmd5').html(data.md5);
$('hashsha1').html(data.sha1);
},
error: function(jxhr){
alert(jxhr.responseText);
}
});
Don't use the same id value in HTML, never ever. They must be unique to correct perform JavaScript functions on elements.
yes it is possible. Write a javascript function that would trigger on submit, disable the submit button so user couldn't press it again, and finally request the server via ajax. on successful response update the content. Something like following in Jquery
$('.form-submit').click(function(event)) {
event.preventDefault();
if(form is valid and not empty) {
$.ajax({
type: "POST",
url: "path to script that will handle insetion",
data: "data from form", //like ({username : $('#username').val()}),
suceess: function(data){
//update the content or what. data is the response got from server. you can also do like this to show feedback etc...
$('.feedback').html("Data has been saved successfully");
},
error: function(){
$('.feedback').html("Data couldn't be saved");
}
});
}
}

Jquery: Only fill in data from .load if there is content?

Im using the jquery .load function to query a php file that will output some data. Now sometimes the script will return nothing. In this case, can I have the load function not put any data into my specified div? (right now it clears out the div and just puts a blank white area.
Thanks!
try using $.get;
$.get('<url>',{param1:true},function(result){
if(result) {
$('selector').html(result);
}
else {
//code to handle if no results
}
});
Use $.get
http://api.jquery.com/jQuery.get/
in addition to #jerjer's post, you can also use this:
var paramData= 'param=' + param1 + '&user=<?echo $user;?>';
$.ajax({
type: "GET",
data:paramData,
url: "myUrl.php",
dataType: "json", // this line is optional
success: function(result) {
// do you code here
alert(result); // this can be an any value returned from myUrl.php
},
statusCode: {
404: function() {
alert('page not found');
}
}
});

Categories