Useing php and ajax to insert data to database - php

My problem is my code go to else condition. So what I want I need if condition.
see my code bellow :
Ajax code :
<script>
$(document).ready(function(){
$(function(){
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
var my_value = ($(this).val());
alert(my_value);
var toLoad = "ajax.php/"+my_value;
$("#my_div").load(toLoad,function(response,status,xhr){
if(status == "error"){
alert("Please check again have some error ");
}
else{
alert($(this).val());
}
});
return false;
}
});
});
});
</script>
- Html code:
<div id="my_div">
<form>
<input type="radio" name="group2" value="Water"> yes<br>
<input type="radio" name="group2" value="Beer"> Good<br>
<input type="radio" name="group2" value="Wine">Exellent
</form>
</div>
<div>
<?php
if(isset($_GET['my_value'])) {
echo $_GET['my_value'];
$con=mysqli_connect("localhost","root","");
mysql_query("INSERT INTO test_ajax(id, username, password) VALUES(Null,'sothorn', '123')");
}else
echo "Not get value";
?>
</div>
I would like to insert database but it go to else condition please help me

var toLoad = "ajax.php/"+my_value;//this line
//should be
var toLoad = "ajax.php/my_value="+my_value;//this code

Related

Submit form checkbox value without page refresh Ajax php

