jQuery $.post Callback Function (data) is Undefined - php

I submit a form using jQuery to a php file on my server.
Everything works... (the php file gets the right post variables, makes a database entry etc.)
But on the response, sometimes 'data' goes wacky.
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
if ( data.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
}, "json");
});
php script returns (on success)
$response['status'] = 1;
$response['message'] = 'worked';
echo json_encode($response);
exit();
I'm getting a whole lot of crap, and not enough awesome sauce.
Does anyone have an idea why sometimes 'data.status' is undefined, and sometimes it isn't?

Try it like this>
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
var obj = jQuery.parseJSON(data);
if ( obj.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
});
});

How does exit() behave with regards to output buffering? Does it flush the output buffer?

try this one:
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize())
.success(function(){
alert('awesome sauce');
}).error(function(){
alert('crap');
});
});

Related

if else condition in jquery ajax response

I have one Ajax function which is running properly.but i want when my Ajax response is
<h3>No Couriers found near by you.please select another location</h3>
i want to display some error message else i want to display another map div in else condition.
but every time when i hit Ajax only else condition is working..but when i alert response and see the output it shows this message when
<h3>No Couriers found near by you.please select another location</h3>
but still it not comes in if condition..can anyone help me to do this....
<script>
$('#weight0,#weight1,#weight2,#weight3').click(function() {
var checked = $(this).is(':checked');
if($(this).is(":checked")) {
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Orders","action" => "searchCourier")); ?>',
data: {
frmlat: $("#PoolLatitude").val(),
frmlong: $("#PoolLongitude").val(),
mylocation: $("#PoolLocation").val()
},
dataType: "html",
success: function(response) {
alert(response);
if(response =="<h3>No Couriers found near by you.please select another location</h3>"){
alert(thanks);
} else {
$('#map_canvas').css('display', 'none');//used to hide map after ajax success response.
$("#load_map").html(response);
}
},
complete: function() {
$('.spinicon').hide();
}
});
} else {
$("#secretcode").val("");
}
});
</script>
In your php script, return a boolean flag instead of a string :
<?php
if (some_condition) {
$return = true;
} else {
$return = false;
}
die(json_encode(array('return' => $return)));
And in the ajax success :
...
dataType: 'json',
success: function(data) {
if (data.return) {
alert("return is true");
} else {
alert("return is false");
}
},
...
Hope it helps.
PS : use Json Encode to parse the response and access values easily.
First of all, i suggest you to use status for ajax response something like:
1 for success
0 for failure
Than, as per your statement, your are getting the correct response in:
alert(response);
Than, you must need to check either response having <h3></h3> tags or not.
In your code, the main issue is that, you are using string without quotes in alert alert(thanks); this will return undefined thanks in console and treated as a variable.
This should be alert("thanks");
One more suggestion, it's always better to check browser console when you are not getting success in Ajax or any other script, this will help you to find the errors.

Call PHP file in JavaScript Function for Updating MYSQL Table?

I want to integrate a Java script Slot Machine game into my script.
You can see demo here ; http://odhyan.com/slot/
And also git hub is here ; https://github.com/odhyan/slot you can see all JS files here.
I created a Point Coloumn in User Table that people can play the game with this Point.
I think this JS Function in slot.js checking if user won the game or lose.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
} else {
res = "You Lose";
}
$('#result').html(res);
}
So i want to add +100 Point if user won the bet.
I made this PHP codes Uptading points For userid "1".
<?php
mysql_connect ("localhost","username","password") or die (mysql_error());
mysql_select_db('slot_machine');
$pointsql = mysql_query("SELECT * FROM user WHERE userid = 1");
while ($row = mysql_fetch_array($pointsql))
{
$row['point'] +=100;
$addpoint = mysql_query("UPDATE user SET point = '{$row['point']}' WHERE userid = 1");
}
?>
So how can i call or excute this PHP Codes in JavaScript function if user Win?
You'll need to trigger a network request from your javascript code to execute your php script server side. Using jQuery's $.ajax() function is an extremely common way to do this abstracting away various browser differences.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
} else {
res = "You Lose";
}
$('#result').html(res);
}
You can use jQuery's $.post() function to trigger an asynchronous request to your PHP file.
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
res = "You Win!";
// Here's the line you need.
$.post('score.php', {userid: 1}, function(data) {
alert("Score saved.");
});
} else {
res = "You Lose";
}
$('#result').html(res);
}
This will send POST data to score.php, or whichever file you want to send the data to. The PHP file can then access the userid sent to it by checking the value of $_POST['userid'].
As mentioned in the documentation, $.post() is a shortcut for jQuery's $.ajax() function that is simplified and has some of its options pre-set. The third argument in $.post() is a callback function, and the variable data will contain whatever is echoed out or printed from score.php by the time it's done executing. So, you could use alert(data) instead, to see what score.php printed out. This is useful for troubleshooting and error handling.
try this
$(document).ready(function(){
setInterval(function() {
$.get("databaseUpdated.php");//or what ever your php file name is with corrct path
return false;
}, 1000);
});
hope this will help you use it in your function
function printResult() {
var res;
if(win[a.pos] === win[b.pos] && win[a.pos] === win[c.pos]) {
// if
setInterval(function() {
$.get("databaseUpdated.php");//or what ever your php file name is with corrct path
return false;
}, 1000);
} else {
res = "You Lose";
}
$('#result').html(res);
}

