Send Ajax post request and retrieve the inserted id - javascript

I am trying to submit a form which will insert data into a mysql database which is working fine. I then would like to return the id of the new inserted row (id auto increment in mysql table) as I want to open up a modal once the form is submitted so I can provide a link which includes id as a parameter in the url.
To send the data for the form I am using the following code:
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#commentForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "SubmitData.php",
data: string,
cache: false,
success: function(result){
//alert(result);
}
});
});
});
The SubmitData.php file then inserts the form data into the database.
In the SubmitData.php I can create a variable to pick up the id of the newly inserted row like
$last_id = mysqli_insert_id($conn);
Is there a way I can return the $last_id from the SubmitData.php file within the same function?

Yes return from SubmitData.php the id using the following echo:
echo json_encode(['id'=>$last_id]);
js:
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#commentForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "SubmitData.php",
data: string,
cache: false,
success: function(result){
alert(result.id);//this will alert you the last_id
}
});
});
});

print last id in that php file
echo $last_id;
get that in ajax success function
success: function(result){
alert(result);
}

Related

How let an ajax request to read a number that is a result of an sql query

I have a very simple sql query:
case 'getFeedbackIvr':
$idClient = $_GET['idClient'];
$query = "SELECT COUNT(idClient) AS _callsNumber
FROM table
WHERE idClient = {$idClient}";
$callsNumber='_callsNumber'
First, I'm trying to understand if this:
$callsNumber='_callsNumber'
is correct
What I need is that when a field in a php form is filled, query is executed and an Ajax request reads the value in $callsNumber and if this value>0 a field (field) in a php form has to appear, else hidden if $callsNumber=0
After several attempts and searchs I'm doing this (but it's incomplete and that's why I'm making this ask):
<script>
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: "html",
url: '<?=$requestUrl?>' + "?ivrChoiceId="+$(this).val()+"&qType=getFeedbackIvr",
success: function(data){
$("?").html(data);
},
async:true
$('#field').closest('tr').hide();
if ($callsNumber>0)
{
$('#field').closest('tr').show();
}else{
$('#field').closest('tr').hide();
});
});
});
</script>

Get value from ID of AJAX-loaded content

I have javascript to get content from another page, like this :
$.get('disp/run_txt.php?type=andon&dispnm=PS&line=1',function(data){
$('#result').html(data);
});
What I want is the value of id='result' can transfer to variable, i have try :
$result = "<span id='runtxt'></span>";
echo $result;
My question is, how to capture the id='result' to variable?
Try
var resultVariable = $('#result').val(); //For non-text value
OR
var resultVariable = $('#result').text(); //For text value
If you want to pass what you have in data to some PHP code, you will have to do an ajax call to a php page.
$.get('disp/run_txt.php?type=andon&dispnm=PS&line=1',function(data){
$('#result').html(data);
var url = 'your-php-page.php';
// Will now send data to your-php-page.php
// where you can assign it to the variable
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});

send table created in one page to another page

I have created country and city as dependable menus. When I select all the dropdown values and click on the display button it should render created html table just below the display button which is illustrated in image below.
For table creation when I click on the display button it loads javascript code and sends ajax request to another php page. In this php page table is created. How can I render thus created html table in section just below the Display button.
My javascript code in index.php page is
<script type="text/javascript">
function tbl_display(){
var sel_countryid= $("sel_country").val();
var sel_cityid= $("#sel_city").val();
var dataString = 'sel_countryid='+ sel_countryid+ '&sel_cityid='+ sel_cityid;
alert(dataString);
if(sel_regionid=='' || sel_lbtype=='')
{
alert("Please enter Valid Data");
}
else
{
$.ajax({
type: "POST",
url: "tbl_create.php",
data: dataString,
cache: true,
success: function(html){
}
});
}
}
</script>
I have created table in tbl_create.php page.
How can I use thus created table to render below display button or How can I pass created html table to javascript code and render it to desired section ?
in your ajax function set the dataType to html and in it's success-function put the result out to a <div> below your form:
$.ajax({
type: "POST",
url: "tbl_create.php",
data: dataString,
dataType: "html",
cache: true,
success: function (html) {
$("#target").html(html);
}
});
html:
<!-- your form is here -->
<div id="target"></div>
you can append the return html table from tbl_create.php using the html() jquery function
so the return must be a string
$table = "<table><tr><td>THIS IS A TABLE</td><td>FIRST ROW</td></tr></table>";
return $table
if return won't work
try
echo $table
then in the success function
success: function(html){
$('#appendReturnTable').html(html);
}
that should do the trick hope it helps
Assuming that in your html page you have a div for your table like this :
<div class="myTable"></div>
Then in the success function of your ajax request try this :
//....
success: function(html){
$('.myTable').html(html)
}
//....

