Below is my ajax file. Here I passed all my text box values.
And I post that values to edu.php. There I want to update two tables like details and test.
But nothing is updating in my database.While I checked the value with var_dump the string seems to be empty.But while passing from ajax I checked it with an alert it shows all the values in text box. So I believe problem is happening while posting from ajax to php.
AJAX Code
$('#edubackgroundsubmit').click(function (event) {
event.preventDefault();
alert("Hello");
var per_email = $('#per_email').val();
var master_overall = $('#master_overall').val();
var master_pass_year = $('#master_pass_year').val();
var master_college = $('#master_college').val();
var master_univ = $('#master_univ').val();
var data1 ="master_qual="+master_qual+"&master_overall="
+master_overall+"&master_pass_year="+master_pass_year+"&master_college="+master_college+"&master_univ="+master_univ
+"&edu_flag="+edu_flag;
alert(data1);
$.ajax({
type:"POST",
url: "edu.php?per_mobile="+per_mobile,
dataString1: data1
}).done(function( dataString1 )
{
alert(dataString1);
$('#edu_alert').append(
'<div class="alert alert-success text-center">' +
'<button type="button" class="close" data-dismiss="alert">' +
'×</button>' + dataString1 + '</div>');
});
});
PHP File
if (isset($_POST['pass_year_12'])) {
$pass_year_12 = $_POST['pass_year_12'];
} else {
$pass_year_12 = "";
}
$l1 = "UPDATE test
SET edu_flag='$edu_flag'
WHERE per_mobile='$per_mobile'";
$l2 = "UPDATE details
SET master_qual='$master_qual',
master_overall='$master_overall',
master_pass_year ='$master_pass_year ',
master_college='$master_college'
WHERE per_mobile='$per_mobile'";
$exec = mysqli_query($link, $l1);
if (mysqli_query($link, $l2)) {
echo "Education Details Updated Successfully";
} else {
echo "Error updating record: " . mysqli_error($link);
}
This is wrong. What's this bit:
dataString1: data1
You need to change it as:
data: data1
The function $.ajax() POSTs only those given in the data attribute.
Problem with your code is hat you are sending the data at edu.php?per_mobile
so you need to add isset condition before the code... like this
if(isset($_REQUEST['per_mobile'])){ //write your code here }
and also replace datastring to data.
and then try.
Hope it may help.
For instance you can also use jQuery get or post method, that is more reliable and easy to learn.
Related
Here is my little script code I want to get data from codeingiter controller. I get json data from controller to view ajax, but It print with html page code.
any one can help me here, How can I solve this.
I only want to get json data ans a variable data to my page.
this is output that I am getting but this is comming with html code and I don't want html code.
[{"id":"1","p_name":"t_t11","p_type":"t_t1","paid_type":"0"},{"id":"2","p_name":"t_t12","p_type":"t_t1","paid_type":"1"},{"id":"3","p_name":"t_t1","p_type":"t_t1","paid_type":"0"}]
I have follow some question answers but can't et success, because that question's answers not related to me.
Link 1
Link 2 and many more...
<script>
$("a.tablinks").on('click',function(e){
e.preventDefault();
var p_name = $(this).attr('value');
alert(p_name);
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'text',
type: "POST",
data:{p_name : p_name},
success : function(data){
alert(data);
if(data !=""){
var obj = JSON.parse(data);
alert(obj.id);
/*$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});*/
}else{
alert(data+ '1');
}
},
error : function(data){
//var da = JSON.parse(data);
alert(data+ '2');
//alert(da+ '2 da ');
}
});
});
</script>
Here is controller code.
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
echo json_encode($query['res']);
$this->load->view('teq', $tabs_data);
}
You added view at the end of your function that return view's code.
Remove line:
$this->load->view('teq', $tabs_data);
You can either use
if ($this->input->is_ajax_request()) {
echo json_encode($data_set);
}else{
//Procced with your load view
}
Or if you're avoiding ajax request check then please pass any extra paramter from your ajax call then then check for its existence at your controller and on behalf of it proceed your conditional statement . it will solve your problem
Change your controller method like this:
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
// if ajax request
if ($this->input->is_ajax_request()) {
echo json_encode($query['res']);
return; // exit function
}
$this->load->view('teq', $tabs_data);
}
In your ajax code chage dataType: to json
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'json',
type: "POST",
data:{p_name : p_name},
success : function(res)
{
if(res !=""){
alert(res.id);
}else{
alert(res+ '1');
}
}
});
And in your controller
public function gettabdata()
{
if($this->input->post('p_name'))
{
$p_name = $this->input->post('p_name');
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
if($query['res'])
{
$resp = $query['res'];
}
else
{
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
}
else
{
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
$this->load->view('teq', $tabs_data);
}
}
Hope this helps :)
I hope it's ok to ask this here. I have searched everywhere, but can't find a solution.
I've found a nice js library called jTinder at https://github.com/do-web/jTinder
Now I am trying to save likes or dislikes in a mysql database and php. But soon I will give up! I've tried a lots of different code, but nothing really happens.
Mostly I crasch the script from working at all.
Can someone help me?
$("#tinderslide").jTinder({
// dislike callback
onDislike: function (item) {
// set the status text
$('#status').html('Dislike image ' + (item.index()+1));
},
// like callback
onLike: function (item) {
// set the status text
$('#status').html('Like image ' + (item.index()+1));
},
animationRevertSpeed: 200,
animationSpeed: 400,
threshold: 1,
likeSelector: '.like',
dislikeSelector: '.dislike'
});
getdata.php looks like this:
$link = mysqli_connect("127.0.0.1", "root", "", "vacation");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$liked = mysqli_real_escape_string($link, $_POST['like']);
$sql = "INSERT INTO destinations (like) VALUES ('$liked')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
Ajax:
$.ajax({
url: 'getdata.php',
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
var count = data[3];
$('#output').html('like('+id+')');
}
There a are many problem in this code so
In your html file where is data coming from in ajax while you are not returning anything in you php code. So your code sholud be somthing like the for test
$("#tinderslide").jTinder({
// dislike callback
onDislike: function (item) {
$.ajax({
url: 'getdata.php',
data: 'DATA_YOU_WANT_TO_SEND',
dataType: 'json',
success: function (data) {
console.log()
//$('#output').html('like(' + id + ')');
}
});
// set the status text
$('#status').html('Dislike image ' + (item.index()+1));
},
// like callback
onLike: function (item) {
// set the status text
$('#status').html('Like image ' + (item.index()+1));
},
animationRevertSpeed: 200,
animationSpeed: 400,
threshold: 1,
likeSelector: '.like',
dislikeSelector: '.dislike'
});
And in php code
You are inserting like into it how do you get a post data in the php file if you are not sending it from the ajax so put data to it.
I have a form which submits it to the database using JQuery, AJAX and PHP. The problem is, whenever I click the submit button of the form, the JavaScript alert says that the record (data from the form) has successfully recorded (to the database). I would then check my database but the data is not recorded, leaving the database empty and no changes at all. My question is, there something wrong with the script? Or with the PHP code?
Here's the script addnew.js:
$(document).ready(function() {
$("#submit").click(function() {
var transMonth = $("#transMonth").val();
var transDay = $("#transDay").val();
var transYear = $("#transYear").val();
var voucherNum = $("#voucherNum").val();
var expType = $("#expType").val();
var acctsPayable = $("#acctsPayable").val();
var amount = $("#amount").val();
var dataString = 'transMonth1='+ transMonth + 'transDay1='+ transDay + 'transYear1='+ transYear + 'voucherNum1='+ voucherNum + 'expType1='+ expType + 'acctsPayable1='+ acctsPayable + 'amount1='+ amount;
if(voucherNum=='') {
alert("Please fill a valid voucher number.");
}
else {
$.ajax ({
type: "POST",
url: "addnew.php",
data: dataString,
cache: false,
success: function(result) {
alert(result);
}
});
}
return false;
});
});
Here's the PHP code addnew.php:
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("mydb", $connection);
//fetch values
$transMonth2 = $_POST['transMonth1'];
$transDay2 = $_POST['transDay1'];
$transYear2 = $_POST['transYear1'];
$voucherNum2 = $_POST['voucherNum1'];
$expType2 = $_POST['expType1'];
$acctsPayable2 = $_POST['acctsPayable1'];
$amount2 = $_POST['amount1'];
//query
$query = mysql_query("insert into anotherSample(transMonth, transDay, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
echo "Record added successfully";
mysql_close($connection);
I think your dataString in addnew.js should be transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='...,
otherwise the $transDay2,$transYear2..would be null, if your transDay or more set NOT NULL in mysql, there will occur a mysql error. :)
You should check returned result. You can do this by the following code:
$result = mysql_query("insert into anotherSample(transMonth, transDay, transMonth, transYear, voucherNum, expenseType, acctPayable, amount) values ('$transMonth2', '$transDay2', '$transYear2', '$voucherNum2', '$expType2', 'acctsPayable2', '$amount2')");
if (!$result) {
die('Invalid query: ' . mysql_error()); // only for development, in production you shouldn't print error to client!
}
echo "Record added successfully";
mysql_close($connection);
PS. Also, I advice you to read about SQL-injections, because your code is vulnerable.
I see a problem in insert statement, insert into anotherSample(transMonth, transDay, transMonth, transYear,....) values ('$transMonth2', '$transDay2', '$transYear2, .....) 'transMonth' is repeated twice and eight columns with seven values.
In your addnew.js file you should use an ampersand (&) between each key/value pair like this:
var dataString = 'transMonth1='+ transMonth + '&transDay1='+ transDay + '&transYear1='+ transYear + '&voucherNum1='+ voucherNum + '&expType1='+ expType + '&acctsPayable1='+ acctsPayable + '&amount1='+ amount;
This way you will ensure that each variable will have a value when you are reading them in your addnew.php file.
Check fetched values in addnew.php
and echo mysql_error($connection) to check if mysql error was occurred.
Possibly someone asked question like as my question. But, I can't find any solution.
ProfileEditor.php (controller)
method 1:
public function modify_personal_information() {
$this->data['userinfo'] = $this->personal_information_of_mine($userid);
$this->load->view('layouts/header', $this->data);
$this->load->view('profile/personalinformation', $this->data);
$this->load->view('layouts/footer', $this->data);
}
method 2:
public function check_url_if_exists() {
$newportalurl = $this->uri->segment(2);
$this->results = $this->profile_model->checknewportalurl($newportalurl);
if ($this->results == 1) {
$this->status['status'] = 1;
$this->status['msg'] = 'This name is available. Thanks.';
} else {
$this->status['status'] = 0;
$this->status['msg'] = 'This name is not available. See suggestions.';
}
$this->load->view('profile/layouts/availiability', $this->status);
//or echo json_encode($this->status);
}
profile/personalinformation.php (views)
a form with <div id="urlsuggestions"></div>
profile/layouts/availiability.php (views)
where i am printing the message which i am getting from the check_url() function
ajax.js (ajax)
$('#newportalurl').blur(function() {
var fval = $(this).val();
var ifexists = fval.toLowerCase().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
$.ajax(baseurl + "check/"+ifexists, function(data) {
//i tried following things
//alert(window.location);
//$('#msgbox').html(data.msg).show().addClass('alert-success').delay(2000).fadeOut();
//$('#urlsuggestions').load(window.location + 'modifypersonalinformation #urlsuggestions');
});
});
Now, I am trying to load the message to personalinformation view. What I am doing wrong or what will be the procedure to do it? I actually want to know the process how codeigniter handle them.
Please try like this, im not able to get response from your metod.
$.ajax({
url: "<?= base_url("check/") ?>"+ifexists,
success: function (data) {
$("#urlsuggestions").html(data);// if you want to replace the data in div, use .html()
or if you want to append the data user .append()
}
});
I've been struggeling with this problem for a while now and I still can't understand why it's not working. I've tried multiple possibilites but none of them worked, so can someone please help me with how to pass var superstr = $( "#savelyric" ).text(); through Ajax and into my database? This is what I've been experimenting with:
function saveinPHP() {
//alert("Came here");
var lyr = $( "#savelyric" ).text();
var superstr = { lyricsave:lyr }
//var superstr = 'lol';
//var hashString = "lol";
//var data = { yoururl:'hmm'}
$.ajax({
type: "POST",
url: "includes/sendlyrics.php",
data: superstr,
success: function(data){
alert("***DATA***"+data+"***MSG***");
alert("Settings has been updated successfully." + data + "~~~" + hashString);
//window.location.reload(true);
}
});
}
And as you can see, I've tried with multiple ways of doing it, but it just never works. I don't understand how on earth you do this. And the PHP file goes like this:
<?php
include ('db_connect.php');
$data = $_POST['data'];
$query = "UPDATE song SET time='".$data."' WHERE id='1'";
mysqli_query($query);
?>
And yes, I'm fully aware that my database is vulnerable for SQL injections, and I will fix that as soon as I get this working.
This is what I've tried, but I can do things completely different if you think that is necessary.
Right now I got the JS:
function saveinPHP() {
var superstr = $( "#savelyric" ).text();
$.ajax({
type: "POST",
url: "includes/sendlyrics.php",
data: {superstr: superstr},
success: function(data){
alert("***DATA***"+data+"***MSG***");
alert("Settings has been updated successfully." + data + "~~~");
//window.location.reload(true);
}
});
And PHP
<?php
include ('db_connect.php');
$data = $_POST['superstr'];
$query = "UPDATE song SET lyrtime='".$data."' WHERE id='1'";
mysqli_query($query);
?>
Only change this line:
var superstr = { lyricsave:lyr }
with
var superstr = { data:lyr }
You are trying to pass var superstr = $( "#savelyric" ).text(); as your question states, but in your code you are actually assigning:
var superstr = { lyricsave:lyr }
Change it to:
var superstr = $( "#savelyric" ).text();
UPDATE (per Kevin B's comment)
You also need to change the following:
data: {superstr: superstr},
and in your PHP:
$data = $_POST['superstr'];
Also, why are you tring to set it to the time column? I have not seen your tables, but a wild guess will tell me that time is a different datatype (TIMESTAMP/DATETIME maybe?) and is rejecting your data. Don't you want to set it to a column named data or lyrics or anything which contains text?