How To Return Data from PHP to Use in jQuery(ajax)?

I have to process a Simple log-in File. In Many Web Tutorials I have read that for any Ajax requests in jquery the callback function is function(data) and the data is returned by the server side script.
Well, my server side script is PHP. I wish to know how can I return data from PHP which will be stored in jquery's data and I can use conditional loops to process them.
Here is my jquery Code:
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, processLI );
function processLI(data) {
if (data == 'success'){
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
}
I am using simple return statement in my php file, which does not seem to work at all. here is the login.php file. I just posted the part necessary here.
$statement = $connection->prepare("SELECT * FROM users WHERE username = '$username'");
$statement->execute(array());
$result = $statement->fetch(PDO::FETCH_ASSOC);
if ($result['password'] == $safepass) {
setcookie("Login", true);
echo 'success';
}
else
echo "Failure";
Try doing it like this, by placing the function as the parameter, and not by calling the function.
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, function(data){
if (data == 'success') {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
});
Use the echo statement to output data, if the login is successful echo 'success';
This is an answer about how to debug AJAX requests. First, use Chrome (or Safari, or Firefox with Firebug plugin installed), then open up the developer tools from the settings menu. In the network panel, you can see the request/response. It may not be a direct answer, but please - try to use the Chrome developer tools with the "Net Panel" to see request/response/cookies/headers.
This will save you the trouble of having to guess, it will show you the response verbatim. Then you can solve it next time ;) and the time after
Have you been able to see the request/response? If not, I suggest a simple
alert(JSON.stringify(data))
...from your callback function if you have issues using the Chrome debugger.
Try giving the dataType for post as 'html'
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.ajax({
url : 'login.php?'+querystring,
cache : false,
success : function(data) {
if(data == "success") {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
} else if(data == "failure") {
alert("Login Failed");
}
};
});
});

jquery wont send with post method

