Ajax it does nothing when sending parameters to a php page - javascript

I am a beginner using ajax and am trying to change the status of reading a book by clicking an image.
I had the code working but without ajax. Now I have no php error but not a change in mysql.
The code:
<script type="text/javascript">
function sendState(state_id){
var hd_haveread = $("#hd_haveread").val();
var hd_toread = $("#hd_toread").val();
var hd_reading = $("#hd_reading").val();
var val = 0;
var baseurl = "img/";
switch(state_id){
case 1:
if (hd_haveread == "0"){
document.getElementById('hd_haveread').value = "1";
document.getElementById('hd_toread').value = "0";
document.getElementById('hd_reading').value = "0";
val = 1;
}
else{
document.getElementById('hd_haveread').value = "0";
val = 0;
}
break;
case 3:
if (hd_toread == "0"){
document.getElementById('hd_toread').value = "1";
document.getElementById('hd_haveread').value = "0";
document.getElementById('hd_reading').value = "0";
val = 1;
}
else{
document.getElementById('hd_toread').value = "0";
val = 0;
}
break;
case 2:
if (hd_reading == "0"){
document.getElementById('hd_reading').value = "1";
document.getElementById('hd_haveread').value = "0";
document.getElementById('hd_toread').value = "0";
val = 1;
}
else{
document.getElementById('hd_reading').value = "0";
val = 0;
}
break;
}
var parameters = {
"book" : <?php echo $id_book; ?>,
"state" : state_id,
"val" : val
};
$.ajax({
cache: false,
data: parameters,
url: 'change_state_ajax.php',
type: 'post',
dataType: "html",
beforeSend: function (){
},
success: function (response){
switch(state_id){
case 1:
if (hd_haveread == "0"){
$("#img_haveread1").css("display","none");
$("#img_haveread2").css("display","inline-block");
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
else{
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
}
break;
case 3:
if (hd_toread == "0"){
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
$("#img_toread1").css("display","none");
$("#img_toread2").css("display","inline-block");
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
else{
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
}
break;
case 2:
if (hd_reading == "0"){
$("#img_haveread1").css("display","inline-block");
$("#img_haveread2").css("display","none");
$("#img_toread1").css("display","inline-block");
$("#img_toread2").css("display","none");
$("#img_reading1").css("display","none");
$("#img_reading2").css("display","inline-block");
}
else{
$("#img_reading1").css("display","inline-block");
$("#img_reading2").css("display","none");
}
break;
}
}
});
}
</script>
And the change_state_ajax.php code:
<?php
if(isset($_POST['book']) && isset($_POST['state']) && isset($_POST['val'])){
include 'connection.php';
include('php_lib/config.ini.php');
include_once('php_lib/login.lib.php');
$lib_id = $_POST['book'];
$state = $_POST['state'];
$val = $_POST['val'];
$result=changeState($lib_id, $state, $val);
echo $result;
}
function changeState($lib_id, $state, $val){
session_start();
$usu_id = $_SESSION['USSER']['id'];
$mark = 0;
$pos = 0;
$query = $pdo->prepare('SELECT uliusu_id, ulilib_id, uliedl_id FROM '.TABLE_USSERS_BOOKS.' WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->execute();
while($row = $query->fetch(PDO::FETCH_OBJ)){
$mark = 1;
$state_actual = $row->uliedl_id;
}
if($mark == 0){
$query = $pdo->prepare('INSERT INTO '.TABLE_USSERS_BOOKS.' (uliusu_id, ulilib_id, uliedl_id, uli_posicion, uli_fecha) VALUES (:fil_usu_id, :fil_lib_id, :fil_edl_id, :fil_pos, NOW())');
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->bindParam(':fil_edl_id', $state, PDO::PARAM_INT);
$query->bindParam(':fil_pos', $pos, PDO::PARAM_INT);
$query->execute();
}else{
if($state == $state_actual){
$query = $pdo->prepare('DELETE FROM '.TABLE_USSERS_BOOKS.' WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$queryquery->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->execute();
}else{
$query = $pdo->prepare('UPDATE '.TABLE_USSERS_BOOKS.' SET uliedl_id = :fil_edl_id WHERE ulilib_id = :fil_lib_id AND uliusu_id = :fil_usu_id');
$query->bindParam(':fil_edl_id', $state, PDO::PARAM_INT);
$query->bindParam(':fil_usu_id', $usu_id, PDO::PARAM_INT);
$query->bindParam(':fil_lib_id', $lib_id, PDO::PARAM_INT);
$query->execute();
}
}
if($state == 1){
$result = 0;
}else{
$result = 1;
}
return $result;
}
?>
Can anyone help me solve this?
Thanks.

You are not checking for the proper variables. Your JavaScript passes a var called estado but you check in PHP for a var called state.
And because you require all three variables to be set your condition fails.
Also like Hank said in his comment your jQuery.Ajax call uses POST (type: 'post',) but then in your PHP script you check GET variables which of course are not set.
Either change you jQuery call type to GET or change the checking in your PHP script to POST
if(isset($_POST['book']) && isset($_POST['state']) && isset($_POST['val'])){
include 'connection.php';
include('php_lib/config.ini.php');
include_once('php_lib/login.lib.php');
$lib_id = $_POST['book'];
$state = $_POST['state'];
$val = $_POST['val'];
$result=changeState($lib_id, $state, $val);
echo $result;
}

Things I noticed:
1) First you are POSTing but in PHP, you are using $_GET.
2) you are passing "book", "estado", "val" but are trying to get "book", "state", "val", so it never enters into if condition

Related

How do I submit form without page reload taking into consideration the php script?

So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else{
}
if (email == ""){
$("input#youremail").focus;
return false;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
//qis_process_application in register.php
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});

PHP AJAX script not working properly on all conditions

I have a script where I want to process form data using ajax. The script is returning the success message but not the error message. Have a look at the scripts below.
AJAX Script
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val()
};
$.ajax({
type: "POST",
dataType : "json",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#submit").show();
$("#loading").hide();
},3000);
}
});
return false;
});
});
PHP Script
<?php
session_start();
include'config/db.php';
$msg = null;
$sessionid = (!empty($_SESSION['login']))?$_SESSION['login']:null;
$wp = $pdo->prepare("SELECT set_cointoss_wp, set_cointoss_prob FROM settings");
$wp-> execute();
$sp = $wp->fetch();
$percent = $sp['set_cointoss_wp'];
$probablity = $sp['set_cointoss_prob'];
$bal = $pdo->prepare("SELECT mb_acbal, mb_wallet FROM mem_balance WHERE mb_id = :mem");
$bal-> bindValue(':mem', $sessionid);
$bal-> execute();
$bf = $bal->fetch();
$balance = $bf['mb_acbal'];
$wallet = $bf['mb_wallet'];
$coin = (!empty($_POST['flip']))?$_POST['flip']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
if($_POST){
if($wallet < $amount){
$msg = "<div class='message-error'>Sorry buddy! You have insufficient balance. Please <a href=''>recharge</a> your wallet.</div>";
}else{
$deduct = $wallet-$amount;
$prob = rand(1, 10);
//set new wallet balance after bet amount deduction
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_wallet = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $deduct);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
if($coin == ''){
$msg = "<div class='message-error'>Sorry buddy! Fields cannot be left empty.</div>";
}else{
if($coin == "head"){
if($prob <= $probablity){
$result = 1;
}else{
$result = 2;
}
if($result == 1){
// win
$wa = $amount*$percent;
$win_amount = $wa/100;
$final_cash = $win_amount+$balance;
// update database with winning amount
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $final_cash);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
$msg = "<div class='message-success'>Congratulations buddy! You won... <strong>$".$win_amount."</strong> has been credited to your account.</div>";
}else{
// loose
$msg = "<div class='message-error'>Sorry buddy! You lost... But do not loose hope. Try your luck again :)</div>";
}
}else{
if($prob <= $probablity){
$result = 2;
}else{
$result = 1;
}
if($result == 1){
// loose
$msg = "<div class='message-error'>Sorry buddy! You lost... But do not loose hope. Try your luck again :)</div>";
}else{
// win
$wa = $amount*$percent;
$win_amount = $wa/100;
$final_cash = $win_amount+$balance;
// update database with winning amount
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $final_cash);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
$msg = "<div class='message-success'>Congratulations buddy! You won... <strong>$".$win_amount."</strong> has been credited to your account.</div>";
}
}
}
}
echo json_encode(array('status' => $msg, 'deduct' => $deduct));
}
?>
Here in the scripts above, when if($wallet < $amount) condition is false and else condition is executed, the scripts works fine and returns <div class='message-success'> as required. But, if if($wallet < $amount) condition is true then its not returning <div class='message-error'> and the loading image keeps on moving (as if waiting for the response) but does not receives any response in return. I am stuck since a few days on this but not being able to find any solution for the same. Please help.
I am not sure but I think in your php script $deduct has been declared inside the else block.
so when the script executes and if ($wallet < $amount) condition evaluates to true, then the else part is skipped and you directly return this:-
return echo json_encode(array(
'status' => $msg,
'deduct' => $deduct
));
so it might be the case that $deduct is not recognized. try executing by declaring the $deduct before the if block.