Still learning ajax.
Now i go stuck at this point.
Am trying to get the value of the checkbox on my form.
Below is my HTML code
<form method="post">
<input type="text" name="mytext" id="text">
<br>
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<input type="submit" id="form4" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax Script
$(document).ready(function() {
$("#form4").click(function(event) {
var action = 'another_test';
var text = $("#text").val();
var agreed = $("#agreed").val();
event.preventDefault();
$.ajax({
type: "POST",
url: "test3.php",
data: {
mytext:text,
test:agreed,
action:action
},
success: function (response)
{
$(".form-message").html(response);
}
});
});
});
Then this is my PHP code below which is on a different page
<?php
if (isset($_POST['action']))
{
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$mytext = $_POST["mytext"];
$errorEmpty = false;
if (empty($mytext)) {
echo "<p>enter your text</p>";
$errorEmpty = true;
}
elseif (empty($test)) {
echo "<p>Click the checkbox</p>";
$errorEmpty = true;
}
else {
echo "<p>Correct</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
It works for text, textarea input but not for checkbox. I know am wrong. Am still learning though.
Please help me. Thanks in advance.
Using $("#agreed").val() you only receive the value you setted in the "value" attribute on your input checkbox tag. To get a boolean value of checkbox's state you have to do use .is() function
$("#agreed").is(":checked");

No alert in success function

I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>

How to one change the value of the next input?

how can i one to one change the value of the next input?
this code doing check all or unchec all, but i want to check or uncheck one to one,
jQuery(document).ready(function() {
jQuery('#topluekle').click(function() {
if(jQuery(this).attr('checked')) {
jQuery('input:checkbox').attr('checked',true);
jQuery('input:text').attr('value','E');
} else {
jQuery('input:checkbox').attr('checked',false);
jQuery('input:text').attr('value','H');
}
});
});
Sample code:
<form>
<? for($i=1;$i<=5;$i++) { ?>
<input type="checkbox" id="pgun[]" name="pgun[]">
<input size="1" type="text" name="degerler[]" id="degerler[]" value="H">
<br />
<? } ?>
<label class="checkbox">
<input type="checkbox" value="E" name="topluekle" id="topluekle">
Check / Uncheck All *
</label>
</form>
Try
jQuery(function ($) {
$('#topluekle').click(function () {
$('input[name="pgun[]"]').prop('checked', this.checked);
$('input[name="degerler[]"]').val(this.checked ? 'E' : 'H');
});
});
Use val() like,
jQuery('input:text').val('H');
and use prop() in place of attr() like
jQuery(document).ready(function() {
jQuery('#topluekle').click(function() {
if(jQuery(this).prop('checked')) {
jQuery('input:checkbox').prop('checked',true);
jQuery('input:text').val('E');
} else {
jQuery('input:checkbox').prop('checked',false);
jQuery('input:text').val('H');
}
});
});
If you want to change value for each checkbox click then you can try,
jQuery(document).ready(function() {
jQuery('input[name="pgun[]"]').click(function() {
var newVal=$(this).next('input:text').val()=='E' ? 'H' : 'E';
$(this).next('input:text').val(newVal);
});
});
It will change corresponding text box's value of checkbox
jQuery(document).ready(function() {
var txtObj = $('input:text');
jQuery('input:checkbox').each(function(i){
jQuery(this).click(function(){
if(jQuery(this).attr('checked')) {
$(txtObj[i]).val("E");
} else {
$(txtObj[i]).val("H");
}
});
});
});

how to get session values to textbox when checkbox is clicked in jquery

I'm having two pages with similar textboxes when user inserts data into first page and goes to next page, if he need to give same data am adding a checkbox, when user clicks it same data which is in session from before page has to be get into the second page variables through ajax. can someone help me please. thanks
Response for the Comment
I made sample code which will give you idea about how to can do this.
jQuery Code for checkbox change event
$(function(){
$('input:checkbox').change(function(){
if($(this).is(':checked'))
{
$.ajax({
url : 'script.php',
success : function(session)
{
$('input:text').val(session);
}
});
}
});
});
HTML
<input type="text" />
<input type="checkbox" />
script.php
<?php
session_start();
echo $_SESSION['name_of_the_session_variable'];
exit;
?>
EDIT
$("#checked").click(function()
{
if ($(this).is(':checked'))
{
$('#provisional_total_public_funding').val(<?php echo empty($this->session->store['actual_info']['actual_total_public_funding']) ? '' : $this->session->store['actual_info']['actual_total_public_funding']; ?>);
}
});
Ajax Request Response
<select name="fin_year" id="fin_year">
<option value="" >Please select an year</option>
<option value="<?= $actFinYr; ?>"><?= $actFinYr; ?></option>
</select>
<script type="text/javascript">
$(function(){
$('#fin_year').change(function()
{
var options = $(this);
if(options.val() != '')
{
$.ajax(
{
url : 'CODEIGNITER_HTTP_URL/'+options.val(),
beforeSend : function()
{
//show loading
},
success : function(response)
{
//play with the response from server.
}
});
}
});
});
</script>
I'd use jQuery like this:
HTML 1st page:
input1 <input type="text" id="input1" name="input1"/>
input2 <input type="text" id="input2" name="input2"/>
jQuery 1st page:
$input1 = $("#input1");
$input2 = $("#input2");
$input1.keydown(function(){
$.post("yourPHP.php", {input1: $input1.val()});
});
$input2.keydown(function(){
$.post("yourPHP.php", {input1: $input1.val()});
});
PHP 1st page:
if(session_id() == '') {
session_start();
}
if(isset($_POST['input1'])){
$_SESSION['input1'] = $_POST['input1'];
}
if(isset($_POST['input2'])){
$_SESSION['input2'] = $_POST['input2'];
}
HTML 2nd page:
input1 <input type="text" id="input1" name="input1"/>
input2 <input type="text" id="input2" name="input2"/>
<br/>
radio1 <input type="radio" id="radio1" name="radio"/>
radio2 <input type="radio" id="radio2" name="radio"/>
jQuery second page:
$input1 = $("#input1");
$input2 = $("#input2");
$radio1 = $("#radio1");
$radio2 = $("#radio2");
$radio.click(function(){
$.post("yourPHP.php", {request: "input1"}, function(data){
$input1.val(data);
});
});
$input2.keydown(function(){
$.post("yourPHP.php", {request: "input2"}, function(data){
$input2.val(data);
});
});
PHP 2nd page:
if(session_id() == '') {
session_start();
}
if(isset($_POST['request'])){
switch($POST['request']){
case 'input1':
echo $_SESSION['input1'];
break;
case 'input2':
echo $_SESSION['input2'];
break;
}
}
I hope it works.

Can I use PHP value in JavaScript?

I’m using below a simple Jquery code to call a PHP page and get the button information back in a div:
<head>
<script>
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
myPHPfile.php
<?php
if( $_REQUEST["selectedButtonValue"] )
{
$buttonPHP = $_REQUEST['selectedButtonValue'];
echo "Value button is ". $buttonPHP;
}
?>
How can I get the PHP information inside JavaScript, as follows:
alert(<?php echo('buttonPHP'); ?>);
Note: The following code shows the alert box message, but I can’t use it since I need the $buttonPHP value:
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue}, function(data){ alert(data); });
I’ve tried $_SESSION in myPHPfile.php, and also all jQuery AJAX functions: load(), get(), post() and the ajax() method, none of them is giving the PHP value inside JavaScript.
I looked all over but I couldn’t find an answer.
You would be better with an $.ajax request. Don't echo the 'Value of button is' part, just echo the actual value. For example:
$.ajax({
url: "myPHPfile.php",
context: document.body
}).done(function(data) {
var buttonValue = data;
// Whatever you want to do with the data goes here.
});
See the jQuery docs http://api.jquery.com/jQuery.ajax/
Alternatively, if you are generating the page with PHP, just echo the PHP variable into the JavaScript
<script>
...
var buttonValue = "<?php echo $buttonPHP; ?>";
...
</script>
Encode it in JSON instead of trying to echo the data :
<?php
if( $_GET["selectedButtonValue"] )
{
$buttonPHP = $_GET['selectedButtonValue'];
header('Content-Type: application/json');
echo json_encode($buttonPHP);
}
?>
Then use jquery get json to grab the data
$.get('myPHPfile.php?selectedButtonValue='+buttonvalue, function(data){
console.log(data);
});
Try:
alert('<?php echo $buttonPHP; ?>');
As a temporary solution, you could quickly merge both into a dirty code like this:
index.php:
<?php
$buttonPHP = "10"; //Set up your default button variable
if( $_REQUEST["selectedButtonValue"] == 10 )
{
echo "Selected button value: 10"; //You can also print $_REQUEST["selectedButtonValue"] here directly, but what's the point if you can select it from DOM through jQuery?
exit;
} else if ($_REQUEST["selectedButtonValue"] == 20) {
echo "Selected button value: 20";
exit;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = <?php echo $buttonPHP ?>; //Duplicate default value from PHP to JS
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
</html>
index.php rendered in browser:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = 10; //Duplicate default value from PHP to JS
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
</html>
EDIT: Stored session
<?php
session_start();
if (isset($_REQUEST['selectedButtonValue'])) {
$_SESSION['selectedButtonValue'] = $_REQUEST['selectedButtonValue'];
echo $_REQUEST['selectedButtonValue'];
exit;
} else if (!isset($_SESSION['selectedButtonValue'])) {
$_SESSION['selectedButtonValue'] = 10;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = <?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?>;
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv"><?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?></div>
</body>
</html>
Also make sure you filter the $_REQUEST variable, because as of now, it will print anything. See http://en.wikipedia.org/wiki/Cross-site_scripting for details.

Categories