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.
Related
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
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;
}
}
});
Hi I have a jQuery ajax request for a login system. At first, it worked very well. But after a few try, it just started to show negative response. I checked firebug and it says that the response is, in my case "Connected". But the ajax response just shows "Not_connected". I don't know what to do :(. Please help me.
This is my jquery code :
var data_str = "username="+usrn+"&password="+pwd;
$.ajax({
type: "POST",
url: "index.php?rnd=" + Math.random(),
data : data_str,
complete : function(xhr,data){
if(data == 'connected'){window.location.href = 'admin.php';}
else if(data = 'not_connected'){ error_gen.html('Invalid username or password'); }
alert(data);
}
});
AS for the PHP code :
$log_result = $u_obj->login_user();
if($log_result == true)/*user is connected*/
{
echo 'connected';
exit;/*stoping the script after sending the result*/
}
elseif($log_result == false)/*error while logging in*/
{
echo 'not_connected';
exit;/*stoping the script after sending the result*/
}
Look at this thread: Is it possible to cache POST methods in HTTP?
It might be that there are headers which now make browser caching the response (although it's POST).
Also instead of rnd=" + Math.random() you can add write
$.ajax({
type: "POST",
cache: false,
..
Could it be browser caching?
Try adding this $.ajaxSetup({ cache: false });
You are using the wrong $.ajax option to retrieve the result. You should use the success option. Just change the
complete : function(xhr,data){
line for
success : function(data){
It should work.
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;
}
Here a sample use case:
I request a simple form via an ajax request. I want to submit the result to the same page that I requested. Is there a way to access the URL of that request in the resulting request's javascript?
Below is some code that accomplishes what I want via javascript AND PHP. The downside to this is that I have to include my javascript in the same file as myajaxform.php. I'd rather separate it, so I can minify, have it cached etc.
I can't use location.href, b/c it refers to the window's location not the latest request.
frm.submit(function () {
if (frm.validate()) {
var data = frm.serialize();
jQuery.ajax({
url : '<?= $_SERVER['PHP_SELF'] ?>',
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
}
return false;
});
If there's not a way to access it via javascript directly, how would you solve this problem so that the javascript can go in it's own file? I guess that I could in the original ajax request's success handler, create some sort of reference to the URL. Thoughts? Maybe something using the jQuery data method?
You can store the url to submit to in the action attribute of the form, and then set the url to frm.action:
jQuery.ajax({
url : frm.action,
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
Forgive me if I totally misinterpret your question, as I find it somewhat confusing. What about
frm.submit(function () {
if (frm.validate()) {
var data = frm.serialize();
jQuery.ajax({
url : window.location.href,
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
}
return false;
});