I have a jQuery validation script that is working perfectly with the except of the event handler. I have simplified this post for troubleshooting purposes.
jQuery
submitHandler: function (form) {
$.ajax({
type: $(form).attr("method"),
url: $(form).attr("action"),
data: $(form).serialize(),
dataType : "json"
})
.done(function (data) {
if (data.resp > 0 ) {
alert(data.message);
}
});
return false; // required to block normal submit since you used ajax
},
// rest of the validation below, truncated for clarity
The submitHandler successfully posts to my PHP script that adds a user to a database and then echoes back a json_encode() result.
PHP
<?php
// All processing code above this line has been truncated for brevity
if($rows == "1"){
$resp = array("resp"=>1, "message"=>"Account created successfully. Waiting for user activation.");
}else{
$resp = array("resp"=>2, "message"=>"User account already exists.");
}
echo json_encode($resp);
?>
As you can see the idea is simple. Alert the user with the proper response message. When I run my script the user account is added successfully to the database but no alert is displayed to the user. The Console in Chrome shows no errors, what am I missing?
The data variable in the done() is a string. You have to transform it to an object like this
var response = $.parseJSON(data);
in order to access the attributes
I am sorry I missed dataType : "json" in your code in my previous answer.
Any way I tried your code and it is working. The alert shows the message. I think you have an error somewhere else. I think it has some thing to do with the array you are encoding to json(PHP part). The response you get is not complete. Try to debug your PHP and test the page separately from AJAX and see what is the result
After some tinkering I was able to get things working the way I wanted. Here's the updated code.
jQuery
.done(function (data) {
$("#user_add_dialog").dialog({
autoOpen: false,
modal: true,
close: function (event, ui) {
},
title: "Add User",
resizable: false,
width: 500,
height: "auto"
});
$("#user_add_dialog").html(data.message);
$("#user_add_dialog").dialog("open");
});
return false; // required to block normal submit since you used ajax
PHP
<?php
// All processing code above this line has been truncated for brevity
if($rows == "1"){
$resp = array("message"=>"Account created successfully. Waiting for user activation.");
}else{
$resp = array("message"=>"User account already exists.");
}
echo json_encode($resp);
?>
Related
I have an AJAX script that should insert data into a mysql database when users are logged in. However it is currently running the success function, even when 'success' => 'false' is returned in the console.
Her is my code
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"http://localhost/stumble/Site/add_to_fav",
dataType: "json",
data: form_data,
success: function (data){
alert("This Video Has Been Added To Your Favourites");
console.log(data.status);
},
error: function (data){
if(data.success == false){
alert("You Must Be Logged In to Do That");
console.log(data.status);
};
}
});
})
})
here is the php, bear in mind my project is in codeigniter.
public function add_to_fav(){
header('Content-Type: application/json');
$this->load->model('model_users');
$this->model_users->add_favs();
}
and this is the actual model for adding data to db
public function add_favs(){
if($this->session->userdata('username')){
$data = array(
'username' => $this->session->userdata('username'),
'title' => $this->input->post('heading'),
'embed' => $this->input->post('embed')
);
$query = $this->db->insert('fav_videos',$data);
echo json_encode(array('success'=>'true'));
} else {
echo json_encode(array('success'=>'false'));
}
}
Thank you for any suggestions!
You aren't returning an error.
You are returning a 200 OK with the data {"success": "false"}.
You can either handle that in your jQuery success function or send a different status code (it looks like a 403 error would fit here).
You have to remember error that occurs for asynchronous requests and errors that occur for PHP backend are different. Your error occurs at PHP-level, and PHP returns valid HTML as far as the javascript frontend is concerned. You need to check if the "success" variable in the returned JSON is true.
I have the following Jquery code that listens to a user typing in a captcha and sends an ajax request on each keyup to see if the correct code has been typed:
$('#joinCaptchaTextBox').keyup(function() {
$.get('scripts/ajax/script.php', {
'join_captcha': '1',
'captcha': $('#joinCaptchaTextBox').val()},
function(data) {
var obj = JSON.parse(data);
if(obj.ajaxResponse.status) {
$('#joinCaptchaNotAcceptable').hide();
$('#joinCaptchaAcceptable').show();
}else{
$('#joinCaptchaAcceptable').hide();
$('#joinCaptchaNotAcceptable').show();
}
});
});
The PHP script on the other end just checks the session and replies:
if($siteCaptcha == $_SESSION['secretword']) {
$this->captchaCompare = TRUE;
}else{
$this->captchaCompare = FALSE;
}
This works fine 95% of the time but I'm finding sometimes it reports the captcha typed is incorrect even though its correct. I think this could be because when typed fast many requests are sent to the server and the order or requests coming back isn't the order sent and therefore (as only one will be correct) a prior one is recieved last and incorrect is displayed.
Is there a better way to do this? Is there a way to ensure the last request sent is recieved last? Is there something I'm missing here. I can give more info.
thankyou
Add a timeout so as to not send a request on every keyup when the user types fast:
$('#joinCaptchaTextBox').on('keyup', function() {
clearTimeout( $(this).data('timer') );
$(this).data('timer',
setTimeout(function() {
var data = {
join_captcha: '1',
captcha : $('#joinCaptchaTextBox').val()
};
$.ajax({
url : 'scripts/ajax/script.php',
data: data,
dataType: 'json'
}).done(function(result) {
$('#joinCaptchaNotAcceptable').toggle(!result.ajaxResponse.status);
$('#joinCaptchaAcceptable').toggle(result.ajaxResponse.status);
});
},500)
);
});
This ajax code posts the variables and displays $('#data').html(data); which is been eco-ed in php.-which works
$.post('login.php',{username:username,password:password},
function(data)
{
$('#data').html(data);
if (data=='login'){
alert("sucess");
}
});
However the problem lies on the next line which does not work:
if (data == 'login') {
alert("sucess");
}
This code is supposed to show a dialog box if the data == login
I have looked through different tutorials and this code is supposed to be working but its doesn't for some reason.
Thanks!
You can simply put JSON data Type and use json array as response..
$.post('login.php',{username:username,password:password},
function(data)
{
if (data.status=='login'){
$('#data').html(data.status);
alert("sucess");
} else{
alert('not login');
}
}, 'json');
And in your PHP
<?php
#.. put any code before that response because after it you must put exit.
# No other data except it must be sent! Else you will break it..
echo json_encode(array('status'=>'login'));
exit();
data holds the return result of the response of login.php.
In your case it probaly returns html, like <h1> welcome user x</h1> (I don't know what your code returns so it is an exampe).
If that is the case, you code should check if that is valid. I suggest using JSON. Your login.php checks the login data. If the login attempt is valid you return login: true; And redirect the user.
When in valid just return the data errors and show them with jquery.
Use this code, if your response fails you will get proper alert.
var jqxhr = $.post("login.php", {username : username, password : password}, function(data) {
alert("success" + data);
console.log(data);
},'text')
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
else you will get alerted by "succes" and your data.
More information how to use this function you can find on http://api.jquery.com/jQuery.post/
To be sure it works. Put in login.php
<?php
echo 'ajax works';
exit;
?>
You use old functions that will be removed. Use PDO or other engine.
Your code is not secure. SQL Injections are possible.
Im currently new to PHP and JQuery after having using ASP.Net and C Sharp for the 2 years. I have this major problem in which i require some assistance in.
I have a HTML <input type="submit" id="btnWL" value="Add to Wishlist"> button. Basically when this button is pressed a table called 'wishlist' in the database is checked to see if the current product is already in a wishlist. If no the button will trigger a database save else it will return a JQuery alert pop up error message.
I having difficulty in passing 2 PHP variables: $_SESSION["username"] and $_GET["ProductId"] into this JQuery method:
<script type="text/javascript">
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php");
});
});
</script>
As you can see this JQuery method must pass those values to an external PHP File which checks for an already exsisting record in the 'wishist' table with those details.
<?php
$WishlistDAL = new WishlistDAL();
$result = $WishlistDAL->get_ProductInWishlistById($_GET["ProductId"]);
if (isset($_POST["isPostBack"])) {
if (isset($_SESSION["username"])) {
if (isset($_GET["btnWL"])) {
//Check if ProductId is in Cart
if (mssql_num_rows($result)>0)
{
//Return an error
//Sumhow this has to trigger an alert box in the above JQuery method
}
else
{
//Write in Wishlist Table
$WishlistDAL->insert_ProductInWishlist($_GET["ProductId"], $_SESSION["username"]);
}
}
}
else
{
//Return Error
}
}
?>
Another problem I have is then displaying an alert box using the same JQuery method for any errors that where generated in the php file.
Any Ideas how I can implement this logic? Thanks in advance.
Your "$.post()" call isn't passing any parameters, and has no callback for interpreting the results:
$.post('addToWishlist.php', { username: something, password: something }, function (response) {
});
The "something" and "something" would probably come from your input fields, so:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
});
Now the callback function would interpret the response from the server:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
if (response === "FAIL") {
alert("fail");
}
else {
// ... whatever ...
}
});
Exactly what that does depends on your server code; that "FAIL" response is something I just made up as an example of course.
jQuery accepts an callback:
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php", {'isPostBack':1}, function(res){
if (res.match(/err/i)){
alert(res);
}
});
});
});
Then, in the php, just (echo('Error adding record')) for this jquery to see there's an error string in the response and pop up the error message.
Other methods would be to use json, or http status codes and $.ajaxError(function(){ alert('error adding'); });.
from what i can tell so far is you'll only need to pass in the product id in and you can do this by appending your $.post call with the value; this will pass to your php script as a query string variable. i'm not sure which php script you posted, but if you're sending your data with jquery, it's using post and not get, so you may need to make an adjustment there and the session data should be available regardless, since it's the same session.
again this is without seeing all the code and since some of it isn't labeled, it's hard to determine. another thing, i like to use $.ajax for most actions like this, you have a lot more room to define and structure, as well as create one generic ajax function to call the methods and post data, as well as make a response callback. here's the documentation for you to look into $.ajax
i hope this helps.
I want to be able to display a message if a user is not logged in if they try rating a user by clicking a rating. Is there a way to add it to my JQuery code below or can I pass it to my PHP script?
I'm using PHP
Here is the JQuery code.
$('#rate li a').click(function(){
$.ajax({
type: "GET",
url: "http://localhost/update.php",
data: "rating="+$(this).text()+"&do=rate",
cache: false,
async: false,
success: function(result) {
// remove #ratelinks element to prevent another rate
$("#rate").remove();
// get rating after click
getRating();
getRatingAvg();
getRatingText2();
getRatingText();
},
error: function(result) {
alert("some error occured, please try again later");
}
});
just check it if one is login in your update.php script. If not login, echo something like "error".
then in your success handler,
success: function(result) {
if (!$.trim(result)==='error') {
// remove #ratelinks element to prevent another rate
$("#rate").remove();
// get rating after click
getRating();
getRatingAvg();
getRatingText2();
getRatingText();
} else {
// not login, do something...
alert('login first please...');
}
},
Send something back to jQuery as the result and check it, before you perform your other steps.
jQuery alone cannot test reliably if the user is logged in, but your request to PHP could send an answer if theuser was logged in or not. This answer can be checked and then display an error (or not).
Use your update.php script to send back a codified response that includes an acknowledgement of whether the user is logged in; I am assuming the script echoes some value which is then received as the result variable in your jquery snippet.
if(result.loggedin == "1"){ //Assuming your output is a JSON object
}else{
}
In Wordpress you can easily check with below code:
if(jQuery('body').hasClass('logged-in')) {
// add your jquery code
}