jQuery for Updating Database table entry using PHP. after ajax code is not working for me please help.
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var allottedValue = $(this).parent().find('input').val();
alert('Row id = ' + rowID + ' Enrollment no = ' + allottedValue);
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
// After this line it is not working
$.ajax({
type: "POST",
url: "request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
$(this).parents(".success1").replaceWith(html);
}
});
//$(this).parents(".success1").animate({backgroundColor: "#003"}, "slow").animate({opacity: "hide"}, "slow");
});
// HTML to Show Multiple Inputbox for multiple upload with link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dynamic-table">
<div class="success1">
<input name="enrollNo" type="text" value="" class="postEnroll"/>
<br/>
Allot Enrollment No
</div>
</div>
You are trying to replace with parent, it must be child. Use below code
success: function (html) {
$("#dynamic-table .success1").replaceWith(html);
}
OR
success: function (html) {
$("#dynamic-table").find(".success1").replaceWith(html);
}
This code works great i have used similar.... try this one..
function FormSubmit() {
$.ajax(
type: "POST",
url: 'success1.php',
data: $("#attend_data").serialize(),
async: false
}).done(function( data ) {
$("#attend_response").html(data);
});
}
I have updated your code snippet below... tested offline and the code is working:
A few pointers:
Instead of this: request/allot_enrollmentNo_gov.php
Try this: /request/allot_enrollmentNo_gov.php
Notice the forward slash ( / ) This indicate that the Ajax path must start from the root directory depending on your server settings.
Use this: $(".success1").html(html); instead of $(this).parents(".success1").replaceWith(html);
Working code below:
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var allottedValue = $(this).parent().find('input').val();
alert('Row id = ' + rowID + ' Enrollment no = ' + allottedValue);
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
// After this line it is not working
$.ajax({
type: "POST",
url: "/request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
$(".success1").html(html);
alert('Response from the POST page = ' + html + ');
}
});
//$(this).parents(".success1").animate({backgroundColor: "#003"}, "slow").animate({opacity: "hide"}, "slow");
});
// HTML to Show Multiple Inputbox for multiple upload with link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dynamic-table">
<div class="success1">
<input name="enrollNo" type="text" value="" class="postEnroll"/>
<br/>
Allot Enrollment No
</div>
</div>
Now it is working Perfectly by setting parent:
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var rowParent = $(this).parent('.success1');
var allottedValue = rowParent.find('input').val();
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
$.ajax({
type: "POST",
url: "request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
rowParent.replaceWith(html);
}
});
return false;
});
Related
my problem is: I want to upload image/pdf with ajax. In my code i have multiple inputs but i do not use FormData() to pass data from input to my upload.php. All work perfect. So here for better imagine:
$('#addData').on('click', function(){
var c_zakazky = $('#c_zakazky').val();
var pozicia = $('#pozicia').val();
var p_cislo = $('#p_cislo').val();
var stav = $('#stav').val();
var tech = $('#tech').val();
var zar = $('#zar').val();
var operator = $('#op').val();
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var datum = d.getFullYear() + '-' + (month<10 ? '0' : '') + month + '-' + (day<10 ? '0' : '') + day;
//alert(dokument);
$.ajax({
url: 'add.php',
type: 'POST',
processData: false,
contentType: false,
data: {
otk: 1,
c_zakazky: c_zakazky,
pozicia: pozicia,
p_cislo: p_cislo,
stav: stav,
tech: tech,
zar: zar,
operator: operator,
datum: datum
},
success: function(data){
$('#live_data').html(data);
$('#modalInsert').modal('hide');
$('#c_zakazky').val();
$('#pozicia').val();
$('#p_cislo').val();
$('#stav').val();
$('#tech').val();
$('#zar').val();
$('#op').val();
$('#dokument').val();
fetch_data_otk();
alert(data);
}
});
});
And now if i want to iclude image to this how to do it? I tried add this:
var data = new FormData();
data.append('image', $('#image').prop('files')[0]);
console.log(data);
but when i select image/pdf and hit upload in console (data) is empty and i do not know hot to do it.
Please Try this, if you want console formdata object attributes.
// Create a test FormData object
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
// Display the key/value pairs
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
Please take a look at the sample code to save your data and image/media files to form_data and then using AJAX to save the said data in the backend
<!DOCTYPE html>
<head>
<title>Example</title>
</head>
<body>
<form enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_img" name="img_url" multiple>
</div>
<input type="button" class="btn btn-primary" name="submit" value="Submit" onclick="myfunction();">
</form>
</body>
<script>
function myfunction(){
var form_data = new FormData();
var image = document.getElementById('upload_img').files.length;
for (var x = 0; x < image; x++) {
form_data.append("image", document.getElementById('upload_img1').files[x]);
}
$.ajax({
url : 'your-backend-file-with-DB-Query.php',
method : 'POST',// OR GET
data: form_data,
dataType: 'json',
success:function(data) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
}
</script>
</html>
I unable to understand, what exactly you want but please try below code, it will submit all form elements data:
$.ajax({
type : 'POST',
url : 'url',
data : $('#form').serialize() + "&post1&post2",
success : function(){
},
error : function(){
}
}
OR
$.ajax({
url: 'url',
type: "POST",
data: new FormData(this),
success : function(){
},
error : function(){
}
});
this is what i do and works
append the formdata,
var formData = new FormData(your_form);
// for multiple files , because i need to check
new_files is class, i use because i am creating form dynamically
add dynamic data also
$.each($(".new_files"), function (i, obj) {
// console.log(obj.files);
$.each(obj.files, function (j, file) {
var max_size = 5120000;
var file_type= file.type;
var match = ["image/jpeg", "image/png", "image/jpg", "application/pdf"];
// after validation etc
// append formdata
formData.append('file[' + j + ']', file);
});
});
// if you want something else,
formData.append("id", $('#kreditornr').val());
// ajax
$.ajax({
type: "POST",
url: "url",
data: formData,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) {
// success
}
});
So thank you for help. Now it works perfect. SOLUTION:
I changed only script (php code is still same)
//pridanie udajov
$('#addData').on('click', function(){
var fileInput = document.querySelector('form input[type=file]');
var attachment = fileInput.files[0];
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var datum = d.getFullYear() + '-' + (month<10 ? '0' : '') + month + '-' + (day<10 ? '0' : '') + day;
var formData = new FormData();
formData.append('otk', 1);
formData.append('c_zakazky', $('#c_zakazky').val());
formData.append('pozicia', $('#pozicia').val());
formData.append('p_cislo', $('#p_cislo').val());
formData.append('stav', $('#stav').val());
formData.append('tech', $('#tech').val());
formData.append('zar', $('#zar').val());
formData.append('op', $('#op').val());
formData.append('datum', datum);
formData.append('image', $('#image').prop('files')[0]);
console.log(formData);
$.ajax({
url: 'add.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data){
$('#live_data').html(data);
$('#modalInsert').modal('hide');
$('#c_zakazky').val();
$('#pozicia').val();
$('#p_cislo').val();
$('#stav').val();
$('#tech').val();
$('#zar').val();
$('#op').val();
$('#dokument').val();
fetch_data_otk();
alert(data);
}
});
});
I have got this html
<div class="Likes" data-i=<?php echo $row[8];?>>
<img src="../img/like.png">
<p class="L_c"><?php echo $row[4];?></p>
</div>
And this jquery/ajax
$(".Likes").click(function() {
var i = $(this).attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
$(this).children(".L_c").html(data);
}
});
});
Connect.php
if (isset($_GET["I"]) && !isset($_GET["C"])) {
$RandS=$_GET["I"];
$query3=$con->query("SELECT id,likes FROM uploads WHERE Rand='$RandS'");
$row=$query3->fetch_row();
$IdU=$row[0];
$Likes=$row[1];
$Sel2=$con->query("SELECT id FROM likes WHERE User_id='$NameId' AND Post_id='$IdU'");
$num_rows=$Sel2->num_rows;
if ($num_rows>0) {
echo $Likes;
}else{
$query=$con->query("INSERT INTO likes (Post_id,User_id,`DATE`) VALUES('$IdU','$NameId',NOW())");
$query=$con->query("UPDATE uploads SET Likes=$Likes+1 WHERE Rand='$RandS'");
echo $Likes+1;
}
}
But it does not return anything untill i refresh the page
The this keyword inside the $.ajax methods callback is not the element, but the ajax call itself.
You have to either set context, or just store the outer this -value
$(".Likes").on('click', function() {
var me = $(this);
var i = me.attr("data-i");
$.ajax({
type: "GET",
url: '../connect.php',
data: "I=" + i,
success: function(data) {
me.find(".L_c").html(data);
}
});
});
I have data which I got from database and It's in display.php.
Then mousemove is used to display data. But the data keeps repeating when I do mouseover. This is the code to mouse move
$(line.node).mousemove(get_over_handler(country));
and this is some code in function get_over_handler(country)
function get_over_handler(country) {
return function (event) {
color_country(country, selected_color);
var country_name = $("#country_name_popup");
country_name.empty();
country_name.append("<span id='popup_country_name'> " + code_to_name[country] + "</span><table width='100%' style='border-spacing:20px;'>");
var id_dataset = $("#dataset_select").find('option:selected').attr('id');
$.ajax({
type: "POST",
url: "display.php",
data: {ibukota: country, id_dataset: id_dataset},
success: function (data) {
country_name.append(data);
}
});
My question is how to prevent repeated data I got from database?
Rewrite your function to:
function get_over_handler(country) {
return function (event) {
color_country(country, selected_color);
var id_dataset = $("#dataset_select").find('option:selected').attr('id');
$.ajax({
type: "POST",
url: "display.php",
data: {ibukota: country, id_dataset: id_dataset},
success: function (data) {
var country_name = $("#country_name_popup");
country_name.empty();
country_name.append("<span id='popup_country_name'> " + code_to_name[country] + "</span><table width='100%' style='border-spacing:20px;'>");
country_name.append(data);
}
});
}
}
I am trying to make an ajax call on click on anchor tag dynmically generated from $.each loop for a JSON response.
For Information : #records is my table and .update is the class of anchor tag in that table.
Please be informed that the table is generated dynamically.
Now the problem is that my ajax call is returning nothing even i have checked it error: but no response received. I have tried alerting my var data just before the ajax call and it worked.So the problem starts from the ajax call. Moreover, my server side code is running fine.
// Update existing customers
$("#records").on('click', ".update", function() {
var data = '?'+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data: data,
success: function(response) {
console.log(response);
}
});
});
Thanks in advance.
For reference below is the code that generates the table.
// Function to make datagrid
function getRecords() {
$.getJSON("viewcustomers.php", function(data) {
var items = [];
var xTd = '';
var xTr = '';
$.each(data, function(key, val) {
var c = 0;
var id = 0;
$.each(val, function(key1, val1) {
if (c == 0)
{
id = val1;
}
c++;
xTd += '<td>' + val1 + '</td>';
});
xTd += '<td>Edit</td>';
xTd += '<td>Delete</td>';
xTr = '<tr>' + xTd + '</tr>';
items.push(xTr);
xTd = '';
xTr = '';
});
$("#records").append(items);
});
}
Updated the server side code:
page url : localhost/hotel/viewcustomers.php
/**
* Fetch single row for the purpose of update / delete.
*/
if(isset($_GET['update'])){
$customer = new Customers;
$Id = $_GET['update'];
$customer_single = $customer->View_Single_Customer($Id);
echo json_encode($customer_single);
unset($customer);
}
This line is not used the right way var data = '?'+ $(this).attr('id');
Change it like this: var my_id = $(this).attr('id');
Then update the line data: data with data : {id:my_id}
Complete code :
$("#records").on('click', ".update", function() {
var my_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data : {id : my_id},
success: function(response) {
console.log(response);
}
});
});
Or do it like this:
$("#records").on('click', ".update", function() {
var param = '?id='+ $(this).attr('id'); /*notice that I have added "id=" */
$.ajax({
type: "GET",
url: "viewcustomers.php" + param,
/* remove the data attribute */
success: function(response) {
console.log(response);
}
});
});
Modify it as
$("#records").on('click', ".update", function() {
var request = '?id='+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php" + request,
success: function(response) {
console.log(response);
}
});
});
For some reason ajax is not sending data.
On the PHP I have this code:
if (isset($_POST['submit'])) {
echo "submit";
} else {
echo "not submit";
}
And I get not submit.
This is JS code:
$(function () {
$('#submit').click(function () {
var length = $('#number').val();
var small = $('#small').val();
var big = $('#big').val();
var number = $('#numero').val();
var special = $('#special').val();
var submit = 'submit';
var url = 'public/php/codegenerator.php';
var data = "length=" + length + "&small=" + small + "&big=" + big +
"&number=" + number + "&special=" + special + "&submit=" + submit;
$.ajax({
type: "POST",
url: url,
data: data,
success: function () {
$('#code').load(url, function () {
$(this).fadeIn(1000)
});
}
});
return false;
});
});
You can try this approach
$(function(){
$('#submit').click(function(){
//YOUR CODE
var param = {
length:length,
small:small,
big:big,
number:number,
special:special,
submit:submit
}
$.ajax({
type: "POST",
url: url,
data: param,
//EDITED LINE
success: function (data) {
$('#code').hide().html(data).fadeIn(1000);
}
});
return false;
});
});
// REVISED ANSWER
// IN YOUR PHP FILE
if (isset ($_POST['submit'])) {
echo json_encode(array('result'=>"submit"));
}
else {
echo json_encode(array('result'=>"not submit"));
}
//IN YOUR JQUERY CODE
$.ajax({
type: "post",
url: url,
data: param,
dataType:'json';
//EDITED LINE
success: function (data) {
// alert(data.result);
$('#code').hide().html(data.result).fadeIn(1000);
}
});
You are getting Not submit, because it comes from the .load() call and not from .ajax - and in the load call you just load the URL without passing any POST data. So why you are running .load inside the success callback of .ajax with the same url?