jQuery.AJAX post() - a few questions and issues - php

I'm making a site where a user spams a button and increases their score in doing so.
I don't want the page to refresh when the button is clicked, so I wanna use AJAX to send the data to the server. Here's what I have so far:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#update").click(function() {
$.ajax({
type: "POST",
url: "update.php",
data: "increase",
dataType: "Boolean",
success: function(update) {}
});
});
});
</script>
<button id="update" type="button">Button</button>
<div id="counter"></div>
It's not much at all, I know, but I'm very new to this stuff. The main problem I'm having is with the syntax that you're supposed to use. I want the server to return a Boolean variable if the request is successful, so would I have Boolean in the 'Data Type' in inverted commas, apostrophes or what?
Also, I'm struggling with grasping how the ajax script knows whether it's successful. Is there gonna be something in the 'update.php' script that will return a 'TRUE' or 'FALSE' value?
Finally, the data that's gonna be sent to the php file is supposed to tell the php to update the mysql table with the new score. How should I go about telling the php to update the mysql if it receives the data that the ajax is sending?
Thanks a lot

Something along the lines of this should work:
$.ajax({
type: "POST",
url: "update.php",
data: {"action":"increase"},
success: function(response) {
if(response.error) {
alert(response.error);
return;
}
if(response === 'true') {
//do something
} else {
//do something else
}
}
)};
On the PHP end, your code would likely look like this:
<?php
if(!isset($_POST['action'])) {
echo '{"error": "You must provide a action"}';
exit;
}
$action = $_POST['action'];
if(!in_array($action, array('increase', 'decrease')) die('{"error":"invalid parameters"}');
$action = ($action == 'increase') ? ' + 1' : ' - 1';
//$db is assumed to be a live mysqli object from here on out...
$result = $db->query("UPDATE someTable SET fieldname = fieldname {$action} LIMIT 1;");
echo ($result->affected_rows > 0) ? 'true' : 'false';
?>

The dataType attribute is one of json, xml, html, jsonp, text, or script. Boolean isn't one of the expected types. In this case, you don't want to pay attention to those expected types. jQuery makes an intelligent guess about the type if you pass nothing in based on the MIME type returned by your server.
What you want to do is create a function that will be called by the success callback.
$.ajax({
type: "POST",
url: "http://www.server/path/to/update.php",
data: "increase",
success: function(data, status, xhr) {
functionToProcess(new Boolean(data));
}
)};
The function that is given as an argument to success (an anonymous function, in this case) is called when the Ajax call is complete with a 200 value. Because Ajax is asynchronous (that's what the A is), returning things will do you no good. What you want to do is call another function that will process your boolean value. This I've called functionToProcess in my sample code. For more information, check out the jQuery docs on .ajax().
You can learn about what String values in Javascript produce true versus false boolean values here.

This syntax should work
$(document).ready(function(){
$("#update").click(function(){
$.ajax({type: "POST",
url: "update.php",
data: "increase",
success: function(update) {
if(update)
$("#anyelement").html("Thanks");
else
$("#anyelement").html("Try again !");
}
});
});
});
You can ignore the datatype, because you can parse from any direction
how the ajax script knows whether it's successful
If I understand your point, as far as there is a return to the ajax function the process is success, it is upto you to parse the return and implement the logic.
from you php you do like this:
if(you logic is correct){
//update you database and ... other login goes here
return true;
}else{
return false;
}

Related

The best way passing value from jQuery to PHP

I wonder how I can pass value from Jquery to PHP. I found similar codes but not even one of them work.
Everytime alert shows value of variable but when I open site there is not any. Var_dump shows that $_POST is null. I am ran out of ideas do you have any?
jQuery code:
$("#password-button").click(function(){
var password="";
var numbers =[0,0,0,0,0,0];
for(var i=0;i<=5;i++){
numbers[i] = Math.floor((Math.random() * 25) + 65);
password += String.fromCharCode(numbers[i]);
}
$(".LoginError").text("Nowe haslo: " + password);
$.ajax({
type: 'post',
url: 'dzialaj.php',
data: {'password': password},
cache:false,
success: function(data)
{
alert(data);
console.log(result)
console.log(result.status);
}
});
});
PHP:
if(isset($_POST['password'])){
$temp = $_POST['password'];
echo $temp;
}
Since it looks like you are new on ajax, let's try something more simple ok? Check this js:
<script>
var string = "my string"; // What i want to pass to php
$.ajax({
type: 'post', // the method (could be GET btw)
url: 'output.php', // The file where my php code is
data: {
'test': string // all variables i want to pass. In this case, only one.
},
success: function(data) { // in case of success get the output, i named data
alert(data); // do something with the output, like an alert
}
});
</script>
Now my output.php
<?php
if(isset($_POST['test'])) { //if i have this post
echo $_POST['test']; // print it
}
So basically i have a js variable and used in my php code. If i need a response i could get it from php and return it to js like the variable data does.
Everything working so far? Great. Now replace the js mentioned above with your current code. Before run the ajax just do an console.log or alert to check if you variable password is what you expect. If it's not, you need to check what's wrong with your js or html code.
Here is a example what i think you are trying to achieve (not sure if i understand correctly)
EDIT
<script>
var hash = "my hash";
$.ajax({
type: 'post',
url: 'output.php',
data: {
'hash': hash },
success: function(data) {
if (data == 'ok') {
alert('All good. Everything saved!');
} else {
alert('something went wrong...');
}
}
});
</script>
Now my output.php
<?php
if(isset($_POST['hash'])) {
//run sql query saving what you need in your db and check if the insert/update was successful;
// im naming my verification $result (a boolean)
if ($result) echo 'ok';
else echo 'error';
}
Since the page won't redirect to the php, you need a response in you ajax to know what was the result of you php code (if was successful or not).
Here is the others answers i mentioned in the coments:
How to redirect through 'POST' method using Javascript?
Send POST data on redirect with Javascript/jQuery?
jQuery - Redirect with post data
Javascript - redirect to a page with POST data

Is this true way to send request

i wonder if this is true and safe way to send request via ajax json type to php file or not ?!
note : it return success result ..
but my question if to keep them like this or change it to another safe method ?!
Html Code
<span class="clickable" data-bind={"name":"master","tag":"1"}>click</span>
Javascript Code :
$(".clickable").livequery('click touchstart', function (e)
{
var bind = $(this).data("bind");
$.ajax({
type: "POST",
url: "page.php",
data: bind,
dataType: 'json',
success: function (response)
{
alert(response)
}
});
e.stopImmediatePropagation();
});
PHP File :
$name= mysql_real_escape_string(trim(htmlentities(strip_tags($_POST['name']))));
if(!isset($name) || $name == '' || $name != 'master') {
echo 'Error: Invalid Action';
exit;
}else{
// Do Something
}
Basicly whenever you use ajax to post to a page, anyone with a developer console in their browser is able to see that request. And alter it as they like. Just like they can alter the data-bind attribute by using something like firebug.
You should implement checks on the POST variables in your page.php to make sure the input is not something you want inserted into your PHP code.

Ajax call too slow ? Javascript and PHP

I am setting up a registration form.
This form has 7 fields that are being tested for validation.
2 of them have a special validation; I have an Ajax call to a PHP class where I send an email_string to this class, testing, if such an email already exists in my database (evading duplicates).
params = {};
params['source'] = 'checkEMail';
params['email'] = email
$.ajax({
type: 'POST',
url : 'some_class.php',
data : params,
success: function(msg)
{
if(msg > 0) /* email exists */
is_error = true;
}
});
And in my PHP Class I got something like this:
$final = mysql_fetch_assoc(foo);
echo ($final) ? 1 : 0;
I was testing the data and in fact - I get '1' if the email exists and '0' if it does not.
Funny thing is, that this snippet works fine AS LONG AS there are other errors in this form - like an empty username.
The "is_error" is a boolean that is set to false at the beginning of the script and if one validation fails, it gets true.
Then, finally, I got this:
if(is_error)
{
error.show();
error.empty().append('some html foo');
}
else
{
$('form').submit();
error.empty().hide();
}
So how can it be that I the form will be send although is_error is set to true?
Only reason I could think of is that the form is being send before the "is_error" is being testet - but the send of the form is at the very bottom of the script.
Oh and I am calling it this way:
<script type="text/javascript">
$("#reg_submit").click(function(event) {
event.preventDefault();
checkReg();
});
</script>
instead of having the if(is_error){ part at the end of the script, I would suggest you to do it in the ajax request completion to avoid race conditions:
$.ajax({
type: 'POST',
url: 'some_class.php',
data: params,
success: function(msg) {
if (msg > 0) /* email exists */
is_error = true;
},
complete: function() {
if (is_error) {
error.show();
error.empty().append('some html foo');
} else {
$('form').submit();
error.empty().hide();
}
}
});
Maybe it is caused by different output types that you are trying to match...
First, change your PHP output to
echo json_encode($final ? true : false);
Then, to work with JSON, I would add this line to ajax calling method, to be sure...
$.ajax({
type: 'POST',
dataType:'json',
...
success: function(msg)
{
if(msg!==true){
is_error = true;
}
}
});

Identifying what is returned when submitting a form using jquery

Is it possible to identify what a page returns when using jquery? I'm submitting a form here using jquery like this:
$("#sform").submit(function() {
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
url: "user_verify.php",
success: function(data) {
$("#form_msg").html(data);
}
});
return false;
});
​
The user_verify.php page does its usual verification work, and returns error messages or on success adds a user to the db. If its errors its a bunch of error messages or on success its usually "You have successfully signed up". Can I somehow identify using jquery if its errors messages its returning or the success message. So that way if its errors I can use that data in the form, or if its success, I could close the form and display a success message.
Yes, it's this:
success: function(data) {
$("#form_msg").html(data);
}
You can manipulate data in any way you want. You can return a JSON (use dataType) encoded string from server side and process data in the success function
success: function(data) {
if(data->success == 'ok'){
// hide the form, show another hidden div.
}
}
so user_verify.php should print for example:
// .... queries
$dataReturn = array();
$dataReturn['success'] = 'ok';
$dataReturn['additional'] = 'test';
echo json_encode($dataReturn);
die; // to prevent any other prints.
You can make you php return 0 if error so you do something like this inside
success: function(data) {
if(data==0){
//do error procedure
}else{
//do success procedure
}
}
Hope this helps
You can do and something like this:
$.ajax({
type:"POST", //php method
url:'process.php',//where to send data...
cache:'false',//IE FIX
data: data, //what will data contain
//check is data sent successfuly to process.php
//success:function(response){
//alert(response)
//}
success: function(){ //on success do something...
$('.success').delay(2000).fadeIn(1000);
//alert('THX for your mail!');
} //end sucess
}).error(function(){ //if sucess FAILS!! put .error After $.ajax. EXAMPLE :$.ajax({}).error(function(){};
alert('An error occured!!');
$('.thx').hide();
});
//return false prevent Redirection
return false;
});
You can checke the "data" parameter in "success" callback function.
I noticed that there is a problem in your code. Look at this line :
data: $(this).serialize(),
Inside $.ajax jquery method, "this" is bind to the global window object and not $('#sform')

