Jquery ajax method undefined - ajax

So my problem is that data returned in success method is undefined...
Here is my jquery code:
$('document').ready(function(){
$('#save').click(function() {
var dataString = $("#stepform").serialize();
$.ajax({
url: "<?php echo base_url();?>create/save/<?php echo $row->id; ?>",
type: 'POST',
data: dataString,
success:function(response){
alert(response.status);
}
});//end ajax
return false;
});//end click
}); // end document ready
And php code:
$serverResponse["status"] = 'it worked';
echo json_encode($serverResponse);
And all i'm getting from response.status is 'undefined'... I just can't make it work! Any ideas what i'm doing wrong?
-------------EDIT-------------
Finally i have managed to find a solution to invalid json response. If you are using codeigniter you must write exit() after json_encode. Something like this:
exit(json_encode($yourarray));
If you just echo it then it gives a parse error.

jQuery may not be properly guessing that you are returning JSON. Set the dataType: "json" property on the $.ajax argument object, or add
header("Content-type: application/json");
to your PHP script before emission, or both.

Related

Accessing details of ajax response JSON

I have a really stupid beginner jquery question, even if I saw a lot of similar question here:
From PHP with ajax I send this:
public function to_json() {
return json_encode(array( 'test_id' => 'test_value' ));
}
In the jquery file's success part I put:
function(data) {
alert(data);
}
And it shows this in the alert window:
{"test_id":"test_value"}
Which is fine, I guess, but if I change the function to this:
function(data) {
alert(data.test_id);
}
I got:
undefined
What am I missing?
What am I missing?
To set the Content-Type HTTP response header to application/json in your PHP script:
header('Content-Type: application/json');
Or to set the dataType parameter to json on the client:
$.ajax({
url: '/foo.php',
dataType: 'json',
success: function(data) {
alert(data.test_id);
}
});
The first is preferred because this way your server side script properly indicates to the client the content type it is using. And jQuery is intelligent enough to use this reponse header and automatically parse the response from the server before feeding it to the success callback.
You are missing to use the function parseJSON
reference:http://api.jquery.com/jQuery.parseJSON/
That function converts the json string into a javascript object
You need to parse it like this:
function(data) {
var obj = $.parseJSON(data);
alert(obj.test_id);
}
None of the answers posted so far worked for me.
This is what I had to do to get it working:
$.ajax({
url: '/foo.php',
success: function(data) {
var json = data.responseJSON;
alert(json.test_id);
}
});

jQUery ajax call return an html error

Hi I am just learning to work with jquery and ajax.And an tryin gto berform a basic jquery call and retrieve an ok.But it seems I get back nothing.
This is my html:
Add to Cart
This is my jquery code:
$('.addToCart').on('click', function(){
var itemId = $(this).attr("id");
$.ajax({
url: 'cart.php',
type: 'POST',
data: itemId,
dataType:'html',
success: function(result){
alert(result + " ceva ");
},
error : function(data){
alert(data);
}
});
});
And this is my php code:
echo $_POST['cart'];
When I try to run this in the success alert I get back this:
How can make this ajax call to work properly?
You have to send your post data in key/value pairs, try
$.ajax({
url: 'cart.php',
type: 'POST',
data: {cart:itemId},//key -> cart, value -> itemId
dataType:'html',
success: function(result){
alert(result + " ceva ");
},
error : function(data){
alert(data);
}
});
Looks to me like you have an error in your PHP code. The returned HTML has some text that says "Notice: Undefined index" etc.
The AJAX Call succeeds - so you're seeing the alert message.

when ajax post success i want to refresh a particular <div> in page

i want to refresh a particular div on ajax success, im using the below code but the whole page getting refreshed.
<script type="text/javascript">
$('#post_submit').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
return false;
});
return false;
});
</script>
you have an extra return false which is inside the $.ajax block which most probably causes an error so your form isn't submitted via ajax. If you remove that, you shouldn't have any issues.
Use the submit event of the form and remove the return false from the ajax callback:
$('#myFormId').on('submit', function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
Remove the return false from inside your $.ajax function. Its a syntax error. The $.ajax function only expects a json object as an argument. "return false" cannot be part of a json object. You should keep the JavaScript console open during testing at all times - Press Ctrl-Shift-J in Chrome and select console to see any JS errors.
Also suggest you use <input type=button> instead of <input type=submit> or <button></button>

How use Facebook Javascript SDK response in Ajax request?

Supposing I have the following code which returns a Javascript object which I can read in Firebug's console:
FB.api('/me',function(apiresponse){
console.log(apiresponse);
});
How can I then use the data from apiresponse in an Ajax request on the same page?
Currently my Ajax request looks as follows:
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
I know very little about Javascript, but reading around the subject leads me to think I have to convert the Javascript object to a JSON string. Is that correct? Am I on the right track?
You could put your AJAX call inside the handler for the API call like below..
FB.api('/me', function(apiresponse){
console.log(apiresponse);
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
});
one possible way:
define a global variable in your javascript, e.g. var myVar1;
set apireponse to the global variable in your FB.api callback (i.e. where u call console.log)
reference the var myVar1 in your ajax fcn.

Get a php variable back after an AJAX action?

When I click onto a button of my page, I do the following action :
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(){
alert("Vote done");
}
Then, the page of the url receive my POST variable to treat the vote:
<?php
// I get the timestamp of the last user's vote
list($last_timestamp) = get_last_timestamp($_SESSION['id'], $_GET['id']);
// I get the server timestamp
$timestamp_click=time();
if($timestamp_click-$last_timestamp > $time_limit){
$authorization_vote=false;
}else{
$authorization_vote=true;
}
I would like to get back and send $autorisation_vote to AJAX or jQuery in order to alert the user if his vote has been done. I heard about callback but don't succeed to adapt to my case. How do that ?
there's a couple of ways you could do it.
The quick and dirty way is to just echo "true" or "false" in your PHP and that will be available in to the callback function if you declare it like this
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(data){
alert(data);
}
or you could set the http header to return a status code, which would allow you to declare two call backs in your ajax call on success or failure
The php would look like this
<?php
// I get the timestamp of the last user's vote
list($last_timestamp) = get_last_timestamp($_SESSION['id'], $_GET['id']);
// I get the server timestamp
$timestamp_click=time();
if($timestamp_click-$last_timestamp > $time_limit){
header("HTTP/1.0 423 Locked"); // The resource that is being accessed is locked
}else{
header("HTTP/1.0 204 No Content"); // Processed, but not returning content
}
and your ajax call could look like this
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
statusCode: {
204: function(){ alert("Vote cast"); },
423: function(){ alert("Vote not cast for whatever reason..."); }
}
Which is probably a bit of overkill, but it's good to know these things.
$.ajax({
type: "POST",
url: "index.php?module=pages&action=afficher_page&id=<?php echo $_GET['id']; ?>",
data:"vote="+vote,
success: function(data){
alert(data);
}
(note added data)
and in your php script add
echo "vote done and some data here";
because true is changed to 1 and false would be blank
So example:
if($timestamp_click-$last_timestamp > $time_limit){
$authorization_vote=false;
echo "voted";
}else{
$authorization_vote=true;
echo "vote failed";
}

Resources