using ajax to get data from a database with php [duplicate] - javascript

every type i run this it calls the error: OnError function and i can't see why it doesn't call the success: OnSuccess,
JS:
$(document).ready(function () {
// retreving data on button click
$("#data-submit").click(LoadDataThroughAjaxCall);
//loading screen functionality - this part is additional - start
$("#divTable").ajaxStart(OnAjaxStart);
$("#divTable").ajaxError(OnAjaxError);
$("#divTable").ajaxSuccess(OnAjaxSuccess);
$("#divTable").ajaxStop(OnAjaxStop);
$("#divTable").ajaxComplete(OnAjaxComplete);
//loading screen functionality - this part is additional - end
});
// ajax call
function LoadDataThroughAjaxCall() {
$.ajax({
type: "POST",
url: "Ajax/dataloader.php",
data: '{}',
dataType: "json",
success: OnSuccess,
failure: OnFailure,
error: OnError
});
// this avoids page refresh on button click
return false;
}
// on sucess get the xml
function OnSuccess(response) {
//debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var tweets = xml.find("Table");
showOnATable(tweets);
}
// show data on a table
function showOnATable(tweets) {
//debugger;
var headers = [];
var rows = [];
// header section
headers.push("<tr>");
headers.push("<td><b>tweets</b></td>");
headers.push("<td><b>created</b></td>");
headers.push("<td><b>source</b></td>");
headers.push("</tr>");
// rows section
$.each(tweets, function () {
var tweets = $(this);
rows.push("<tr>");
rows.push("<td>" + $(this).find("tweet_text").text() + "</td>");
rows.push("<td>" + $(this).find("created_at").text() + "</td>");
rows.push("<td>" + $(this).find("source").text() + "</td>");
rows.push("</tr>");
});
var top = "<table class='gridtable'>";
var bottom = "</table>";
var table = top + headers.join("") + rows.join("") + bottom;
$("#divTable").empty();
$("#divTable").html(table);
}
// loading screen functionality functions - this part is additional - start
function OnAjaxStart() {
//debugger;
//alert('Starting...');
$("#divLoading").css("display", "block");
}
function OnFailure(response) {
//debugger;
alert('Failure!!!' + '<br/>' + response.reponseText);
}
function OnError(response) {
//debugger;
var errorText = response.responseText;
alert('Error!!!' + '\n\n' + errorText);
}
function OnAjaxError() {
//debugger;
alert('Error!!!');
}
function OnAjaxSuccess() {
//debugger;
//alert('Sucess!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxStop() {
//debugger;
//alert('Stop!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxComplete() {
//debugger;
//alert('Completed!!!');
$("#divLoading").css("display", "none");
}
PHP:
<?php
//if(isset($_POST['data'])==true&&empty($_POST['data'])==false){
require_once('../connection.php');
function clean($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
//Sanitize the POST values
//$username = clean($_POST['data']);
//$result=sqlsrv_query($conn,"execute sp_ORDER_BY_name '$username'");
$result=sqlsrv_query($conn,"select tweet_text,source from tweets");
if($result) {
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
echo $row['tweet_text'].", ".$row['source']."<br />";
}
}else {
//Login failed
echo 'Name not found';
}
}
//}
?>
HTML FORM:
</head>
<body>
<div id="banner">
<h1>P-CAT version 0.1</h1>
</div>
<div id ="content">
<h2>Sreach Catigroies</h2>
<select id="data2">
<option value="">Plece select one of the follwing</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input name="data" id="data" type="text" />
<input type="submit" id="data-submit" value="Grab">
<div id="divTable">
</div>
</div>
<div id="divLoading" style="display: none; position: absolute; top: 50%; left: 40%;
text-align: left;">
<span>
<img src="Images/ajax-loader.gif" alt="Image not found." /></span>
<br />
<span style="text-align: left; padding-left: 8px;">Loading ...</span>
</div>
<div id="navbar">
<input type="button" value="EDIT">
<input type="button" value="HISTORY">
<input type="button" value="SETTINGS">
<input type="button" value="SEARCH">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/global.js"></script>
</body>