jQuery, AJAX - How to tell if script returned false

I'm using jQuery and AJAX to validate my form when someone creates a new user on my website. I'm programming in OOP PHP, together with the jQuery and AJAX.
I'm using this code:
$.ajax({
type: "POST",
url: "includes/classes/handler.php?do=addLogin",
data: dataString,
success: function() {
$('.sideBarNewUserWrap').fadeOut();
}
});
return false;
But how do I return an error message, if the e-mail already exists?
Hope it's info enough, else I'll just add some more.
Thanks in forward :)
* UPDATE *
This is my PHP checking if email exists:
$email_count = mysql_num_rows($check_email);
if($email_count){
return false;
}
* UPDATE *
success: function(data){
if(data.error){
$('.sideBarNewUserWrap').fadeOut();
} else {
$('.sideBarNewUserError-email').fadeIn();
}
Now this looks pretty much as a failure because.
if(data.error) then it's okay?
Shouldn't it be something like:
if(date.error){
//Error message
}
And not the other way around?
Well, If I try to enter an email which already exists, it tells me as it should, but why does this work? In my eyes I'm doing something wrong here?
php:
$result = array('error' => true); // or $result = array('error' => false);
echo json_encode($result);
js:
success: function(response) {
if (response.error) {
// ...
}
}
You can get the response in the function:
$.ajax({
type: "POST",
url: "includes/classes/handler.php?do=addLogin",
data: dataString,
success: function(response) {
if (response == "ok")
{
$('.sideBarNewUserWrap').fadeOut();
}
else
{
// error happend
}
}
});
return false;
You can return string, int in PHP or even XML, JSON, whatever you want to validate on client side
You can return data by using an echo in your handler.php file.
To receive this in jQuery just place a parameter in the success function of the Ajax function.
success: function(returnedValue)
{
// Here you check if returned value e.g. "returnedValue == 1"
}
basically in the handler.php you should verify whether email already exists or not and then send to the client (at least) two different responses (eg. 0: email exists, 1:ok).
In the success callback you can read the response data so you can tell the user the operation status

Categories