what can I do to prevent xss code?

I have escaped my fields, but when I make an xss code like <script>alert(one frame);</script> then the table which is specially for display the date the xss code is sent it to my database. I want when I make my own xss code dont send the JS script to my database.
$code = trim(stripslashes(htmlspecialchars($_POST['code'])));
$product = trim(stripslashes(htmlspecialchars($_POST['product'])));
$result = new sale();
$sale_type = $result->getTypeSaleById($_POST['sale_type']);
$purchase_price = trim(stripslashes(htmlspecialchars($_POST['purchase_price'])));
$sale_price = trim(stripslashes(htmlspecialchars($_POST['sale_price'])));
$min_stock = trim(stripslashes(htmlspecialchars($_POST['min_stock'])));
$stock = trim(stripslashes(htmlspecialchars($_POST['max_stock'])));
my controller
case 'add_product':
if(isset($_POST['code']) && $_POST['code']!= '' && isset($_POST['product']) && $_POST['product']!= '' && isset($_POST['sale_type']) && $_POST['sale_type']!= '' && isset($_POST['purchase_price']) && $_POST['purchase_price']!= 0 && isset($_POST['sale_price']) && $_POST['sale_price']!= 0 && isset($_POST['min_stock']) && $_POST['min_stock']!= '' && isset($_POST['max_stock']) && $_POST['max_stock']!= '' ){
$code = trim(stripslashes(htmlspecialchars($_POST['code'])));
$product = trim(stripslashes(htmlspecialchars($_POST['product'])));
$result = new sale();
$sale_type = $result->getTypeSaleById($_POST['sale_type']);
$purchase_price = trim(stripslashes(htmlspecialchars($_POST['purchase_price'])));
$sale_price = trim(stripslashes(htmlspecialchars($_POST['sale_price'])));
$min_stock = trim(stripslashes(htmlspecialchars($_POST['min_stock'])));
$stock = trim(stripslashes(htmlspecialchars($_POST['max_stock'])));
$newProduct = new product();
if($newProduct->add($code,$product,$sale_type,$purchase_price,$sale_price,$min_stock,$stock)){
echo "success";
}else{
echo "it cannot be added";
}
}
else{
echo "something went wrong";
}
break;
my javascript function
function addProduct(){
var code = $('#code').val();
var product = $('#product').val();
var sale_type = $('#sale_type').val();
var purchase_price = $('#purchase_price').val();
var sale_price = $('#sale_price').val();
var min_stock = $('#min_stock').val();
var max_stock = $('#max_stock').val();
var valCheck = verificar();
if(valCheck == true){
$.ajax({
url: '../controller/product_controller.php',
type: 'POST',
data: 'code='+code+'&product='+product+'&sale_type='+sale_type+'&purchase_price='+purchase_price+'&sale_price='+sale_price+'&min_stock='+min_stock+'&max_stock='+max_stock+'&boton=add_product',
}).done(function(ans){
if(ans == 'success'){
$('#code,#product,#purchase_price,#sale_price').val("");
$('#sale_type').val('0');
$('#min_stock,#max_stock').val('0');
$('#success').show().delay(2000).fadeOut();
searchProduct('','1');
}else{
alert(ans);
}
})
}
else {
}
}
XSS code in database
datable
While displaying data from database, use htmlspecialchars() function.

