Getting Foreach Data - php

I am trying to get foreach data I am using jquery to submit the page without a refresh being required for some reason jQuery is not retrieving the foreach data, It needs to loop through each admin input field to see each data seperatly.
If it's not possible I won't use JQuery for this but thought I ask
PHP:
if(isset($_POST['admin_add']) AND is_array($_POST['admin_add'])) {
foreach($_POST['admin_add'] as $admin_add) {
if(strlen($admin_add) > 0) {
// $sql=mysql_query("insert into hobbies(hobby)values('$hobby')");
}
}
}
die('<h3>'.$admin_add.'<h3/>');
jQuery:
$(document).ready(function () {
var clan_url_string = window.location.search.substring(1);
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
clan_title_edit: $('#clan_title_edit').val(),
clan_des: $('#clan_des').val(),
admin_add: $('#admin_add').val(),
//remember_me: ($('#remember_me').is(':checked')) ? 1 : 0
}
}
$(window).load(function(){
$('#background_cycler').fadeIn(1500);//fade the background back in once all the images are loaded
setInterval('cycleImages()', 4000); // run every 4s
});
function loading(e) {
$('#loading_status').show();
}
function hide_loading(e) {
$('#loading_status').hide();
}
function success_message(e) {
$('#success_login').html("We're Just Signing You In");
}
function clearfields() {
$('#login-username').val(''); //Clear the user login id field
$('#login_password').val(''); //Clear the user login password field
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/save_settings.php?'+clan_url_string,
type: 'post',
error: function () {
//If your response from the server is a statuscode error. do this!!!'
hide_loading(e);
$('#status_message').html('<b>Something Has Gone Wrong</b><br> Please Try Again Later');
},
beforeSend: function () {
loading(e);
},
data: {
clan_title_edit: $('#clan_title_edit').val(),
clan_des: $('#clan_des').val(),
admin_add: $('#admin_add').val(),
remember_me: ($('#remember_me').is(':checked'))
}, // get current values
success: function (data) {
//if your response is a plain text. (e.g incorrect username or password)
hide_loading(e);
$('#status_message').hide();
$('#status_message').fadeIn(1000).html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#login_content').keyup(function (e) {
if (e.keyCode == 13) {
var username = $('#login-username').val();
check(e);
}
});
$('#submit_clan_settings').click(function (e) {
if (e.keyCode != 13) {
check(e);
}
});
There's the php and jquery
Thanks
Yes its SQL injection prone, havent fix this yet and I should be using mysqli or $db->);

Related

Laravel Ajax - success executed even when db row is not present

I'm working on a project where I have some jQuery code that is supposed to check if a certain row in the database exists. If the row does exist, The code within the success stage gets executed. But the problem I have with this script is when the 'checkdb' function gets executed the code within success happens even though the row doesn't exist in the database. What is causing this?
jQuery code
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
The jQuery above gets executed every minute, To check if the row is present.
The PHP code below is supposed to check if the row in the database exists. If it does, it should return a response which then ends up in the succeeding stage in jQUery. If it does not already exist, Do something else
PHP code
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing');
}
}
Why is it executing the succeeding stage even though the row does not already exist? Thanks in advance
response('content', 200, $headers) and `json()` helper also takes three param `json($data, status, $headers)`
methods take three parameters replace the content of the else
like
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing',404);
}
}
In jQuery, success block gets executed when response status code is 200. If you send status code as 404 which is in else block when DB is not exist, then error block will get executed instead of success. Laravel by default will send 200 as status code for AJAX requests in response.
Add dataType:"JSON"
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
datatype:'JSON',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);

codeigniter function load two pages of same function calls in different ways

I am using two ways for user login in codeigniter:
One is by typing url like this localhost/mySite/login
Other is popup dialog appear when I click a link from localhost/mySite
When I'm following step 2 then calling a function using ajax request.
both time I am calling same function. but when call to the function using Ajax load an additional header.
I used following code for the calling function.
if ($this->input->is_ajax_request()){
echo json_encode(array('status'=>'success','url'=>'auth/enable_account'));
exit();
}
else {
redirect ( "auth/enable_account",'refresh');
}
My jquery code
jQuery('#signin_form').submit(function(event) {
var email = jQuery('#email').val();
var password = jQuery('#password').val();
var remember = jQuery('.dev_signin_remember').is(':checked');
jQuery.ajax({
url:baseurl+'auth/login',
type:'POST',
data:{'email':email,'password':password,'remember':remember},
dataType:'json',
success:function(data){
if(data.status == 'success') {
if(data.url != '') {
window.location.replace(baseurl+data.url);
}
else {
window.location.replace(baseurl+"auth/login");
}
}
else {
jQuery('.dev_signin_error').html('Invalid Username or password');
}
}
});
setTimeout(jQuery.unblockUI);
});

ajax returning true while FALSE

