jQuery success function not executing - php

the first success function works, the second doesnt... it works if I change datatype to text... but if i change datatype to text am not able to iterate through the array .. for example i require data[0].. which works with json....but with json success function is not working ...
var turl = "getForum.php";
var turl = "getForum.php";
var wurl = "getDiscussions.php";
$.ajax({
url:turl,
type:"POST",
dataType:"json",
success:function(data){
forumid = data[0]; // this works ...
dataString = 'forumid='+ forumid;
$.ajax({
url:wurl,
type:"POST",
dataType:"json",
data:dataString,
success:function(data){
alert(data); // this works if I change datatype to text... but if i type datatype to text am not able to iterate through the array .. for example i require data[0].. which works with json....but with json success function is not working ...
}
});
}
});
php file return json object
$query1 = " select * from discussforum where forumId= '$forumid'; ";
$result1 = mysql_query($query1);
while($info1 = mysql_fetch_array( $result1 )){
echo json_encode($info1);
}

Are you sure about your PHP is returning only one JSON object? If not:
$ret = array();
while($info1 = mysql_fetch_array( $result1 )){
$ret[] = $info1;
}
print json_encode($ret);

I think the solution is delineated in the comments, but here it goes in a bit more detail. First take a look at the fine documentation for jQuery.ajax(). You need to add an error callback to all your Ajax calls. with the following signature:
error(jqXHR, textStatus, errorThrown)
You can just add a parameter to .ajax() like this:
error: function(jqXHR, textStatus, errorThrown) {
console.error(textStatus);
},
This way you will see in the console every error that happens during the Ajax call and also during the processing of the message. You can define a generic ajaxError callback in some common .js file and use it everywhere.
In this case you are explaining very well the cause of the error: what getDiscussions.phpis returning is not a JSON, and thus the jQuery parser cannot understand it when you set dataType:"json": it would call the error callback if there was one. It works however when the dataType is set to text. So the POST request is probably failing.
To see what it is sending you can just extract it in the error callback, like this:
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error in response: ' + jqXHR.responseText
},
so you can diagnose the problem in the server.

Related

Unable to send javascript variable to php file using ajax

