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.
Related
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);
?>
I am very new to PHP and Javascript.
Now I am running a PHP Script by using but it redirect to another page.
the code is
<a name='update_status' target='_top'
href='updateRCstatus.php?rxdtime=".$time."&txid=".$txid."&balance=".$balance."&ref=".$ref."'>Update</a>
How do I execute this code without redirecting to another page and get a popup of success and fail alert message.
My script code is -
<?PHP
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
-------- SQL Query --------
?>
Thanks in advance.
You will need to use AJAX to do this. Here is a simple example:
HTML
Just a simple link, like you have in the question. However I'm going to modify the structure a bit to keep it a bit cleaner:
<a id='update_status' href='updateRCstatus.php' data-rxdtime='$time' data-txid='$txid' data-balance='$balance' data-ref='$ref'>Update</a>
I'm assuming here that this code is a double-quoted string with interpolated variables.
JavaScript
Since you tagged jQuery... I'll use jQuery :)
The browser will listen for a click event on the link and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.
As you can see, I'm using .data() to get the GET parameters.
$(document).ready(function() {
$('#update_status').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
rxdtime: $(this).data('rxdtime'),
txid: $(this).data('txid'),
balance: $(this).data('balance'),
ref: $(this).data('ref')
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});
PHP
Looks like you know what you're doing here. The important thing is to output the appropriate data type.
<?php
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
header('Content-Type: text/plain; charset=utf-8');
// -------- SQL Query -------
// your logic here will vary
try {
// ...
echo 'success';
} catch(PDOException $e) {
echo $e->getMessage();
}
Instead of <a href>, use ajax to pass the values to your php and get the result back-
$.post('updateRCstatus/test.html', { 'rxdtime': <?php ecdho $time ?>, OTHER_PARAMS },
function(data) {
alert(data);
});
I've been on a problem for hours without finding any issue...
I have a registration form for users to create accounts. When the submit button is pressed a validateForm function is called.
In this function I do some javascript tests that work, but then I need to verify that the username is available. For this I created an external PHP file and call it using $.ajax.
Here is part of the code :
function validateRegistration(){
// Some tests....
// Check if username is already used
// Call external php file to get information about the username
$.ajax({
url: 'AjaxFunctions/getUsernameAjax.php',
data: "username=" + $("#username").val(),
success: function(data){
// Username already in use
if(data == "ko"){
// Stop validateForm()
}
// Username not used yet
else{
// Continue tests
}
}
});
// Other tests
}
My question is how can I make validateForm() return false from inside the $.ajax ?
Could I for instance declare a js variable before the Ajax part and set it with Ajax ?
I guess the answer is obvious but I'm absolutely new to Ajax and I can't get it...
Thanks a lot for your help!
To achieve this you can either do a synchronous ajax call like described in this answer, but that's something which is incredibly dangerous for the performance of your website.
Alternatively - and this is the right way - you should have an external variable whether the username is available, as soon as the user inputs something you do the request and if it's valid you change the variable otherwise you show an warning message. Next in your validateRegistration() function you only check the external variable (+ possible some form of callback, depending on where you call it from). The advantage being that the user can still continue doing things (like filling out the rest of the form) whilst the request is pending.
You could make a synchronous ajax call, instead of an asynchronous, as you're doing now. This means that the Ajax call will complete before the next lines of code are executed.
To do so in jQuery, just add async: false to your request object:
var someVariable;
$.ajax({
url: 'AjaxFunctions/getUsernameAjax.php',
data: "username=" + $("#username").val(),
success: function(data){
// Username already in use
someVariable = "something";
if(data == "ko"){
// Stop validateForm()
}
// Username not used yet
else{
// Continue tests
}
},
async: false
});
alert(someVariable); // should alert 'something', as long as the ajax request was successful
In the php, if you print out JSON like:
echo json_encode(array("ko"=>"good"));
shows up as:
{
"ko":"good"
}
then in the function it would be
if(data.ko == "good"){
//do stuff
}
This is how I normally do it. You can get the variable by using the name you used in the JSON so you can have other things if you need.
If the goal is to check a username availability, how about checking it as or just after the username is typed in. For example you could either bind it to the keyUp event for keystrokes or the blur event for when you leave the text box.
This would mean that by the time the user gets to the submit button, that part of the form would already be validated.
The traditional solution here is to pass a callback function to validateRegistration which expects a boolean value. Have the Ajax function call the callback function when it completes.
The onsubmit handler expects a return value immeidately, so performing an asynchronous test within your submit event handler is a fairly unituitive way to do things. You should instead perform the test as soon as possible (e.g. as soon as the user enters a username) and then store the result of username validation in a global variable, which is later checked at submit time.
// global variable indicating that all is clear for submission
shouldSubmit = false;
// run this when the user enters an name, e.g. onkeyup or onchange on the username field
function validateRegistration(callback) {
shouldSubmit = false;
// number of ajax calls should be minimized
// so do all other checks first
if(username.length < 3) {
callback(false);
} else if(username.indexOf("spam") != -1) {
callback(false)
} else {
$.ajax({
....
success: function() {
if(data == "ko") {
callback(false);
} else {
callback(true);
}
}
});
}
}
Now call validateRegistration with a function argument:
validateRegistration(function(result) {
alert("username valid? " + result);
if(result) {
$("#username").addClass("valid-checkmark");
} else {
$("#username").addClass("invalid-xmark");
}
shouldSubmit = result;
});
Now use the global variable shouldSubmit in your form's submit event handler to optionally block form submission.
I have a php script that takes some user form input and packs some files into a zip based on that input. The problem is that sometimes the server errors, so all the form data is lost. I was told I could use ajax instead so that the user never even has to change the page. I've never used ajax, and looking at http://api.jquery.com/jQuery.ajax/ without any experience in ajax is quite difficult.
The page says that you can accept returns from an ajax call. How do you set up returns in the PHP file for an ajax call? If the server errors with the ajax call, how will I know?
edit: Also, is there a way to send an ajax request with javascript and jquery as if it were a submitted form?
How do you set up returns in the PHP file
just echo it in ajax page that will return as response
Simple Tutorial
client.php
$.post('server.php',({parm:"1"}) function(data) {
$('.result').html(data);
});
server.php
<?php
echo $_POST['parm'];
?>
result will be 1
edit on OP comments
Is there a way to use ajax as if you were submitting a form
Yes, there is
You can use plugins like jQuery form
Using submit
If you using jquery validation plugin, you can use submit handler option
using sumit
$('#form').submit(function() {
//your ajax call
return false;
});
every ajax function has a function param to deal with server returns.and most of them has the param msg,that is the message from server.
server pages for example php pages you can just use echo something to return the infomation to the ajax funciton . below is an example
$.ajax({
url:yoururl,
type:post,
data:yourdata,
success:function(msg){
//here is the function dealing with infomation form server.
}
});
The easiest way to get information from PHP to JavaScript via AJAX is to encode any PHP data as JSON using json_encode().
Here's a brief example, assuming your server errors are catchable
<?php
try {
// process $_POST data
// zip files, etc
echo json_encode(array('status' => true));
} catch (Exception $e) {
$data = array(
'status' => false,
'message' => $e->getMessage()
);
echo json_encode($data);
}
Then, your jQuery code might look something like this
$('form').submit(function() {
var data = $(this).serialize();
$.ajax(this.action, {
data: data,
type: 'POST',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
if (!data.status) {
alert(data.message);
return;
}
// otherwise, everything worked ok
},
error: error(jqXHR, textStatus, errorThrown) {
// handle HTTP errors here
}
});
return false;
});
I find this tutorial in 9lessons.com : http://www.9lessons.info/2011/01/gravity-registration-form-with-jquery.html
It's about a registration form with validation.
I want to send data to DB.
// Submit button action
$('#submit').click(function()
{
var email=$("#email").val();
var username=$("#username").val();
var password=$("#password").val();
if(ck_email.test(email) && ck_username.test(username) && ck_password.test(password) )
{
$("#form").show().html("<h1>Thank you!</h1>");
///// if OK
///// Show thanks
//// else
//// Error, try again
}
return false;
});
How can I do ?? I searched in internet in jQuery tutorial and I find much codes ...
This tutorial will walk you the entire process:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
It implements jQuery.post and calls a PHP script that will allow you to process the data.
You will need to use Ajax to submit the data to a backend script (such as PHP) to do the actual database interaction. I'd recommend using POST:
http://api.jquery.com/jQuery.post/
you can use jquery post method
$.post("test.php", $("#testform").serialize());
or for more detail visit this link
jquery form post method
Finally I inserted data form to database... I have a problem.. I forgot to verify if email is available or not !
I added this lines from an other tutorial in email verification to test if email exist in DB or not.
First I send email to check_availability.php
if mail exist an error message appear else, the password fiel must appear ...
Like you see in picture, I verify the existence of an email adress and availibality and unavailability message appear but not correctly ...
$('#email').keyup(function()
{
var email=$(this).val();
if (!ck_email.test(email))
{
$(this).next().show().html("Enter valid email");
}
else
{
//$(this).next().hide();
//$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
$.ajax
({
type: "POST",
url: "user_availability.php",
data: "email="+ email,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
if(msg == 'OK')
{
/*$("#email").removeClass('object_error'); // if necessary
$("#email").addClass("object_ok");
$(this).html(' <img align="absmiddle" src="accepted.png" /> ');*/
//////////////////
$(this).next().hide();
$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
//////////////
}
else
{
$("#email").removeClass('object_ok'); // if necessary
$("#email").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
});
The tow first comment lines are the default ines used to show the next field //$("li").next("li.password").slid ...
Like you see I add them in Ok test section ....