I am using codeigniter, i have written a function to check if a user password exists which it does. This is my model
The model: user
public function get_some_password($username,$password) {
$this->db->where('user_password', $password);
$this->db->where('user_username',$username);
$query=$this->db->get('some_users_table');
if($query->num_rows()==1){
return true;
}else{
return false;
}
the controller
public function check_password() {
$username=$this->uri->segment(3);
$temp_pass= $this->input->post('current_password');
$password=md5($temp_pass);
$this->user->get_some_password($username,$password);
}
The ajax on the view
//done on page load
var success1 = $(".success"); //a div on the view that appears if success
var error1 = $(".error"); //a div on the view that appears if error
success1.hide();
error1.hide();
$('#change_password').click(function() {
var username = $('#username').val();
dataString2 = $('#changpassword').serialize();
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>controller_name/check_password/' + username,
data: dataString2,
success: function() {
$('.success').html('password successfully updated!'),
success1.slideDown('slow');
},
error: function() {
$('.error').html('Wrong current password!'),
error1.slideDown('slow');
}
});
The problem: Ajax loads the success div even when the username or password returned is false, where am i missing something
This is a correct behavior as jquery error is executed when response code is not 200:
1) You can parse returned value in success method.
e.g.
success: function(data) {
if (data == 'true') {
// Success
} else {
// Error
}
}
2) You can return error code from server 404, 500, 503 ... To trigger execution of error function.
e.g.
header("Status: 404 Not Found");
note: Header should executed before any output is done.
Try in your controller:
public function check_password() {
$username=$this->uri->segment(3);
$temp_pass= $this->input->post('current_password');
$password=md5($temp_pass);
if(!$this->user->get_some_password($username,$password)) {
$this->output->set_status_header('500');
return;
}
...
}

Jquery and ajax, my function for username checking?

I have written this ajax request for username checking...
function check_username() {
var username = $("#username").val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: $('#username').val(),
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#' + id).after(response).fadeIn(1000);
}
It all works fine just a couple of questions,
Can this code be improved in any way, this is the first ever one I have wrote so I wouldn't know.
Is there a way to make this a function for all my ajax requests rather than just username checking, so it can be used for email checking and such too. I am not sure on how to make a function like that would I have to pass variables on my onblur event which is attached to my form, at the minute it looks like this.
Is there a way to stop the ajax from running if the same error is there as previous, ie, string length should be over 3, so someone inputs AJ, and the error message 'must be over 3 characters' comes up, it the user then triggers the onblur event again, with the value of AJ, or CG, then the same error comes up, triggering a script that is useless and using memory.
Is there a way to make the ajax request with every character the user enters?
My ajax php is as follows...
<?php
require('dbc.php');
if (isset($_REQUEST['username'])) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
?>
To answer 1 & 2. I would turn it into a plugin and do something along these lines.
$.fn.checkValid = function(options)
{
var response = function(response) {
var setClass = '';
var $span = $(this).data('checkValidTip');
if ($span)
{
$span.remove();
}
if (response === undefined) return;
setClass = (response.valid ? 'valid' : 'invalid');
var $span = $('<span>' + response.msg + '</span>');
$(this)
.data('checkValidTip', $span)
.after($span);
$span.hide()
.fadeIn(1000)[0]
.className = setClass;
};
var ajaxOptions = {
type: 'GET',
url: 'ajax.php',
success: response,
dataType: 'json'
};
this.each(function() {
var that = this;
var ajaxRequest = ajaxOptions;
ajaxRequest.data = {};
ajaxRequest.data[options.key] = this.value;
ajaxRequest.context = that
$.ajax(ajaxRequest);
});
};
Usage
$('#username, #email').blur(function() {
$(this).checkValid({ key: this.id });
});
PHP changes
You should make your PHP function return a JSON, instead of HTML i.e.
<?php
// Do your sql statements here, decide if input is valid or not
$arr = array('valid' => $is_valid,
'msg' => $error_or_good_msg
);
echo json_encode($arr);
/* For example will output:
{
"valid": "false",
"msg": "<b>Error: Must be at least 2 characters</b>"
}
Which can be read directly as response.valid
or response.msg from within response() function
*/
To answer question 3: short answer is no. For this to work, you should have basic validation in JS. The best option would be to use a plugin that uses objects for validation parameters, that way you can output your validation requirements dynamically from your database, from within PHP using json_encode i.e. your output format would be:
var validations = {
username: {
min_chars: 4,
max_chars: 10,
valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
},
email: {
regex: /./ //your magic regex here
}
};
jsFiddle
http://jsfiddle.net/sqZfp/2/
To answer 4, just change the event as above from .blur to .keyup should do the trick.

Javascript - waiting for a click before ending function

I have made what is essentially a lightbox whereby if a change requires the user to confirm their password, this lightbox pops up and the user enters there password etc.
I am triggering the function like this:
if(verifyPassword())
{
//apply change
}
The verify function is:
function verifyPassword() {
$('#confirmpasswordoverlay').fadeIn(300);
$('#submit').click(function() {
$.post('', { password: $('input[name=password]').val() },
function(check) {
if(check.error)
{
if(check.password)
{
//show password error
return false;
}
else
{
//show error
return false;
}
}
else
{
return true;
}
}, 'json');
});
}
Basically I am needing the function to wait until #submit is clicked to return either true or false.
Thanks in advance
Since jQuery 1.5.0, you can do apply some magic with Deferred objects:
$.when( verifyPassword() ).done(function() {
// do something
});
You would need to re-write verifyPassword() a little:
function verifyPassword() {
var Notify = $.Deferred();
$('#confirmpasswordoverlay').fadeIn(300);
$('#submit').click(function() {
$.post('', { password: $('input[name=password]').val() },
function(check) {
if(check.error) {
if(check.password) {
//show password error
Notify.resolve();
}
else {
//show error
Notify.reject();
}
}
else {
return true;
}
}, 'json');
});
return Notify.promise();
}
This might not be the most elegant way of achieving your goal here, I'm just saying you could do it in a way like this :-)
Don't stall, instead provide a callback:
function verifyPassword(f) {
/**
* Do all your logic here, then callback to the passed function
*/
f(result);
}
verifyPassword(function (correct) {
if (correct) {
/* Continue */
}
else { /* Other */ }
});
I think you want to convert your $.post() call into the more generic $.ajax() jQuery call, and pass in async: false. Something like:
$.ajax('', { async:false, data: {password:...}, success: function() {
// ... success callback ...
}});

Categories