I want to send a javascript variable to php file which shows the comments on a webpage.
I was able to send this js variable to some other php file, but I can't do it with this comment-list.php file. I guess there is some problem with JSON.
function listComment() {
$.ajax({
url: "Komentarji/comment-list.php",
data : {page_num: page_num},
type : 'post',
success : function(response) {
}
});
$.post("Komentarji/comment-list.php", function(data) {
var data = JSON.parse(data);
.
.
.
The function is called here:
$(document).ready(function() {
listComment();
});
Inside comment-list.php I try to get the variable that was sent with ajax. However it doesn't work and comment's aren't displayed on page. If I delete this line, the comments work again (but of course, I don't get the sent variable).
$num = $_POST['page_num'];
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
Here is the javascript variable and included php file.
<script>
var page_num = 1;
</script>
<?php
include($_SERVER["DOCUMENT_ROOT"]."/index.php");
?>
I get this error in console: Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()
As said eariler if I remove the line where I get the variable with post, this error disappears.
You shouldn't use $.ajax and $.post to do the same thing, pick one, I'd say remove the $.post one and dont forget to put an exit; statement after you echo the response to avoid PHP to process further code if existing, also worth mentionning but not necessary, you can put the dataType to json so dataType: 'json' in the $.ajax call, dataType is used to tell jQuery what to expect as a response type from the server, as you are echoing the response by encoding it in JSON, you won't need to parse the response on your JS side if you speficied the dataType beforehand.
$.ajax({
url: "Komentarji/comment-list.php",
data : {page_num: page_num},
type : 'post',
dataType: 'json',
success : function(response) {
console.log(response); //will show the result of echo json_encode($record_set); from your PHP
}
});
$num = $_POST['page_num'];
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
exit; //exit statement here
Following discussion with OP who wanted to use the $.post method, this is how it is done, pass the data as an object to the second attribute (more infos here):
$.post("Komentarji/comment-list.php", {page_num: page_num});
Just make your format JSON in your JS script
$.ajax({
url : 'Komentarji/comment-list.php',
type: "POST",
data: page_num:page_num,
dataType: "JSON",
success: function(data)
{
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});

How to post value from one php page to another using ajax

I am trying to post one value which I got using Jquery, so I have to pass that value to php page using ajax. but when I did this I got Undefined index data error.
Here is my code:
$("#requirementtable tbody tr").on("click", function(){
desc = $(this).closest("tr").find("td:nth-child(4)").text().trim();
$.ajax({
type:"POST",
url:"get_diagnosis.php",
data: desc,
success: function (data, textStatus, jqXHR)
{
alert(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("some error occured->" + jqXHR.responseJSON);
}
})
})
this is my php code:
<?php
$data = $_POST['data'];
echo $data;
?>
Check the desc variable has some value in it and you have to post data like,
data: {data:desc},
AJAX Code,
$.ajax({
type:"POST",
url:"get_diagnosis.php",
data: {data:desc},
success: function (data, textStatus, jqXHR) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("some error occured->" + jqXHR.responseJSON);
}
});
And in PHP use isset() to prevent undefined errors like,
<?php
$data = isset($_POST['data']) ? $_POST['data'] : 'Not defined';
echo $data;
?>
If you want JSON response format then use dataType:'json' in $.ajax, and use json_encode() in PHP to respond it.
here is a simple example that contains your code and solution
//Data Object
var obj={
name:"uneeb",
city:"gujranwala",
state: "punjab"
};
//Data Object
//Ajax Request to Server
$.ajax({
type: 'post',
url: 'someFile.php',
data:object,
success: function (data) {
//do something here
}
});
//Ajax Request to Server
//PHP
echo $_POST['name']; //prints uneeb
echo $_POST['city']; //prints gujranwala
echo $_POST['state']; //prints punjab
//PHP
Replace the followings:
desc = $(this).closest("tr").find("td:nth-child(4)").text().trim();
// remove ^^^^^^^^^^ since you're currently in tr click
desc = $(this).find("td:nth-child(4)").text().trim();
And replace to:
data: desc,
With:
data: {data:desc}, //to pass data as object as you don't have serialized data
And inside your php code, you can get data using $_POST['data'].
replace this data: desc, field in your ajax to data:{data: desc},, this is the cause you are not getting data in your php code

Ajax Doesn't give me anything in the console?

Updated Question to better reflect the communities support
Based on community support I have changed the Ajax function to be as such:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The resulting PHP Class is as such:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET['element_name'])){
$this->_element_name = $_GET['element_name'];
echo $this->_element_name;
}
}
}
The network tab shows that I have some out put from activating the Jquery which I have shown below:
The Console is spitting out no errors, yet not echoing the element name. I have read up on the Jquery Ajax API and everything I have been doing, thus far, seems to be correct. Yet I am not getting the desired out put.
Note: The response tab is empty.... In other words I am not getting a response back.
You're not passing in the event to your click handler.
Use.
$('a').click(function(e){
// Your code
});
$.ajax({
url : "<?php echo CORETHEME_ADMIN_TEMPLATE_HELPER_URL . 'UncheckPackageThemeHelper.php'; ?>",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(result) {
console.log(result)
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
Simplify the situation. Just for a moment, change your AJAX processor file (UncheckPackageThemeHelper.php) to read like this:
UncheckPackageThemeHelper.php
<?php
$test = $_POST['element_name'];
$r = 'PHP received: [' .$test. ']';
echo $r;
die();
Also, change your AJAX success function to read like this:
success: function(result) {
alert(result);
},
At least, this will show you that your AJAX is getting through.
Then, start adding things back into your AJAX processor file (one or two at a time) and keep echoing something out so that you can discover where the error is happening.
So I was doing a lot of things wrong. But this is the only way it works, for me - please post your comments if you have better solution.
In the class, I have to do this:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET["element_name"])){
$this->_element_name = $_GET["element_name"];
echo json_encode($this->_element_name);
}
}
}
new CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper();
The class cannot be instantiated in the .phtml file with the resulting Ajax or the request is never sent back. Also notice the json_encode You cannot pass regular variables back to Ajax - when in a class (I think) - How ever when not in a class it seems to work - clarification is needed.
The Ajax then looks like this:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The Data that comes back is what I expect: "aisis_options[package_RelatedPosts]"
There ar a couple of issues with this answer - One I dont understand why I have to instantiate the class inside the file its written in, and two not sure why I have to encode the response in a class, but not when its just a "script kiddy" file.

