I have a function that is supossed to send data to a php file..although i get an alert that shows the correct ID and a success message, when trying to echo it out in my process.php, nothing is showed..the function is in adopt.php, the file that refers to process.php:
<script type="text/javascript">
$(function(){
$('#loginform').submit(function(e){
return false;
});
<?php
$q = pg_query($conn, "SELECT * FROM caini_donati");
while($res = pg_fetch_assoc($q)){ ?>
$('#<?php echo $res['id_caine']; ?>').leanModal({ top: 110, overlay: 0.45, closeButton: ".hidemodal" });
$("#<?php echo $res['id_caine']?>").click(function(event) {
var id_caine = event.currentTarget.id;
alert(id_caine);
$.ajax({
type: 'POST',
url: 'process.php',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: { id_caine : id_caine},
success: function(data){
alert("succes"),
console.log(data);
}, error: function(xhr, ajaxOptions, thrownError) {alert ("Error:" + xhr.responseText + " - " + thrownError );}
});
});
<?php } ?>
});
</script>
in process.php i have:
<?php
$var = $_POST['id_caine'];
echo "tr1: ".$_POST['id_caine'];
echo "try: ".$var;
?>
Does anyone know what I'm doing wrong? In process.php i want to run an update query based on the 'id_caine' variable..Any ideea is apreciated..Not important but I have altmost no knowledge about ajax.
RiggsFolly is correct, you are missing the javascript html tags, i have tweaked your code to show you where they should be. Also i corrected the success method so that you actually had a variable to work with. You defined rs as the parameter but then tried to use "data" instead.
<?php
$q = pg_query($conn, "SELECT * FROM caini_donati");
while($res = pg_fetch_assoc($q)){ ?>
<script type="text/javascript">
$('#<?php echo $res['id_caine']; ?>').leanModal({ top: 110, overlay: 0.45, closeButton: ".hidemodal" });
$("#<?php echo $res['id_caine']?>").click(function(event) {
var id_caine = event.currentTarget.id;
alert(id_caine);
$.ajax({
url: 'process.php',
type: 'POST',
data: { id_caine : id_caine},
dataType: 'html',
success: function(data){
alert("succes"),
console.log(data);
}, error: function(xhr, ajaxOptions, thrownError) {alert ("Error:" + xhr.responseText + " - " + thrownError );}
});
});
</script>
<?php } ?>
Related
I am getting error in Ajax by using the method post and getting the total attendance between two dates of the selected person.
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(event){
event.preventDefault();
var fromdate = $("#fromDate").val();
var todate = $("#toDate").val();
var dep = $("#dep").val();
$.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" +"index.php/Ajaxcontroller/getAttendence",
dataType: 'json',
data: {from: fromdate, to: todate,dep:dep},
cache:false,
success: function(result) {
$("#row2").html(result);
},
error: function() {
alert("error");
}
});
});
});
</script>
Please help me to resolve this error.
**this is my controller..**
public function getAttendence()
{
if($this->input->post() && $this->input->is_ajax_request()){
$credentials=array(
'from' => $this->input->post('from'),
'to' = $this->input->post('to'),
'dep' => $this->input->post('dep')
);
$this->load->model('Ajaxmodel');
if($this->Ajaxmodel->selectAttendence($credentials)){
$data['result']=$this->Ajaxmodel->selectAttendence($credentials);
echo json_encode($data);
}
}
else{
$this->load->view('Salarycontrol');
}
}
Edit your code as
data: {'from': fromdate, 'to': todate, 'dep':dep}
If still getting error please elaborate the error exactly you are getting
I am asking for help with my code. I am trying to get values then send it to php script through ajax by jquery. I can get the values but I don't know what's wrong with it. Your help is appreciated :)
Ajax:
$(".Qty").submit(function(e){
data_form = parseInt($(this).find(".buyQty").val());
id = parseInt($(this).attr('name'));
console.log("id :", id, "Quantity: ", data_form);
$(this).find(".addCart").val('Adding...');
$.ajax({
url: "php/cart_process.php",
type: "POST",
data: {'id': id, 'qty': data_form},
success: function(data){
$("#cart-info").html(data.items);
$(".Qty").find(".addCart").val('Add to Cart');
alert("Item added to Cart!");
if($(".shopping-cart-box").css("display") == "block"){
$(".cart-box").trigger( "click" );
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
e.preventDefault();
});
php:
<?php
if(isset($_POST['id'])){
$id = $_POST['id'];
echo "<script>console.log('id received: " .$id. "' );</script>";
}
?>
Your php script isn't returning a JSON object like your JS expects.
Your JS expects data to be a JSON object and you are trying to get the value in the index items. E.G data.items
Try this.
PHP
<?php
if(isset($_POST['id'])){
$output = array();
$id = $_POST['id'];
$output['items'] = "<p>id received: {$id} </p>";
echo json_encode($output);
}
?>
JQuery
$(".Qty").submit(function(e){
data_form = parseInt($(this).find(".buyQty").val());
id = parseInt($(this).attr('name'));
console.log("id :", id, "Quantity: ", data_form);
$(this).find(".addCart").val('Adding...');
$.ajax({
url: "php/cart_process.php",
type: "POST",
data: {'id': id, 'qty': data_form},
success: function(data){
console.log('raw data:');
console.log(data);
$("#cart-info").html(data.items);
$(".Qty").find(".addCart").val('Add to Cart');
alert("Item added to Cart!");
if($(".shopping-cart-box").css("display") == "block"){
$(".cart-box").trigger( "click" );
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
e.preventDefault();
});
I've created array of json objects as
var jsnObjs = [{"key": 0, "data": 1}, {"key": 1, "data": 2}];
Output of console.log(jsnObjs) in chrome is as under
(2) [Object, Object]
0: Object key: 0 data: 1 proto: Object
1: Object key: 1 data: 2 proto: Object
length: 2
proto: Array(0)
also the success:function (given below) shows data transmitted successfully. But the on var_dump(jsnos) in the php file I get Array (size=0).
function doAjaxRequest(jsnObjs) {
jq.ajax({
url: "viewajaxdata.php",
type: "post",
data: {jsnos : jsnObjs},
contentType: "application/x-www-form-urlencoded",
success: function (response) {
alert("Ajax Transmitted successfully");
},
error: function (request, status, error) {
alert("Error: data tranmission failed !\n" + error);
}
});
}
The viewajaxdata.php file is :
<?php
ini_set("display_errors", "On");
var_dump($_POST);
$ajaxadata = json_decode(stripslashes($_POST['jsnos']), true);
$n = count($ajaxdata);
echo $n;
?>
Could anybody please throw some light as to where I'm going wrong.
You can use below code it will works
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jsnObjs = [{"key":0, "data":1}, {"key":1, "data":2}];
function doAjaxRequest(jsnObjs) {
$.ajax({
url: "viewajaxdata.php",
type: "post",
data: {jsnos : jsnObjs},
contentType: 'application/x-www-form-urlencoded',
success: function(response) {
alert(response);
alert("Ajax Transmitted successfully");
},
error: function(request, status, error) {
alert("Error: data tranmission failed !\n" + error);
}
});
}
doAjaxRequest(jsnObjs);
</script>
viewajaxdata.php
<?php
$n = count($_POST['jsnos']);
echo $n;
?>
Friends, finally I could solve the issue. I made following changes in javascript
data: {"jsnos" : JSON.stringify(jsnObjs)},
removed contentType: 'application/x-www-form-urlencoded',
function doAjaxRequest(jsnObjs) {
jq.ajax({
url: "viewajaxdata.php",
type: "post",
data: {"jsnos" : JSON.stringify(jsnObjs)},
success: function(response) {
alert(response);
alert("Ajax Transmitted successfully");
},
error: function(request, status, error) {
alert("Error: data tranmission failed !\n" + error);
}
});
}
Then in my viewajaxdata.php I wrote the following
<!DOCTYPE html>
<html>
<head>
<title>Send json by ajax to php</title>
</head>
<body>
<?php
if (isset($_POST['jsnos'])) {
var_dump($_POST['jsnos']);
$objs = json_decode($_POST['jsnos']);
echo 'K=' . $objs[0]->key . ' data=' . $objs[0]->keysdata;
}
?>
</body>
</html>
The alert(response); show the following (the html markups are omitted here)
K=0 data=1
Now, to solve my problem ahead, I shall write the success function as
success: function() {
alert("Ajax Transmitted successfully");
}
Then I shall code the php file to dynamically generate html form for editing the data values. Hope I shall be able to complete the problem.
Finding place when enter pincode using ajax php. But it doesn't work properly. When we enter each pincode that pincode is checked and then result of that place is displayed .
<label for="pincode">Pin-Code:</label>
<input name="pincode" type="text" class="text" id="pincode" />
<div id="section1"></div>
I am setting this section as input fields.
<script>
$(document).ready(function() {
$('#pincode').keyup(function() {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) { console.log(data.success);
if(data.success){
$.each(data.results[0].address_components, function(index, val){
console.log(index+"::"+val.long_name);
$('#section1').append( val.long_name+'<br>');
});
}
},
});
});
});
</script>
This is ajax section for send data to pincode_check.php.
I am doing pincode_check.php look like below. Here passing value retrive in $pincode variable then using maps.google.com to find logitude of that place. Then find corresponding place. That place name display in below the form field. But it does not worked properly.
<?php
$pincode=$_REQUEST['pincode'];
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$pincode.'&sensor=false');
$response= json_decode($geocode); //Store values in variable
$lat = $response->results[0]->geometry->location->lat; //Returns Latitude
$long = $response->results[0]->geometry->location->lng; // Returns Longitude
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$long.'&sensor=false');
$data= json_decode($geocode);
if($data==true)
{ // Check if address is available or not
$data->results[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
?>
Try this, In your ajax response success object was missed. I have rewritten the code,
also, pincode_check.php
if($data==true)
{ // Check if address is available or not
$data->result[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
In HTML: should be (Remove # in html id element)
<div id="section1"></div>
instead of
<div id="#section1"></div>
UPDATE:
<script>
$(document).ready(function() {
$('#pincode').keyup(function() {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) { console.log(data.success);
if(data.success){
$.each(data.results[0].address_components, function(index, val){
console.log(index+"::"+val.long_name);
$('#section1').append( val.long_name+'<br>');
});
}
},
});
});
});
</script>
HTML:
<label for="pincode">Pin-Code:</label>
<input name="pincode" type="text" class="text" id="pincode" />
<div id="section1"></div>
PHP code
<?php
$pincode=$_REQUEST['pincode'];
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$pincode.'&sensor=false');
$response= json_decode($geocode); //Store values in variable
$lat = $response->results[0]->geometry->location->lat; //Returns Latitude
$long = $response->results[0]->geometry->location->lng; // Returns Longitude
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$long.'&sensor=false');
$data= json_decode($geocode);
if($data==true)
{ // Check if address is available or not
$data->result[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
?>
Try this which has a ready handler
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#pincode').live('change', function() {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) {
if(data.success ==true){
$('#section1').html(data.address_components);
}
},
});
});
});
</script>
Debug your script.
Are you getting data in your $pincode variable?
var_dump($pincode);
I prefer use a defined method in the ajax request, like post:
$.ajax({
url: "pincode_check.php",
method: 'POST'
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) {
if(data.success ==true){
$('#section1').html(data.address_components);
}
},
});
Your success function has already the response, there is no need to use the conditional:
if(data.success ==true){
$('#section1').html(data.address_components);
}
Try to debug it to know what data are you recieving:
success: function(data) {
console.log(data);
}
},
im trying to check if a username a user wants is already taken without having to send the form, basically onBlur of the username field.
I'm having some trouble and have a few questions.
I have my input field plus js:
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#username').on('blur', checkdb);
function checkdb(){
var desiredUsername = $(this).val();
$.ajaxSetup({
url: "check-db.php",
type: "POST",
});
$.ajax({
data: 'desiredUsername='+desiredUsername,
success: function (msg) {
alert (msg);},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert('Error submitting request.');
}
});
}
});
</script>
<input type="text" name="username" id="username">
and my check-db.php file:
$mysqli = mysqli_connect("localhost","connection info");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$desiredUsername = $_POST['desiredUsername'];
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = '?' ");
$stmt->bind_param('s', $desiredUsername);
$stmt->execute();
firstly: im getting an error from my php code, 'number of variables doesnt match number of parameters in prepared statement', which im a bit confused about? I have 1 variable and 1 peramater, don't i?
then, once this is actually working, how do I send a message/ variable back to the input page? so if the username is taken I can say so, or if its available say so?
thanks!
On the server size (PHP in your case), simply echo the things you want to pass to the client side (Javascript) like this :
echo json_encode($datas); //can be array or whatever
Then on the Client side :
$.ajax({
method: 'POST',
dataType:'json',
data: {'username' : desiredUsername}, //then getting $_POST['username']
success: function(datas) {
console.log(datas); //Your previous data from the server side
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus);
}
});
try
function checkdb(){
var desiredUsername = $(this).val();
$.ajaxSetup({
url: "check-db.php",
type: "POST",
});
$.ajax({
data: {
desiredUsername: desiredUsername
},
success: function (msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert('Error submitting request.');
}
});
}
You have an error when sending the data, you should send a JS Object as data, like this:
data: { desiredUsername: desiredUsername },