I'm trying to make simple script using jquery $post function to pass data to my check.php file and then just get some result back so I can figure out the way data is manipulated b/w jQuery and PHP.
I have this script:
<script type="text/javascript">
$(document).ready(function(){
var Status = true;
$('.isLogged').click(function(){
if(Status!=false){
var Check = prompt('Enter Password', '');
$.post('check.php', Check, function(data) {
if(data == 'Y'){
alert('Y');
return false;
}
else
{
alert('N');
return false;
}
});
}
});
});
</script>
and this is all from my check.php file:
<?php
$data = $_POST['Check'];
if ($data == 'Ivan')
{
echo 'Y';
}
else
{
echo 'N';
}
?>
but it's not working and when I make var_dump($_POST) I get array(0). How can I fix this?
Thanks
Leron
"data" in $.post function must be a object
$.post('check.php', {Check: Check}, function(data) {
you should add json in your process.
:)
Your syntax is not correct for ajax request. Check is the value, you must set key for it. Should be like this
var Check = prompt('Enter Password', '');
$.post('check.php', Check:Check, function(data) {
Related
I need to compare two datetime objects but the ajax ain't working.
javascript
<script>
$(document).ready(function(){
$('.datepicker').change(function(){
var date=$(this).data('datepicker').getFormattedDate('yyyy-mm-dd');
$(this).attr('value',date);
});
$('#collectDate').change(function(){
var collectDate=$('#collectDate').val();
var expiryDate=$('#expiryDate').val();
$.post("index.php?ajaxController/fine",{collectDate:collectDate,expiryDate:expiryDate},
function(data){
if(data){
$('#fine').hide();
$('#collectFine').removeAttr('required');
}
else if(!data){
$('#fine').show();
$('#collectFine').attr('required');
}
});
});
$('#fine').hide();
});
</script>
Controller
<?php
class ajaxController extends CI_Controller{
public function fine() {
$data['collectDate']= $this->input->post('collectDate');
$data['expiryDate']= $this->input->post('expiryDate');
$this->load->view("backend/admin/fine",$data);
}
}
View
<?php
$collectDate=$collectDate;
$date= explode('/',$expiryDate);
$expiryDate1=new DateTime($date[2]."-".$date[0]."-".$date[1]);
$diff=$collectDate->diff($expiryDate);
if($diff>=0){
echo true;
}
else {
echo false;
}
I've also tried simple comparison operators but all in vain. It always executes the else part in success function.
It always returns false because you cannot really catch true/false in php code with ajax. What that code in your view does, is make some calculations, return true or false AND THEN RENDER AN HTML PAGE, an empty one in your case.
Calling that page with ajax, means you read the HTML, which if an empty page, means no data returned, so FALSE.
What you need to do is something like this:
In your view:
if($diff>=0){
echo 'true';
}
else {
echo 'false';
}
And in your jQuery:
$('#collectDate').change(function(){
var collectDate=$('#collectDate').val();
var expiryDate=$('#expiryDate').val();
$.post("index.php?ajaxController/fine",{collectDate:collectDate,expiryDate:expiryDate},
function(data){
if(data.indexOf('true') > -1){
$('#fine').hide();
$('#collectFine').removeAttr('required');
}
else if(data.indexOf('false') > -1){
$('#fine').show();
$('#collectFine').attr('required');
}
});
});
This should be fine.
Please help,
I have a dynamically generated set of button-incremented inputs. First i store id's and values into localstorage, and everything goes fine and i can see all the id-value pairs, but i cannot send the data using AJAX call.
Here's what it looks like:
The AJAX is assigned on button click:
<script>
$("#send_order").click(function (e) {
if (localStorage) {
if (localStorage.length) {
for (var i = 0; i < localStorage.length; i++) {
var pid = localStorage.key(i);
var value = localStorage.getItem(localStorage.key(i));
$.ajax({
url: "update.php?pid="+pid+"&qty="+value,
success: function(){
alert( "Прибыли данные: ");
}
});
}
} else {
output += 'Нет сохраненных данных.';
}
} else {
output += 'Ваш браузер не поддерживает локальное хранилище.';
}
)};
</script>
But nothing happens when the button is clicked.
What i do wrong?
While your code looks fine it is little inefficient to send your localstorage data one by one in a loop. It makes more sense to convert your localstorage to a json string and send everything at the same time. You can json_decode the json string in your php update script. Also I included a function to test if localStorage is available by trying to write in it. This is more reliable then if(localStorage)
$("#send_order").on("click", function () {
var output='';
if(localStorageTest() === true){
console.log('localStorage is available');
if(localStorage.length){
var data=JSON.stringify(localStorage);
$.ajax({
type: "GET",
url: "update.php?data="+data,
success: function(){
alert( "your data is send correctly!");
}
});
}else{
output += 'localStorage is empty\n';
}
}else{
output += 'localStorage is not available\n';
}
})
function localStorageTest(){
var test = "test";
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
Im trying to send some data to the server through AJAX with the value i get from a JS variable.
Code:
<script type="text/javascript">
var url;
function aplicarFoto(_src) {
url = _src;
var fotosel = document.getElementById("fotosel");
fotosel.src = 'fotos/'+_src;
}
function guardarCambios() {
$.post("guardarCambios.php",
{url: url},
function(response) {
alert(response);
if (response == "NoUsuario") {
window.location = "../login.php";
} else {
alert("correcto");
}
}
alert(url);
}
</script>
The idea is update the user picture with the url i get from aplicarFoto(_src) with the variable url .
The first function (aplicarFoto(_src)) alone works correctly, but when i put the another function (guardarCambios()), the first function doesnt work, therefore the second neither! I dont know why, but it just happens when using ajax functions because i did a test with an alert(url) (sunrrounding the rest of code with comments) in the second function and both work correctly!
Some guess? Thank you!
Your script alone has syntax errors.
<script type="text/javascript">
var url;
function aplicarFoto(_src) {
url = _src;
var fotosel = document.getElementById("fotosel");
fotosel.src = 'fotos/' + _src;
}
function guardarCambios() {
$.post("guardarCambios.php", {
url: url
}, function (response) {
alert(response);
if (response == "NoUsuario") {
window.location = "../login.php";
} else {
alert("correcto");
}
alert(url);
}
);
}
</script>
When a form is submitted, I can get its field values with $_POST. However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if theres no any blank field.
I am trying following code, and I got the success with jQuery, but the only problem is that I am unable to post the form after checking with jQuery. It does not get to the $_POST after the jQuery.
Also, how can I get the server response back in the jQuery (to check if there was any server error or not).
Here's what I'm trying:
HTML:
<form action="" id="basicform" method="post">
<p><label>Name</label><input type="text" name="name" /></p>
<p><label>Email</label><input type="text" name="email" /></p>
<input type="submit" name="submit" value="Submit"/>
</form>
jQuery:
jQuery('form#basicform').submit(function() {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
return false;
});
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return true;
}
To be very specific to the question:
How can I get the server response back in the jQuery (to check if
there was any server error or not). Here's what I'm trying:
Sound like you're talking about Server-Side validation via jQuery-Ajax.
Well, then you need:
Send JavaScript values of the variables to PHP
Check if there any error occurred
Send result back to JavaScript
So you're saying,
However, I am trying to use a basic jQuery (without any plugin) to
check if any field was blank, I want to post the form content only if
there's no any blank field.
JavaScript/jQuery code:
Take a look at this example:
<script>
$(function()) {
$("#submit").click(function() {
$.post('your_php_script.php', {
//JS Var //These are is going to be pushed into $_POST
"name" : $("#your_name_field").val(),
"email" : $("#your_email_f").val()
}, function(respond) {
try {
//If this falls, then respond isn't JSON
var result = JSON.parse(respond);
if ( result.success ) { alert('No errors. OK') }
} catch(e) {
//So we got simple plain text (or even HTML) from server
//This will be your error "message"
$("#some_div").html(respond);
}
});
});
}
</script>
Well, not it's time to look at php one:
<?php
/**
* Since you're talking about error handling
* we would keep error messages in some array
*/
$errors = array();
function add_error($msg){
//#another readers
//s, please don't tell me that "global" keyword makes code hard to maintain
global $errors;
array_push($errors, $msg);
}
/**
* Show errors if we have any
*
*/
function show_errs(){
global $errors;
if ( !empty($errors) ){
foreach($errors as $error){
print "<p><li>{$error}</li></p>";
}
//indicate that we do have some errors:
return false;
}
//indicate somehow that we don't have errors
return true;
}
function validate_name($name){
if ( empty($name) ){
add_error('Name is empty');
}
//And so on... you can also check the length, regex and so on
return true;
}
//Now we are going to send back to JavaScript via JSON
if ( show_errs() ){
//means no error occured
$respond = array();
$respond['success'] = true;
//Now it's going to evaluate as valid JSON object in javaScript
die( json_encode($respond) );
} //otherwise some errors will be displayed (as html)
You could return something like {"error": "1"} or {"error": "0"} from the server instead (meaning, put something more readable into a JSON response). This makes the check easier since you have something in data.
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return json_encode(array("error" => 0));
} else {
return json_encode(array("error" => 1));
}
JavaScript:
jQuery('input#frmSubmit').submit(function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
var myData = data;
if(myDate.error == 1) {//or "1"
//do something here
} else {
//do something else here when error = 0
}
});
}
$("form#basicform").submit();
return false;
});
There are two ways of doing that
Way 1:
As per your implementation, you are using input[type="submit"] Its default behavior is to submit the form. So if you want to do your validation prior to form submission, you must preventDefault() its behaviour
jQuery('form#basicform').submit(function(e) {
//code
e.preventDefault();
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$(this).submit();
return false;
});
Way 2:
Or simply replace your submit button with simple button, and submit your form manually.
With $("yourFormSelector").submit();
Change your submit button to simple button
i.e
Change
<input type="submit" name="submit" value="Submit"/>
To
<input id="frmSubmit" type="button" name="submit" value="Submit"/>
And your jQuery code will be
jQuery('input#frmSubmit').on('click',function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$("form#basicform").submit();
return false;
});
To get the response from the server, you have to echo your response.
Suppose, if all the variables are set, then echo 1; else echo 0.
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
echo 1;
} else {
echo 0;
}
And in your success callback function of $.post() handle it like
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast",{err:data}, function(e) {
if(e.data.err==1){
alert("no error");
} else {
alert("error are there");
});
});
I have a rather confusing problem.
I have a php file (http://example.com/delete.php)
<?php
session_start();
$user_id = $_SESSION['user_id'];
$logged_in_user = $_SESSION['username'];
require_once('../classes/config.php');
require_once('../classes/post.php');
$post = new Post(NULL,$_POST['short']);
#print_r($post);
try {
if ($post->user_id == $user_id) {
$pdo = new PDOConfig();
$sql = "DELETE FROM posts WHERE id=:id";
$q = $pdo->prepare($sql);
$q->execute(array(':id'=>$post->id));
$pdo = NULL;
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
and I'm trying to get this jquery to post data to it, and thus delete the data.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This post? (" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("post Has Been Deleted!");
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
and when I do that, it returns "Post Has Been Deleted!" but does not delete the post.
Confused by that, I made a form to test the php.
<form action="http://example.com/delete.php" method="POST">
<input type="hidden" value="8" name="short"/>
<input type="submit" name="submit" value="submit"/>
</form>
which works beautifully. Very odd.
I have code almost identical for deleting of a comment, and that works great in the javascript.
Any ideas? Beats me.
Thanks in advance,
Will
EDIT:
this works... but doesn't follow the href at the end, which is the desired effect. Odd.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This Post? (http://lala.in/" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete/post.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("Post Has Been Deleted!");
******************************************
event.preventDefault();
return false;
******************************************
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
If your PHP script delete the post, it doesn't return anything.
My bad, it's not answering the real question, but still is a mistake ;)
Actually, it seems that PHP session and AJAX doesn't quite work well together sometimes.
It means that if ($post->user_id == $user_id) will never validate, hence the non-deleting problem.
2 ways to see this :
Log $user_id and see if it's not null
Try to send the $_SESSION['user_id'] with your ajax post and check with it. But not in production, for security reason.
1-
Your PHP should return something in every case (at least, when you're looking for a bug like your actual case).
<?php
[...]
try {
if ($post->user_id == $user_id) {
[...]
echo 'true';
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
2-
jQuery is nice to use for AJAX for many reasons. For example, it handles many browsers and make checks for you but moreover, you can handle success and error in the same .ajax() / .post() / .get() function \o/
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short'); // If that's where your data is... Fair enough.
if (confirm("Delete This Post? (http://lala.in/" + num + ")")) {
$.post("delete/post.php", {short: num}, // Relative is nice :D
function(data){
if (data == 'false') {
alert('Deleting Failed!');
}else{
alert("Post Has Been Deleted!");
// Your redirection here ?
}
});
}
});
3-
If you need to send data from a form to a script and then do a redirection, I won't recommand AJAX which is usually use not to leave the page !
Therefore, you should do what's in your comment, a form to a PHP script that will apparently delete something and then do a redirection.
In your code I don't see num defined anywhere...and invalid isn't set when you think it is, so you're not passing that 8 value back and you're getting the wrong message, either you need this:
$.post("http://example.com/delete.php", {short: $("input[name=short]").val()},
Or easier, just .serialize() the <form>, which works for any future input type elements as well:
$.post("http://example.com/delete.php", $("form").serialize(),
I'm not sure where your code is being called, if for example it was the <form> .submit() handler, it'd look like this:
$("form").submit(function() {
$.post("http://example.com/delete.php", $(this).serialize(), function(data){
if (data == 'false') {
alert('Deleting Failed!');
} else {
alert("Post Has Been Deleted!");
}
});
Note that you need to check inside the callback, since invalid won't be set to true until the server comes back with data the way you currently have it, because it's an asynchronous call.