using ajax how to show the value after success without refreshing the page

i am adding the value to database by using ajax after adding i want to display the value in front end but now after success i am using window.location to show the data because of this the page getting refresh,i don't want to refresh the page to show the data ,anyone guide me how to do this.
below is my ajax
$(function() {
$(".supplierpriceexport_button").click(function() {
var pricefrom = $("#pricefrom").val();
var priceto = $("#priceto").val();
var tpm = $("#tpm").val();
var currency = $("#currency").val();
var dataString = 'pricefrom='+ pricefrom +'&priceto='+priceto+'&tpm='+tpm+'&currency='+currency;
if(pricefrom=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html;
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
window.location = "?action=suppliertargetpiceexport";
$("#flash").hide();
}
});
} return false;
});
});
The code that you are using to post the data needs to return some meaningful data, JSON is useful for this, but it can be HTML or other formats.
To return your response as JSON from PHP, you can use the json_encode() function:
$return_html = '<h1>Success!</h1>';
$success = "true";
json_encode("success" => $success, "html_to_show" => $return_html);
In this piece of code, you can set your dataType or JSON and return multiple values including the HTML that you want to inject into the page (DOM):
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
//Set the type of data we are expecing back
dataType: json
success: function(return_json){
// Check that the update was a success
if(return_json.success == "true")
{
// Show HTML on the page (no reload required)
$("#display").after(return_json.html_to_show);
}
else
{
// Failed to update
alert("Not a success, no update made");
}
});
You can strip out the window.location altogether, else you won't see the DOM update.
Just try to return the values that you need from the ajax function.Something like this might do.
In your insert.php
echo or return the data at the end of the function that needs to be populated into the page
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(data){
//Now you have obtained the data that was was returned from the function
//if u wish to insert the value into an input field try
$('#input_field').val(data); //now the data is pupolated in the input field
}
});
Don't use window.location = "?action=suppliertargetpiceexport";
This will redirect to the page suppliertargetpiceexport
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$('#your_success_element_id').html(html); // your_success_element_id is your element id where the html to be populated
$("#flash").hide();
}
});
your_success_element_id is your element id where the html to be populated

My function only works with an alert after my ajax call

I'm populating a table with values from my database. I have included a delete icon in rows which can be deleted. The image has an onclick='deleteCat(id);' property, the id is taken from a json array trough a loop like so:
string = "<td align='center'><a href=''><img border='0' src='../images/Bullet-Delete.png' alt='delete' onclick='deleteCat("+json[i]['id']+");'/></a></td>";
This is my deleteCat function:
function deleteCat(id){
var dataString = "catId=" + id;
$.ajax({
type: "POST",
url: "../ajax/categorie_verwijderen.php",
data: dataString,
success: function(data) {
//$("#allecat").find("tr:gt(0)").remove();
//update_table();
}
});
//alert(id);
}
My function works when I put an alert after the ajax. The table refreshes and the row is removed from my db. However when I remove the alert my function does not work, the table is refreshed and the row is still present in the table and db.
Thanks in advance.
You need to prevent the default event for the click - ie the page is being reloaded each time you click on the image
function deleteCat(id){
var dataString = "catId=" + id;
$.ajax({
type: "POST",
url: "../ajax/categorie_verwijderen.php",
data: dataString,
success: function(data) {
$("#allecat").find("tr:gt(0)").remove();
update_table();
}
});
return false; // prevent the browser following the href
}
You will also need to change your html :
onclick='return deleteCat("+json[i]['id']+");
The alert() helps because that delays the processing of the remaining javascript in that function. The ajax send data asynchronously. async key is Default: true and should change it to false in your call till the client wait for end of ajax call.
e.g.:
$.ajax({
async:false,
url: "test.html",
.
.
});

Categories

Resources