Variable getting via Ajax is empty ( Phonegap-Ajax-Json-PHP-MySQL )

I created an android application using Phonegap. I made an account in 000webhost and I've added my PHP files on the server. In the phpMyAdmin, I've created my database.
Right, now I tried to connect my project with the online database and insert or check some data in it.
PROBLEM:
When I run the application in my mobile phone i get this alert from the success: ... part of code in ajax :
There is no such username.
(my PHP had in comments all the echo, except the: echo json_encode)
When I added this line (var_dump($_POST);) right after i am getting the $usernamefrom ajax in the PHP and run my app, I saw this alert: array(1){ [\"username\"]=> string(2) \"hi"\" }
When I added these lines: if (empty($username)) { echo '...' } , after I run my app, I saw that in the alert inside the error: ... part of the ajax, it is printed the echo that is inside this if. So, the $username is empty for sure.
This is my JavaScript file: (I get correctly for sure all the values from html so Focus on the two Ajax parts of code)
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
var el = document.getElementById("register");
el.addEventListener("click", Register, false);
}
function Register() {
var username = document.getElementsByName('username')[0];
var password = document.getElementsByName('password')[0];
var email = document.getElementsByName('email')[0];
var strong_flag_user = 0;
var user = username.value;
if (username.value == "") {
$("#username").focus();
document.getElementById('username').style.boxShadow = "0 0 7px #f00";
navigator.notification.vibrate(500);
}
else{
$.ajax({
url: "http://www.guidemeforall.freeiz.com/phps/check_for_dublicates/check_username.php",
type: "POST",
crossDomain: true,
data: { username: user },
dataType:'json',
success: function(response){
if (response.status == 'success') {
alert(response.message);
document.getElementById('username').style.boxShadow = "none";
strong_flag_user = 1;
}
else if (response.status == 'error') {
alert(response.message);
navigator.notification.alert("This username is already taken! Please use another one!", null, 'Username', 'Okay');
document.getElementById('username').style.boxShadow = "0 0 7px #f00";
navigator.notification.vibrate(500);
strong_flag_user = 0;
//window.location("main.html");
}
else {
alert("error");
strong_flag_user = 0;
}
},
error: function(error){ //function(error){
alert(JSON.stringify(error));
strong_flag_user = 0;
//window.location = "main.html";
}
});
}
//>5 characters, 1 upper case, at least 1 lower case, at least 1 numerical character, at least 1 special character
var passExp = /(?=^.{6,15}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*/;
var strong_flag_pass = 0;
if (!(password.value.match(passExp))) {
$("#password").focus();
document.getElementById('password').style.boxShadow = "0 0 7px #f00";
navigator.notification.alert("Please enter a strong Password! It has to have at least: 6 characters, 1 upper case, 1 lower case, 1 numerical character and 1 special character!", null, 'Password', 'Okay');
navigator.notification.vibrate(500);
strong_flag_pass = 0;
}
else{
document.getElementById('password').style.boxShadow = "none";
strong_flag_pass = 1;
}
var emailExp = /^.+#[^\.].*\.[a-z]{2,}$/;
var strong_flag_email = 0;
if (!(email.value.match(emailExp))) {
$("#email").focus();
document.getElementById('email').style.boxShadow = "0 0 7px #f00";
navigator.notification.alert("Please enter a correct Email!", null, 'Email', 'Okay');
navigator.notification.vibrate(500);
strong_flag_email = 0;
}
else {
document.getElementById('email').style.boxShadow = "none";
strong_flag_email = 1;
}
var gender;
if (document.getElementById("gender").value == "female")
gender = 'F';
else
gender = 'M';
var about_you = document.getElementById("about_you").value;
var age = document.getElementById("radio-choice").value;
if (document.getElementById('radio-choice-1').checked) {
age = document.getElementById('radio-choice-1').value;
}
else if (document.getElementById('radio-choice-2').checked) {
age = document.getElementById('radio-choice-2').value;
}
else if (document.getElementById('radio-choice-3').checked) {
age = document.getElementById('radio-choice-3').value;
}
else if (document.getElementById('radio-choice-4').checked) {
age = document.getElementById('radio-choice-4').value;
}
else if (document.getElementById('radio-choice-5').checked) {
age = document.getElementById('radio-choice-5').value;
}
else if (document.getElementById('radio-choice-6').checked) {
age = document.getElementById('radio-choice-6').value;
}
if (strong_flag_user == 1 && strong_flag_pass == 1 && strong_flag_email == 1){
//add to db
register_db(email.value, password.value, username.value, gender, about_you, age);
}
}
function register_db(em, pass, user, gend, about, ag) {
$.ajax({
url: "http://www.guidemeforall.freeiz.com/phps/sign-up.php",
type: "POST",
crossDomain: true,
data: { username:user, password:pass, email:em, gender:gend, about_you:about, age:ag },
dataType:'json',
success: function(data)
{
if (data.status == 'success')
{
alert("Success!");
}
else if (data.status == 'error')
{
alert("Failure!");
}
}
});
}
This is my PHP file in which I check if the username already exists (Username = Primary Key):
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
//require_once('../database_config.php');
$server = "my***.000webhost.com";
$database = "a1****37_guideme";
$username = "a1****37_guideme";
$password = "*****";
$con = mysql_connect($server, $username, $password);
// if($con) { //echo "Connected to database!"; }
// else { //echo "Could not connect!"; }
mysql_select_db($database, $con);
$topost = file_get_contents('php://input');
$thedata = json_decode($topost, true);
$username = $thedata['username'];
//var_dump($_POST);
//if (empty($username)) {
// echo 'The username is either 0, empty, or not set at all';
//}
$sql = "SELECT COUNT(*) as Count FROM `user` WHERE `username`='$username'";
$result= mysql_query($sql, $con);
$rows = mysql_fetch_array($result);
$count = $rows['Count'];
if (!$result) {
die('Error: ' . mysql_error());
//$response_array['status'] = 'error';
//echo json_encode($response_array);
}
else {
if ($count == 0) {
echo json_encode(array('status' => 'success','message'=> 'There is no such username'));
//$response_array['status'] = 'success';
//echo json_encode($response_array);
}
else
{
echo json_encode(array('status' => 'error','message'=> 'The username already exists'));
//$response_array['status'] = 'error';
//echo json_encode($response_array);
}
}
mysql_close($con);
?>
And this is the PHP file in which I tried to insert the new entry in my database ( my credentials are for sure correct):
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
//require_once('database_config.php');
$server = "mys****.000webhost.com";
$database = "a***37_guideme";
$username = "a***37_guideme";
$password = "******";
$con = mysql_connect($server, $username, $password);
// if($con) { //echo "Connected to database!"; }
// else { //echo "Could not connect!"; }
mysql_select_db($database, $con);
$topost = file_get_contents('php://input');
$thedata = json_decode($topost, true);
$username = $thedata['username'];
$password = $thedata['password'];
$email = $thedata['email'];
$gender = $thedata['gender'];
$age = $thedata['age'];
$about_you = $thedata['about_you'];
$sql = "INSERT INTO user (username, password, email, gender, age, about_you) ";
$sql .= "VALUES ('$username', '$password', '$email', '$gender', '$age', '$about_you')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
// $response_array['status'] = 'error';
// echo json_encode($response_array);
}
else {
echo json_encode(array('status' => 'success','message'=> 'No problem'));
// $response_array['status'] = 'success';
// echo json_encode($response_array);
}
mysql_close($con);
?>
My problem solved by changing the way I get the data in my PHP to -> $user = $_POST['username']; instead of the way with Json (json_decode e.t.c.).

using jquery to loads result into pages

I have got a php databse query which I am trying to process with jquery to loads pages, at the moment when i try and test nothing happens so I feel that the problem lies within my HTMLoutput within the jquery script where I am trying to carry out a php explode function could anyone shed some light on this?
here is the php code to parse the data:
if (!$db_server){
die("unable to Connect to MYSQL: " . mysqli_connect_error($db_server));
$db_status = "not connected";
}else{
if(trim($_POST['submit']) =="submit"){
}else{
if (isset($_POST['dropoption']) && ($_POST['dropoption'] != '')){
if (isset($_POST['meal']) && ($_POST['meal'] != '')) {
if(isset($_POST['pn'])){
$rpp = preg_replace('#[^0-9#', '', $_POST['rpp']);
$last = preg_replace('#[^0-9#', '', $_POST['last']);
$pn = preg_replace('#[^0-9#', '', $_POST['pn']);
if ($pn < 1) {
$pn = 1;
} else if ($pn > $last){
$pn = $last;
}
include_once("db_connect.php");
$limit = 'LIMIT ' .($pn - 1) * $rpp .',' .$rpp;
$sql = "SELECT * FROM `recipename` WHERE `cuisine_type` ='$dropoption' AND `b_l_d` ='$meal' $limit";
$query = mysqli_query($db_server, $sql);
$datastring = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$mealname = $row["mealname"];
$mealpic = $row["imagepath"];
$cookingtime = $row["minutes"]."minutes".$row["hours"]."hours";
$ingredients = $row["ingredients"];
$recipe = $row["recipe"];
$datastring .= $mealname.'|'.$mealpic.'|'.$cookingtime.'|'.$ingredients.'|'.$recipe.'||';
}
echo $datastring;
exit();
}
$dropoption = clean_string($db_server, $_POST['dropoption']);
$meal = clean_string($db_server, $_POST['meal']);
$quer = "SELECT COUNT(recipeid) FROM `recipename` WHERE `cuisine_type` ='$dropoption' AND `b_l_d` ='$meal'";
mysqli_select_db($db_server, $db_database);
$querya= mysqli_query($db_server, $quer);
if (!$querya) die("database access failed: " . mysqli_error($db_server));
$row = mysqli_fetch_row($querya);
$total_rows = $row[0];
$rpp = 1;
$last = ceil($total_rows/$rpp);
if(last < 1){
$last = 1;
}
}//if(meal)//
}//if(cuisine)//
} //if(trim)//
}
?>
And here is the jquery script:
<script type="text/javascript">
var rpp=<?php echo $rpp; ?>;
var last=<?php echo $last; ?>;
function request_page(pn) {
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results";
var hr = new XMLHttpRequest();
hr.open("POST", "results.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urleconded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var dataArray = hr.responseText split("||");
var html_output = "";
for(i= 0; i< dataArray.length - 1; i++) {
var itemArray = dataArray[i].split("|");
html_output += "Recipe: "+itemArray[0]+"<img src='http://ml11maj.icsnewmedia.net/Workshops/Week%207/"+itemArray[1]+"'/><h2>Ingredients</h2><?php $ingredientchunks = (explode(",","+itemArray[2]+"));
for($i = 1; $i < count($ingredientchunks); $i++){
echo "$i.$ingredientchunks[$i] <br/>";}?>"+itemArray[3]+"<h2>Recipe</h2>
<?php $recipechunks = (explode(",","+itemArray[4]+"));
for($i = 1; $i < count($recipechunks); $i++){
echo "$i.$recipechunks[$i] </br>";}
?>";
}
results_box.innerHTML = html_output;
}
}
hr.send("rpp="+rpp+"&last="+last+"&pn="+pn);
//change pagination controls//
var paginationCtrls = "";
if(last !=1) {
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn !=last) {
paginationCtrls += '< <button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
Yep, I suspect it's your explode(",","+itemArray[2]+") that's causing the problem.
Explode is used to split strings into arrays, like so:
$string = "Apples,Oranges,Pears";
$array = explode(",",$string);
var_dump($array);
Example Output
array(2)
(
[0] => string(5) "Apples"
[1] => string(6) "Oranges"
[2] => string(4) "Pears"
)

Categories

Resources