You have to response a json from php like,
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
$xml='<Table>';
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
$xml.='<tweet_text>'.$row['tweet_text'].'</tweet_text>';
$xml.='<source>'.$row['source'].'</source>';
// create xml tag for created_at
}
$xml.='</Table>';
echo json_encode(array('d'=>$xml));
return TRUE;
} else {
//Login failed
echo json_encode(array('d'=>'Name not found'));
}

Related

get data back from ajax php script

hello i am trying to add live search functionality to my website i used ajax php to do so
i would like when i click on a live search result to change the value of the live search field and to put the id of the selected result in a hidden form field to be used in insert later
i tried doing it in the code below but it gives the following error:
Uncaught SyntaxError: missing ) after argument list
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"GET",
data:{textbook:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
<script>
selectxt(id, textbood_adress){
$('#search').val(textbood_adress);
}
</script>
<div class="form-group input-group" id="textbook">
<input type="text" name="search" id="search" placeholder="Search" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-search"></i>
</button>
</span>
</div>
<div id="result"></div>
and for the php
include ("../../includes/config.php");
$output = '';
if(isset($_GET['textbook'])){
$key=$_GET['textbook'];
$key = $db->escape($key);
$results = $db->rawQuery("SELECT * from textbook where textbook_address like '%{$key}%' ");
if($db->count > 0){
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>Textbook address</th>
<th>select?</th>
</tr>';
foreach ($results as $result) {
$output .= '
<tr>
<td>'.$result["textbook_address"].'</td>
<td><a id="selectclick" href="#" onclick="selectxt('.$result['id'].','.$result['textbook_address'].')">select</a></td>
</tr>
';
}
echo $output;
}else{
echo "<span>No results for your search</span>";
}
}
?>
Your function declaration is wrong. Change your javascript code
from
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"GET",
data:{textbook:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
<script>
selectxt(id, textbood_adress){
$('#search').val(textbood_adress);
}
</script>
to
<script>
function load_data(query) {
$.ajax({
url: "search.php",
method: "GET",
data: {textbook: query},
success: function (data) {
$('#result').html(data);
}
});
}
function selectxt(id, textbood_adress) {
$('#search').val(textbood_adress);
}
$(document).ready(function () {
load_data();
$('#search').keyup(function () {
var search = $(this).val();
if (search != '') {
load_data(search);
}
else {
load_data();
}
});
});
</script>
Your javascript function declaration were wrong and also misplaced. Here's an example on CodePen.
Please check and make sure that $result['textbook_address'] doesn't have ' in it. This will break your html output as the browser will try to interpret it wrong

How to get only the newest value response from Ajax?

I have the issue with AJAX response and display errors.
For example, when I submit my form, I see 1 in console, but If I write something in first input and submit again, then
I see:
1
2
Ajax below read 1 and 2 as both responses, so I see 2 errors but I should see only the newest, so it should be only 2.
Also, I getting value when I try to use search (invite), but Ajax skipping everything and showing only success message after Submit.
ajax.js
$(document).ready(function() {
$('#form_create_circle').submit(function(event){
event.preventDefault();
$.ajax({
url: 'form-create-circle.php',
type: 'POST',
data: $('#form_create_circle').serialize(),
dataType: 'json',
success: function(response) {
console.log(response);
if (response == 1) {
$('#title').addClass('is-invalid');
$('#invalid_title').append('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else if (response == 2) {
$('#invite').addClass('is-invalid');
$('#invalid_invite').append('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else if (response == 3) {
$('#color').addClass('is-invalid');
$('#invalid_color').append('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else {
// success message
$('#_noti-container').append('<div class="noti noti-success noti-top-right noti-close-on-click noti-on-leave" style="z-index:100000"><div class="noti-content-wrapper"><div class="noti-content">Circle has been created!</div><div class="noti-close">×</div></div></div>');
}
}
});
return false;
});
});
form-create-circle.php
require_once($_SERVER['DOCUMENT_ROOT'].'/system/mysql/config.php');
$title = $db->EscapeString($_POST['title']);
$invite = $db->EscapeString($_POST['invite']);
$color = $db->EscapeString($_POST['color']);
$time = date('Y-m-d H:i:s');
$search = $db->QueryFetchArrayAll("SELECT * FROM user_about WHERE firstname LIKE '%".$invite."%' OR lastname LIKE '%".$invite."%'");
foreach ($search as $key) {
echo "
<div class='invite_search_cont'>
<div class='invite_search_img'><img src='{$key['profile_image']}'></img></div>
<div class='invite_search_name'>{$key['firstname']} {$key['lastname']}</div>
</div>
";
}
if ($title == '' || (!preg_match('/^[a-zA-Z0-9]+$/', $title))) {
echo 1;
} elseif ($search == '') {
echo 2;
} elseif ($color == '') {
echo 3;
} else {
$db->Query("INSERT INTO user_circle (user_id, user_added, title, color, time_added) VALUES ('{$user['id']}', '$invite', '$title', '$color', '$time')");
}
HTML
<form method='POST' id='form_create_circle'>
<div class='modal-body'>
<div>
<div class='form-group'>
<input type='text' name='title' id='title' placeholder='Family' class='form-control'>
<div id='invalid_title'></div>
</div>
<div class='form-group'>
<input type='text' name='invite' id='invite' placeholder='Search' class='form-control'>
<div id='invite_search_result'></div>
<div id='invalid_invite'></div>
</div>
<div class='form-group'>
<select name='color' id='color' class='form-control'>
<option value='0'>white</option>
<option value='1'>yellow</option>
<option value='2'>red</option>
</select>
<div id='invalid_color'></div>
</div>
</div>
</div>
<button type='submit' class='btn btn-primary' id='ajax_create_circle'>Submit</button>
</form>
<div id='_noti-container' class='noti-t-right'></div>
Sounds to me you just need to add $('#invalid_...').empty() to the start of the script before the ajax or change .append to .html
Also removeClass on all the divs involved:
$('#form_create_circle').submit(function(event) {
event.preventDefault();
$.ajax({
url: 'form-create-circle.php',
type: 'POST',
data: $('#form_create_circle').serialize(),
dataType: 'json',
success: function(response) {
console.log(response);
$('#title, #invite, #color').removeClass('is-invalid');
$("[id^=invalid]").empty(); // empty all error divs
if ("123".indexOf(response) > -1) {
var type = ["", "title", "invite", "color"][response];
$('#' + type).addClass('is-invalid');
$('#invalid_' + type).html('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else {
// success message
$('#_noti-container').html('<div class="noti noti-success noti-top-right noti-close-on-click noti-on-leave" style="z-index:100000"><div class="noti-content-wrapper"><div class="noti-content">Circle has been created!</div><div class="noti-close">×</div></div></div>');
}
}
});
});

jQuery ajax keeps adding more and more elements

When a user searches for a username he gets results. When he backspaces or modifies the query, the results just keep getting added on top of the previous results instead of the results being modified and a fresh, updated result returned. I have modified the script here and there with no success yet.
My view:
<div class='container'>
<div class='row'>
<div class='col-sm-6 col-xs-12 col-centered'>
<div class='panel panel-default'>
<div class='panel-heading sticky'>
<div class='back pull-left'><a href='<?php echo site_url('chats') ?>'><span class='glyphicon glyphicon-chevron-left'></span></a></div>
<h1 class='panel-title text-center'>New Chat</h1>
<input class='form-control' id='search-field' type='text' placeholder='Username'>
</div>
<div class='panel-body'>
<ul class='users collapse'>
</ul>
</div>
</div>
</div><!--end column-->
</div><!--end row 1-->
</div><!--end container-->
My JS:
$(function() {
var $search_field = $('#search-field');
$search_field.on('keyup', searchByUsername);
$search_field.focus();
});
function searchByUsername(e) {
var username = this.value.trim();
var keyCode = e.keyCode;
var data = {username : username};
var $usersElement = $('.users');
var users = [];
// Use this condition to prevent searching when whitespace is entered
if (username) {
var request = $.ajax({
url : site_url + 'search/searchByUsername/',
method : 'GET',
data : data,
dataType : 'json'
});
request.done(function(jsonRepsonse) {
if (jsonRepsonse) {
var status = jsonRepsonse.status;
var usernames = jsonRepsonse.usernames;
if (status === 'success') {
$.each(usernames, function(index, value) {
// must be one line or will throw syntax error
users.push("<li class='user text-center'><a href='#'><span class='glyphicon glyphicon-user'></span><strong class='username'>" + value + "</strong></a></li>");
});console.log(users);
$usersElement
.append(users)
.show();
}
}
});
request.fail(function(xhr, status, error) {
console.log(error);
});
}
users.length = 0
$usersElement.hide();
}
My Codeigniter controller function:
public function searchByUsername()
{
$username = $this->input->get('username', true);
$usernames = [];
if (!empty($username)) {
$usernames = $this->find_users_model
->searchByUsername($username);
}
if (!empty($usernames)) {
$this->jsonResponse(
['status' => 'success',
'usernames' => $usernames]);
return;
}
$this->jsonResponse(
['status' => 'success',
'usernames' => ['User not found']]);
}
private function jsonResponse($response)
{
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response));
}
Result:
This is your users container:
var $usersElement = $('.users');
On ajax response, you do:
$usersElement.append(users).show();
But you're always appending, never removing. Try emptying the element before populating it with users again:
$usersElement.empty().append(users).show();

Convert a JavaScript variable to a PHP variable

I'm learning HTML JS CSS and PHP and I have a big problem.
The $input variable in getPosForLieferschein() should be the user input, but I found no way to convert JS variables to PHP. The user should write a contract number into the input field and the contract positions - getPosForLieferschein() - show up in the table below. The page should not be reloaded just in case that no other way works. I know the code is terrible!
Head:
<?php include 'connection_manager.php'; $tags = getLieferscheine();?>
<script type="text/javascript">
var availableTags = "<?php echo $tags;?>"
$(function () {
var values = availableTags.split(",");
$('.select').autocomplete({
source: values
});
});
function generate() {
var eingabe = document.getElementById('input').value;
var position = "<?php $positionen = getPosForLieferschein($input); echo $positionen; ?>";
var arr = position.split(','), contract = arr[0], pos = arr[1], article = arr[2], name = arr[3], amount = arr[4], unit = arr[5];
var table = document.getElementById("table1body");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(2);
var cell5 = row.insertCell(2);
var cell6 = row.insertCell(2);
var i = 60;
var a = document.getElementById("input");
if ((a.value == eingabe)) {
while (i > 0) {
cell1.innerHTML = contract;
cell2.innerHTML = pos;
cell3.innerHTML = unit;
cell4.innerHTML = amount;
cell5.innerHTML = name;
cell6.innerHTML = article;
i = i - 60;
}
}
else {
swal({
title: "Fehler!",
text: "Bitte geben Sie eine gültige Auftragsnummer ein!",
type: "error",
confirmButtonText: "Ok",
confirmButtonColor: "#FF0000"
});
}
};
$(document).ready(function () {
$("#details").click(function () {
$("#uebertragen").removeAttr("disabled");
$("#details").attr("disabled", "disabled");
})
$("#uebertragen").click(function () {
$("#details").removeAttr("disabled");
$("#uebertragen").attr("disabled", "disabled");
})
})
$(document).ready(function () {
$("#uebertragen").click(function () {
$("td").remove()
})
})
</script>
Body:
<body>
<center>
<img style="position:relative;left:25px;" src="quehenberger.jpg" height="50px" width="240px" alt="quehenberger logo" align="left"/>
<img style="position:relative;right:25px;" src="bilton.png" height="50px" width="300px" alt="bilton logo" align="right"/>
<h1><b>QLog Eingabe</b></h1>
<hr/>
<div class="container">
<div class="row">
<form action="" method="get">
<input id="input" type="text" style="width:50%;position:relative;left:14em;" value="" class="select form-control col-xs-1" Placeholder="Auftragsnummer"/>
<button style="position:relative;left:18em;" id="details" class="col-xs-1 btn btn-success" onclick="generate();">Prüfen</button>
</form>
</div>
</p>
<button style="width:100px;position:relative;left:58.65em;" id="uebertragen" disabled="disabled" class="col-xs-1 btn btn-danger">Übertragen</button>
</div>
<table class="table">
<thead>
<tr>
<th>Auftragsnummer</th>
<th>Positions Nummer</th>
<th>Artikel Nummer</th>
<th>Artikel Bezeichnung</th>
<th>Artikel Menge</th>
<th>Einheit</th>
</tr>
</thead>
<tbody id="table1body">
</tbody>
</table>
</center>
</body>
</html>
You cannot just convert the variable. It is not possible. There are other options to make changes to the page without reloading:
You can make an ajax request each time the user input field has its content changed. Do all the calculations you need to do in the controller (server side) and just return the result and display it in the same page.
If you would use Yii2 framework, there would be another option. But this would require you to make some changes to the structure of your functions. In Yii2 you can write your JS in the view file and use values of PHP varibles. There is some info about that function here.
As I understand, you are not using any framework, so I would suggest to use ajax requests and pass the calculated values back to the page (option 1).
This is the final code! Thanks for help guys! :D`
<script type="text/javascript">
var availableTags = "<?php echo $tags;?>"
var currentTag = false;
$(function(){
var values = availableTags.split(",");
$('.select').autocomplete({
source: values,
select: function( event, ui ) {
//$('#input').val()
//console.log(ui.item.value);
getAuftrag(ui.item.value);
}
});
});
function sendAuftrag() {
if (currentTag !== false) {
$.ajax({
method: "GET",
url: "save.php",
data: {
q : currentTag
},
dataType: "html",
success: function(data) {
$("#tableBody").html("");
$("#uebertragen").attr("disabled", "disabled");
swal({title: "Erfolg!",
text: "Auftragsnummer " + currentTag + " erfolgreich übermittelt!",
type: "success",
confirmButtonText: "Ok",
confirmButtonColor: "#FF0000"
});
currentTag = false;
}
});
}
}
function getAuftrag(str) {
if (str == "") {
document.getElementById("tableBody").innerHTML = "";
currentTag = false;
return;
}
var values = availableTags.split(",");
if (values.indexOf(str) === -1) {
currentTag = false;
swal({title: "Fehler!",
text: "Bitte geben Sie eine gültige Auftragsnummer ein!",
type: "error",
confirmButtonText: "Ok",
confirmButtonColor: "#FF0000"
});
} else {
$.ajax({
method: "GET",
url: "ajax.php",
data: {
q : str
},
dataType: "html",
beforeSend: function(jqxhr) {
currentTag = str;
},
success: function(data) {
$("#tableBody").html(data);
$("#uebertragen").removeAttr("disabled");
// console.log(data);
}
});
}
}
$(document).ready(function(){
$("#uebertragen").click(function(){
$("#uebertragen").attr("disabled", "disabled");
})
})
</script>`
HTML:
`<body>
<center>
<img style="position:relative;left:25px;" src="quehenberger.jpg" height="50px" width="240px" alt="quehenberger logo" align="left"/>
<img style="position:relative;right:25px;" src="bilton.png" height="50px" width="300px" alt="bilton logo" align="right"/>
<h1><b>QLog Eingabe</b></h1>
<hr/>
<div class="container">
<div class="row">
<input id="input" style="width:50%;position:relative;left:14em;" class="select form-control col-xs-1" Placeholder="Auftragsnummer"/>
<!-- <button style="position:relative;left:18em;" id="details" class="col-xs-1 btn btn-success" >Prüfen</button> -->
<button style="width:100px;position:relative;left:18em;" id="uebertragen" disabled="disabled" class="col-xs-1 btn btn-danger">Übertragen</button>
</div>
</div>
<div id="tableBody"><b></b></div>
<div style="background-color: #E6E6E6;height:40px;width:100%;" data-role="footer" data-tap-toggle="false" class="ics-footer">
<p>Copyright IcoSense GmbH. All rights reserved.</p>
</div>
</center>
</body>
</html>`

How can I call second jquery/ajax request?

Well, I'm validating my html form with jquery/ajax request. It's process by add_contact_process.php page. In this page if data (family or given name) is exit then I'm showing a message with a button which value is Yes and Cancel.
So
1) If Yes button is press I want to call a another jquery/ajax request which save the data to db.
2) If Cancel button is press then I want to remove/hide the message.
Can someone suggest me how can I do this ?
Html form code :
<form id="addcontact">
<table width="450" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Family name</td>
<td><input type="text" name="family_name" maxlength="50" placeholder="Family name"/></td>
</tr>
<tr>
<td>Given name</td>
<td><input type="text" name="given_name" maxlength="30"placeholder="Given name"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add Contact" class="submit"></td>
</tr>
</table>
</form>
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
$('#success').delay(3000).fadeOut('slow');
</script>
add_contact_process.php page :
<?php
$family_name = inputvalid(ucfirst($_POST['family_name']));
$given_name = inputvalid(ucfirst($_POST['given_name']));
$exitfname = mysqli_query($link, "SELECT family_name FROM contact_details WHERE family_name = '$family_name'");
$numfname = mysqli_num_rows($exitfname);
$exitgname = mysqli_query($link, "SELECT given_name FROM contact_details WHERE given_name = '$given_name'");
$numgname = mysqli_num_rows($exitgname);
$msg = array();
$msg['error'] = false;
if(empty($family_name)){
$msg[] = "<div class='error'>Family name required.</div>";
$msg['error'] = true;
}
if(strlen($given_name) > 30){
$msg[] = "<div class='error'>Given name is too big.</div>";
$msg['error'] = true;
}
// If error is not found
if($msg['error'] === false){
if(!empty($family_name) && $numfname >= 1 || !empty($given_name) && $numgname >= 1){
$msg[] = "<div class='error'>A contact with this name exists. Do you wish to continue adding this new contact?
<input type='submit' name='warning' value='yes' id='yes' class='submit' style='margin:0px;'/>
<input type='submit' name='warning' value='Cancel' id='cancel' class='submit' style='margin:0px;'/>
</div>";
$msg['error'] = true;
}else{
$query_2 = "INSERT INTO contact_details (family_name, given_name) VALUES('$family_name', '$given_name')";
$query_2 = mysqli_query($link, $query_2);
$last_id = mysqli_insert_id($link);
if($query_2){
$msg[] = "<div class='success'><strong>Successfully added a new contact</strong>. </div>";
$msg['last_id'] = "$last_id";
$another = "close";
}else{
$msg[] = "<div class='success'>Sorry we can not add a new contact details. </div>";
$msg[] .= mysqli_error();
$another = "close";
}
}
}
echo json_encode($msg);
?>
Call Second ajax within success
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
/*------------------------------------------------------------------*/
if(confirm('Write your message here')){
/* Second ajax after clicking ok on confirm box */
$.ajax({
url : 'Second URL',
method :'POST',
data : {'data1':data1},
success:function(response){
// code after success
},
error: function(e){
return false;
}
});
}else{
$('#success').hide();
$('#success').hide();
}
/*----------------------------------------------------------*/
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
You should define the second Ajax call in first Ajax call complete method. By default Ajax call is asynchronous, it will start executing the code or statements in success method with out waiting for response from the server. you code should me like this
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
// some code
},
complete:function () {
//you second ajax call
}

Categories

Resources