PHP json_encode data to jQuery for AJAX call - php

I am having a problem in using json_encode function.I am putting a simplified version of the problem here.
Here is the file containing php and jquery code.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
<?php
$test = "xxxxxxx";
?>
<p onclick="testAjax()">Click here</p>
<script>
var sendbody;
function testAjax(){
sendbody = "<?php echo json_encode($test); ?>";
$.ajax({
type: 'POST',
cache:false,
url: 'testAjaxCall.php',
data: {sendbody:sendbody},
success:function(data){
alert("1");
},
error:function(data){
alert("0");
}
});
}
</script>
And the ajax file simply contains
<?php
echo "testAjax";
?>
When I use json_encode function, the jquery code written after using the json_encode function stops working and the ajax function shows neither the success message nor the error message.
However if I write it as
sendbody = "<?php echo $test; ?>";
In this case the jquery code below this line works and shows success message.

When using json_encode, you don't have to quote the result, it's already quoted.
So change
sendbody = "<?php echo json_encode($test); ?>";
to
sendbody = <?php echo json_encode($test); ?>;
Otherwise you got:
// this cause syntax error
sendbody = ""xxxxxxx"";

First of all whenever you are expecting JSON to be returned to your AJAX call you have to tell it that by setting dataType: 'json', if not it tries to process it as text and obviously fails (your call is a success but the processing of the response isn't). The next best thing to do is use console.log(data) to get a better understanding of the response.

Related

Display HTML returned as JSON during AJAX call

My AJAX call previously returned an array of data as JSON using "echo jason_encode(array)" in my PHP code and I then looped through the result in my script and built the HTML using the returned data before displaying.
Now I changed the code to build the HTML in my PHP code and I want to return the HTML string to my script and display the HTML but I have no idea how to get it working and I have looked at over a dozen examples on this site and others but no luck.
PHP
$html = '<tr><td><div class="dummy">This is some text.</div></td></tr>';
$arr[] = array('html' => $html);
echo json_encode($arr);
Script
<script type="text/javascript">
$('.mashed_row a').click(function () {
var link_id = $(this).attr('link_id');
$.ajax({
type: 'POST',
url: 'explode',
data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', link_id},
dataType: 'json',
success : function(data) {
if(data)
{
var txt = data['html'];
$("#xarticletab").html("");
$("#xarticletab").append(txt).removeClass("hidden");
$("#comments").removeClass("hidden");
}
}
});
return false;
});
</script>
First of all, I think there is an error on your JS code: link_id alone.
on JS, you should define key: value. So, maybe 'link_id': link_id ?
Correct typo: {key1: 'value1', 'key2': 'value2'}
After, use console editor of your browser to know if there is any Javascript error.
Alternatively, you can play with javascript functions: console.log(data); or event alert(data)

how to send json object in ajax to a php page

I am trying to send a json object to a php page demo.php using an ajax request
<script type="text/javascript" charset="utf-8">
$(document).ready(function ()
{
var data =
{'name':'Sam','ID':'1345'};
var test = {}
test["data"] = JSON.stringify(data);
$("#btnsend").click(function()
{
$.ajax({
type:"POST",
url:"/demo.php",
dataType:'json',
data:test,
success: function(data)
{
console.log('success');
}
error: function()
{
console.log('failure');
}
});
});
});
</script>
This is what I tried in jQuery,but it is not rendered on my php page.In php I tried the following:
<html>
<?php
$json = json_decode(stripslashes($_POST['data']), true);
echo var_dump($json);
?>
<body>
Hello World !!!
</body>
</html>
But it is printing a failure in console. Please help me with this.
Edit: My initial answer was wrong, the reason you get to the error function, is that you have specified:
dataType:'json',
So jQuery expects the output of your php script to be valid json. It is not, you are returning text / html so that is why your success function is never reached.
The way you have setup your php script (outputting html), you probably should just remove:
dataType:'json',
and then you will get to your success function.
By the way, nothing is rendered on your page until you do something (show...) the data variable in your success function:
success: function(data) {
console.log('success');
$('#some_element').html(data); // to put the output in #some_element
}
And in your php script you should only send back / echo out what you want to display in your html element, so no html or body tags.

echo jQuery function in PHP as variable

Ok so I am trying to echo an function from jQuery inside of PHP.
I was searching a little bit, I did not found any exact answer but I found that I need to use ajax for it ?
I am not familiar with ajax so I have found this.
<?php
$status = "<script>
$.ajax({
url: '/',
data: {action: 'test'},
type: 'post',
success: function(output) {
notifyBox();
}
});
</script>";
?>
I also have this part somewhere on the page:
<?php if(isset($status)) { echo $status; } ?>
I am not quite sure if I need all of that to execute the function ?
But it works only if I put jQuery in head of the website.
I usually put all my scripts above </body> (at closing tag) and now it bothers me if I have to put all these scripts into head
Because of many pages I cannot separate all scripts now just cause of one page that bother me at the moment.
Can anyone please tell me, how do I call that function without getting console error of undefined '$' because jQuery is loaded at the end of the page.
Thank you in advance.
That should work so long as you make sure that you put your PHP if statement after the <script> tag that includes jQuery.
The problem is being caused by jQuery not being loaded when that variable is echoed. When Javascript sees a function call, it executes it right then and there. To prevent this, you will need to echo your variable after jQuery has been loaded.
Example:
<script type="text/javascript" src="path/to/jquery.js"></script>
<?php
echo $script;
?>
OR, you can put your AJAX call into a function that will be called later:
<?php
$script = '<script type="text/javascript">function myFunc() {
//Call AJAX here
}
</script>';
echo $script;
?>
Then later, you can call your function: myFunc();
Make sure jquery is loaded. This should work:
$status = "<script type='text/javascript'>
$(function(){
$.ajax({
url: '/',
data: {action: 'test'},
type: 'post',
success: function(output) {
notifyBox();
}
});
});
</script>";
$(document).ready() is also a jquery function, hence, try it with window.onload.

