I am making an AJAX call but its not returning a value in the success handler. This is my AJAX call. I have checked that it's hitting the PHP file correctly
var msj;
$.ajax({
type: "POST",
url: "ajaxFile.php",
data: {
name: name,
status: status,
description: description,
action: 1
},
sucess: function(data){
msj = data;
alert(data);
}
});
alert(msj);
My PHP code is as follow:
if (isset($_POST['action']))
{
if ($_POST['action'] == 1)
{
$obj = new project($_POST['name'], $_POST['active'], $_POST['description']);
$obj = testInput($obj);
$check = validateName($obj->getName());
if ($check == 1)
{
echo $nameError;
}
else
{
print "asdasdasd";
}
}
}
Please help me tracking the mistake.
As far as I can see there's a syntax error in your code. There's sucess instead of success.
You are only providing a "success" callback function. You should also provide an "error" callback so you can debug and see what is wrong. You can also provide a "complete" callback that will be used in both alternatives.
var msj;
$.ajax({
type:"POST",
url:"ajaxFile.php",
data:{name:name,status:status,description:description,action:1},
complete:function(data){
msj=data;
alert(data);
}
});
alert(msj);
In your PHP, you could add
header('Content-Type: application/json');
to make sure JQuery identify well your web service.
Related
I'm trying to catch a PHP variable in AJAX, but I'm not having much luck.
myCode.php
<?php
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
?>
In my HTML, I have the following:
<script>
function initiate_delete() {
$.ajax({
url: '{$modulelink}&action=delete',
type: "post", //request type,
dataType: 'json',
data: {
type: 'test'
}
});
}
</script>
Is there any way to have AJAX wait for the PHP to execute and then get $status when I execute initiate_delete?
Thanks in advance.
Change code to
<?php
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
echo $status
or short it to
echo myFunction() ? "success" : "failure";
To wait for an answer - you can execute the request asynchronously, and get the result in the .done() callback
$.ajax({
url: $(this).attr('href'),
type: 'POST',
fail: function(){
//do something
},
done: function(m){
/// do something else
}
});
Your PHP needs to return the value. If you want to keep the dataType Json (suggested) you just need to json_encode your output.
So the PHP becomes:
<?php
$type=$_POST['type'];
//myFunction that will return a status
if(myFunction() === true){
$status = "success";
}else{
$status = "failure";
}
echo json_encode('status'=>$status);
?>
Then you need to tell Ajax what to do with the answer received using .done()
So your Ajax will become:
$.ajax({
url: '{$modulelink}&action=delete',
type: "post", //request type,
dataType: 'json',
data: { type: 'test'}
}).done(function(data){
console.log(data.status);
});
Now you can do what you want with status but only in the .done() function. The rest of your js will be executed without waiting for ajax to return a value since it is asyncronous. So add here all the logic like dom manipulation and so on depending on this response.
Obviously you can have more data returned by php in the json and acccess them by key as done for status.
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.
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
here is it my code i call ajax by jquery $.ajax
js
$("#form-login").submit(function(){
var email = $("#menu_username");
$.ajax({
type: "post",
url: "register_cmd.php",
data: {email:email},
dataType: "json",
cache:false,
success:function(data){
if(data.c == "ok"){
window.location.reload();
} else {
alert(data);
}
return false;
}
})
});
register_cmd.php
<?PHP
include 'system/library/main.php';
$main = new mainQuery();
$chk_email = $main->checkEmail($email);
?>
main.php
function checkEmail($email){
$result = "function here";
return $result;
}
then it return 500 internal server error i don't know why
I just had this problem myself, even though i couldn't find the reason for it in my case, when changing from POST to GET, the problem 500 error disappeared!
because GET method sends the encoded user information appended to the page request.
type:'POST'
to
type:'GET'
I doing little changes in your codes. Just try this
var email = $("#menu_username").val(); // if you want to take the value from email field
$.ajax({
type: "POST",
url: "register_cmd.php",
data: {email:email},
dataType: "json",
cache:false,
success:function(data){
if(data.result == "ok"){
window.location.reload();
} else {
alert(data.result);
}
return false;
}
});
AND change the codes in register_cmd.php as follows
<?PHP
include 'system/library/main.php';
$main = new mainQuery();
$chk_email['result'] = $main->checkEmail($email);
print_r(json_encode($chk_email)); // if you are using json, you should use json_encode before it returns.
?>
the function in main.php need's a class arround it
class mainQuery {
public function checkEmail($email){
$result = "function here";
return $result;
}
}
otherwise you cannot instance new mainQUery;
also on top of everything to debug set
error_reporting(E_ALL);
ini_set('display_errors', true);
500 are serverside errors and have nothing to do with ajax.
probably this line:
var email = $("#menu_username");
might have to be
var email = $("#menu_username").text();
//or
var email = $("#menu_username").val();
It doesn't matter if it's a POST or GET request.
I am trying to get the data return from a function called by a jquery ajax call. My function is located in a a php file and it looks liket his
valid_user() {
$id = $_POST('id');
if($id == 'hello'){
return true;
}
else{
return false;
}
}
and here is my ajax call
$.ajax({
type: "POST",
url: path + "valid_user",
sucess: function(msg) {
alert("Data returned: " + msg );
}
});
I have tested everthing and the function is wokring ( has been changed for this example) but I can not the return value of the function valid_id(). How do I get this? the variable msg keeps coming back empty. Thanks
From my understanding, there are several issues.
1) the method valid_user() is not been called.
2) The url doesn't look like it is correct either.
3) The "success" keyword is spelt "sucess".
4) You aren't passing any "data".
Here is an example ajax call tailored to what you may want.
$.ajax({
type: "POST",
url: "validateUser.php",
data: "id=49",
success: function(msg){
alert( "true or false: " + msg );
}
});
It looks like you misspelled sucess----but this may not be in your running code. You should check the second parameter of success:
success:function(data, textStatus)
You need to write PHP server-side code that calls the function and writes its return value to the output stream. For example:
<?php echo valid_user(); ?>
This should work - you might want to put better sanitizing on the POST value just in case.
In the PHP file:
$id = isset($_POST['id']) ? trim($_POST['id']) : '';
$return = 'false';
if($id!=''){
valid_user($id);
}
echo $return;
valid_user($id) {
if($id == 'hello'){
$return = 'true';
}
}
jQuery Call:
<script>
id = 'hello';
$.ajax({
type: "POST",
url: "validateUser.php?id="+id,
success: function(msg) {
alert("Data returned: " + msg );
}
});
</script>
Thank you for your help, I figured out the issue, the reason why it was not working was becuase my function valid_id() was returning true or false, and I needed to return echo "true"; and echo "false"; once I did this the msg variable contained the data true or false.