ajax post request to php without response (isset every time false) - php

I'm using jquery multiselect plugin and I want to perform an ajax request on a select/deselect event.
My problem: When I send the request to the php file, ISSET(VAR) returns every time false so that I can't pass variable to the php file.
But Firebug extension for Chrome/Firefox shows me that the POST value is set right POST -> "Response myvar" but GET is empty.
How do I pass the variable to the php file?
(I've searched arround the web but found nothing.)
My script, where this pointer is from the multiselect plugin and afterSelect returns if a object is selected
afterSelect: function()
{
this.qs1.cache();
this.qs2.cache();
count++;
var dataString = "count=" + count;
if ( count > 0 )
{
$.ajax
({
type: 'POST',
url: 'page-to-send-request.php',
data: dataString,
success: function()
{
$("#div-to-load").load("page.php #div-to-load").fadeIn('slow');
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
});
}
},
The php page to load has for test only
if($_POST['count'])
{
$count = $_POST['count'];
echo "Count " .$count;
}
else{ echo "FALSE"; }
Expected result should be
Count 5
But real output is
FALSE

1st try
success: function(data)
{
console.log(data);
},
it should output "Count " .$count; if not
try to use
var dataString = {count: count};
and then you can use
$("#div-to-load").html(data).fadeIn('slow');
the reason of return false .. you used the .load to load the php page .. when you load it .. javascript know it as a separated page .. so $_POST['count'] is undefined in this case . and It will return False always
your success function should be like this
success: function(data)
{
$("#div-to-load").html(data).fadeIn('slow');
},

Related

500 error when passing variables to function

I have the below function in my WordPress functions file, and if I run it as below without the two parameters it works fine, but when I pass the parameters the error handler in the jQuery returns status 500.
If I don't pass the parameters to the PHP function I get status 200 from jQuery, but it's coming from the error handler, and not from the success handler. Why so?
function subscribe_funk(){//$payment_method, $customer_handle){
return "This is a test";
die();
}
It gets called from this ajax:
function subscribe(data) {
jQuery.ajax({
url: PT_Ajax.ajaxurl,
type: "POST",
data: {'action': 'subscribe_funk', 'payment_method': data.payment_method, 'customer_handle': data.customer},
cache: false,
dataType: 'json',
beforeSend: function(){
console.log('Before send subscribe');
},
complete: function(){
},
success: function (response) {
console.log('Message from success handler: ');
console.log(response);
},
error: function(xhr, status, error){
console.log("Message from error handler:")
var errorMessage = xhr.status + ': ' + xhr.statusText
console.log(errorMessage);
}
});
}
Your function expects 2 parameters, however WP/ajax is not passing them directly.
You need to fetch them from $_POST array yourself:
function subscribe_funk(){
$payment_method = $_POST['payment_method'];
$customer_handle = $_POST['customer_handle'];
return "This is a test";
die();
}
Also, you may want to sanitize the post data with sanitize_text_field() or similar function.
Here is a relevant thread in WP StackExchange: how to pass parameters from jQuery ajax to a PHP function

jQuery / Ajax to get html and save with php

I am trying to get a jQuery script to run behind the scenes with php. It basically will get the contents of a div with jQuery (works) then calls a script with ajax (works) but I need the ajax script that called the php to send the vars to php so I can save the conents.
Here is the code:
<script>
$( document ).ready(function() {
$( ".tweets" ).click(function() {
var htmlString = $( this ).html();
tweetUpdate(htmlString);
});
});
</script>
<script>
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
</script>
and my code for saveTweets.php
<?
// SUPPOSED TO receive html conents called htmlString taken from a div
// and then I will write this code to a file with php and save it.
echo $_POST[htmlString];
?>
You have to give a name to the parameter, so that PHP can retrieve it. Change the $.ajax call to do:
data: { htmlString: htmlString },
Then in your PHP, you can reference $_POST['htmlString'] to get the parameter.
Correct your funcion.
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: "htmlString="+htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
then on saveTweets.php page write below line, you will get value on that page.
echo '<pre>';print_r($_REQUEST );echo '</pre>';
Using json is better for sending data:
data_htlm=[];
data_html.push({"htmlString": htmlString});
$.ajax(
{
type: "POST",
dataType: "json",
url: "saveTweets.php",
data: JSON.stringify(data_html),
success: function(html)
{
console.log(html);
}
});
now with php you can just do this:
echo $_POST['htmlString'];
You can use the $.post method to post to a PHP page and then retrieve the result from that page in a callback function.

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

How to get the PHP AJAX error to get to show up in my jQuery code?

I have some PHP AJAX code that is supposed to validate some parameters sent by jQuery and return some values. Currently, it consistently returns invokes the jQuery error case, and I am not sure why.
Here is my jQuery code:
$('.vote_up').click(function()
{
alert ( "test: " + $(this).attr("data-problem_id") );
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
alert (json);
},
error : function(json)
{
alert("ajax error, json: " + json);
//for (var i = 0, l = json.length; i < l; ++i)
//{
// alert (json[i]);
//}
}
});
//Return false to prevent page navigation
return false;
});
and here is the PHP code. The validation errors in PHP do occur, but I see no sign that the error that is happening on the php side, is the one that is invoking the jQuery error case.
This is the snippet that gets invoked:
if ( empty ( $member_id ) || !isset ( $member_id ) )
{
error_log ( ".......error validating the problem - no member id");
$error = "not_logged_in";
echo json_encode ($error);
}
But how do I get the "not_logged_in" to show up in my JavaScript of the jQuery so that I know it is the bit that got returned? And if it isn't, how do I make it that that error is what comes back to the jQuery?
Thanks!
Don't echo $error in the json_encode() method just simply echo $error like so. Also, don't use the variable json, use the variable data. Edited code below:
PHP
if ( empty ( $member_id ) || !isset ( $member_id ) )
{
error_log ( ".......error validating the problem - no member id");
$error = "not_logged_in";
echo $error;
}
jQuery
$('.vote_up').click(function()
{
alert ( "test: " + $(this).attr("data-problem_id") );
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=+';
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
// ? :)
alert (data);
},
error : function(data)
{
alert("ajax error, json: " + data);
//for (var i = 0, l = json.length; i < l; ++i)
//{
// alert (json[i]);
//}
}
});
//Return false to prevent page navigation
return false;
});
jQuery uses the .success(...) method when the response status is 200 (OK) any other status like 404 or 500 is considered an error so jQuery would use .error(...).
You must handle all output returned from the php script in the success handler in javascript. So a not-logged in user in php can still (should normally...) result in a successful ajax call.
If you are consistently getting the error handler in your javascript call, your php script was not run or is returning a real error instead of a json object.
According to the manual, you have 3 variables available in the error handler, so just checking these will tell you exactly what the problem is:
// success
success: function(data)
{
if (data == 'not_logged_in') {
// not logged in
} else {
// data contains some json object
}
},
// ajax error
error: function(jqXHR, textStatus, errorThrown)
{
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
//
Easiest way to debug PHP in this case, is to modify .htaccess to create an error log.
php_flag log_errors on

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