nothing is being sent with $.post
function clicked()
{
var $contact_title=$("#contact_title");
var $contact_summary=$("#bbcode");
alert($contact_title.val());// How do I get the contents of the title
alert($contact_summary.val());// How do I get the contents of the textarea
$.post('jquery_send_admin.php',{ title:$contact_title, content:$contact_summary }, function(data){ alert("Message was sent") }, 'html');
}
I get exceptions in my console error..like the following:
UPDATE:
no data is inserted on the next page..why?!?
if( isset($_POST["title"]) && isset($_POST["content"]) )
{
$title=mysql_escape_string($_POST["title"]);
$content=mysql_escape_string($_POST["content"]);
$result=mysql_query("INSERT INTO users (query_title,query_message) VALUES(''$title', '$content')") or die(mysql_error());
}
The following error happens:
Error: uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js :: <TOP_LEVEL> :: line 16" data: no]
UPDATE:
Thats what I request from the page, which is triggered by jquery:
<?php
echo 'outside';
if( isset($_POST["title"]) && isset($_POST["content"]) )
{
echo 'inside';
$title=mysql_escape_string($_POST["title"]);
$content=mysql_escape_string($_POST["content"]);
$result=mysql_query("INSERT INTO users (query_title,query_message) VALUES(''$title', '$content')") or die(mysql_error());
}
?>
You need to extract the values using the .val() method:
var $contact_title = $('#contact_title').val();
var $contact_summary = $('#bbcode').val();
var dataToPost = { title: $contact_title, content: $contact_summary };
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert('Message was sent');
}, 'html');
var $contact_title=$("#contact_title").text();
var $contact_summary=$("#bbcode").text();
try to get the value/text instead of just the control.
var $contact_title=$("#contact_title").text();
or
var $contact_title=$("#contact_title").val();
Edit:
Not sure how it works in PHP but I use it with vb.net and there I need to give my controller name(aka file) and function so it becomes
$.post('myFile/myJSONFunction', {all-your-parameters});
So maybe thats why it wont post your data.
Something else you might want to look at is that your php might return different data than you are actually expecting him to return.
function clicked() {
var $contact_title = $("#contact_title");
var $contact_summary = $("#bbcode");
alert($contact_title.val()); // with the val
alert($contact_summary.val()); // with the val
$.post('jquery_send_admin.php', { title: $contact_title.val(), content: $contact_summary.val() }, function (data) { alert("Message was sent") }, 'html');
}
Instead of this posted by #Darin
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert('Message was sent');
}, 'html');
use this
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert(data);
});
That will show the result of the echo statements in the alert box which could possibly help you debug the issue.
Oh my. jQuery bugs, PHP debugging bugs. I'll probably get down-rates for this answer... but sometimes, it helps to simply read the manuals if you're that lost that people have to help you cross the street: http://api.jquery.com/ & http://php.net/manual/

livevalidation.js custom username check function

I am sure this is probably something simple that i am not doing. Running livevalidation.js jquery plugin (livevalidation.com). It provides for custom function callbacks. I am trying to check for username availability. The server side is working fine and I am getting the proper responses back in my data var...
Here is my JS:
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
if (data.status === 'notavailable')
{
Validation.fail('oops, not available.');
}
});
};
I am calling it using:
var username = new LiveValidation('username', { validMessage: curr_username + "is available!" });
username.add( Validate.Presence, { failureMessage: "Choose a username" });
username.add( Validate.Username, { failureMessage: "Username is not available." } );
The problem I am getting is:
Uncaught ReferenceError: Validation is not defined
If I put the Validation.fail() outside of my .post() function it works fine. So am pretty sure it is because it's not able to be referenced inside the .post() function.
I've tried using a callback function
if (data.status === 'notavailable')
{
status_not_available();
}
I get the same error.
I realize this is something probably extremely simple, but any help would be appreciated. Thank you in advance.
i am having the same issue.
Ive found the following, http://forum.jquery.com/topic/ajax-return-value-on-success-or-error-with-livevalidation but have not been able to get it working.
BUT YES! At this very moment i made som (crappy) javascript addon that made it behave, i think :)
This is what i use.
function check_avail(name, id, postUrl)
{
var dataVal = name+'='+$(id).val();
var isaccepted = ''
$(id).next('div').remove();
$(id).after("Undersøger om "+name+" er ledigt");
$.ajax({
url: postUrl,
cache: false,
type: 'post',
dataType: 'json',
data: dataVal,
async: false,
success: function(data) {
if( data.success == 'true' )
{
$('#'+name+'-availability').remove();
//return false;
isaccepted = false;
}
if( data.success == 'false' )
{
$('#'+name+'-availability').remove();
// name.destroy();
isaccepted = true;
}
}
});
if (isaccepted == false) {
return false;
} else{
return true
};
}
And
f1.add( Validate.Custom, { against: function() {
return check_avail( 'brugernavn', '#ft001', 'usernamecheck.asp' );
}, failureMessage: 'Brugernavnet er optaget' } );
Hope it helps you :)
The json query you can read about on the link in the begining :)
(I am not at all skilled at javascript, and the "isaccepted" solution could problalby be made a lot better)
try to change it from Validation.fail to Validate.fail
try wrapping it in another function and try putting your validateStatus(status) function both inside and outside your Validate.Username function. example below is inside
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
validateStatus(data.status);
});
function validateStatus(status){
if (status === 'notavailable'){
Validate.fail("not available");
}
}
};

Categories