Getting a PHP variable in jQuery

So I have this:
<?php
echo '
<script>
$(function(){
$("a#yeah").click(function(){
$.ajax({
url: "ajax.php?action=yeah&id='.$id.'",
success: function(html){
$("a#yeah").html("your cool")
}
})
})
})</script>';
?>
basically I am using the PHP variable $id which can be find in the document, how could I get this same variable but without echoing the jQuery(so I could keep my editor syntax highlight in the JavaScript part)?
never echo any client side code - just type it as is.
PHP especially good in this http://www.php.net/manual/en/language.basic-syntax.phpmode.php
<script>
$(function(){
$("a#yeah").click(function(){
$.ajax({
url: "ajax.php?action=yeah&id=<?php echo $id?>",
success: function(html){
$("a#yeah").html("your cool")
}
})
})
})</script>
You can add the php inline like:
<script> var yourVariable = '<?php echo $phpVar; ?>'; </script>
Just echo around the variable, as that appears to be the only piece requiring processing:
...stuff...
url: "ajax.php?action=yeah&id=<?=$id?>",
...more stuff...
If your server doesn't have short_open_tag enabled, then <?php echo $id; ?>

send php variables to php file using jquery ajax?

i want to send a php variable $thread_id to php file using jquery ajax, so the php file can get all posts for $thread_id and echo it back to main file.
it doesnt work when i type:
$.get("ajaxcall_reply.php", thread_id: $thread_id, function(data) {
$("#threads").html(data);
});
how should i type?
Do you know what $thread_id is outputting? Try putting it into a variable of its own and looking at the output before putting it in the get function. It might have symbols or things that are messing up your javascript syntax. Do you have an example output? Additionally the get method returns the XMLHttpRequest object (data) so you might want to look into setting the type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text".
Try this:
$.get("ajaxcall_reply.php", {thread_id: $thread_id}, function(data) { $("#threads").html(data); });
<script>
$.get(url, { get_var: '<?php echo $phpvar ?>' }, function(data) { alert(data); });
</script>
at the URL:
<?php
echo $_GET['get_var'];
?>

Categories