JQuery AJAX Issue without error

So I am adding a list of stores to a web page via a jQuery AJAX request. This little utility is not dynamic, just database driven. I have decided to use jQuery/AJAX to transfer the data because when I try to embed PHP in our current PHP CMS, I get a bunch of conflicting errors.
The problem I am having is that I am getting a jQuery AJAX error when trying to make the request to the PHP script, and I am not sure why.
Here is my AJAX request
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(data) {
console.log(data.error);
}
});
});
The cryptic console error i am getting is this
function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
Here is my PHP code if it will be helpful:
//database connection
$return_arr = array();
$sql = mysql_query("SELECT * FROM where_to_buy");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$row_array['store_name'] = $row['store_name'];
$row_array['store_url'] = $row['store_url'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
I think the problem might be because I wrapping my JSON in an array?
EDIT:: JSON output from php script as requested
[{"store_name":"Example 1","store_url":"http:\/\/www.example1.com"},{"store_name":"Example 2","store_url":"http:\/\/www.example2.com"}]
Thanks for any help!
The reason you are getting that weird error message is that the error callback for the jQuery ajax function takes 3 arguments instead of 1, as described in the docs here: http://api.jquery.com/jQuery.ajax/
The first argument is a jQuery-special XMLHttpRequest object, which has a property called error that contains the function you are seeing logged to your console. The actual error that occurred during execution of your ajax call is the passed in to the error callback as the 3rd argument.
To see it, you should do something like:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
That will get you closer to the real problem.
UPDATE:
Please show the output from your php script. It may be that it is not returning valid json. As noted in the php docs ( http://php.net/manual/en/function.json-encode.php ), [json_encode] only works with UTF-8 encoded data.
You might also check in to json_last_error ( http://php.net/manual/en/function.json-last-error.php ) to see if the encoding failed for some reason.
UPDATE 3:
It seems like your problem may be the path to the php script.
try it with:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php", // <-- notice the leading slash!!!
//dataType: "json",
success:function(data){
//results(data);
console.log(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
or, putting it all back together if the above logs the correct json output to the console...
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});

php ajax success: function (msg) - get msg

I have some jquery/php code which uses ajax to call another page.
var pall_id = $(this).attr('id');
$.ajax({
type: "POST",
url: "do_history.php?pall_id="+pall_id,
success: function (msg) {
alert (msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('Error submitting request.');
}
});
However what do I do to get the value of msg? e.g. if do_history.php is simply:
<?php
$text="text";
return $text;
?>
would 'msg' not be "text" so when I alert(msg); I would get "text" popping up on my screen.
What do I need to do to return a string value? Any ideas?
Thanks,
Use echo $text; and in your $.ajax options add dataType: 'text'.
However, a better solution would be using dataType: 'json' and then echo json_encode($text); - in this case $text could also be an array/object/number and it would be the appropriate type in the JavaScript function
.
You have to echo or print the variable since jquery fetches the output of your script. A simple return doesn't produce any output.
<?php
$text="text";
echo $text;
?>
You need to check jQuery mannual for function $.post,the success param is a function and have several params .The most common used param is msg which is the output by the request url.
you need to know the param msg is the output of request url(do_history.php),if you use return in do_history.php,the content($text) will not output to browser so the msg param will contain nothing.but if you use echo ,print etc, the content($text) will output to browser so the msg param will contain the value!
You need to output text on php side (print 'text'; // echo 'text')

Categories