How can I call second jquery/ajax request? - javascript

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
}

Related

Successful ajax script doesn't give me response

The general problem is that I cannot get back echo or return through ajax from another file.The alert(msg) is empty. Does that prevent.default stop sending the GET? I am not very fluent in programming, could you please help me in this?
I have my simple form:
<form class='findAndBlock1' method="GET" action="">
<input type='text' name="nameToBlock1" placeholder=" who do you want to block?" class='nameInput'>
<input type='submit' value="Search" class='submitInput1'>
</form>
After clicking it, the ajax script starts:
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg);
},
error : function(error) {
alert('error');
}
});
});
</script>
It is directed to the script that is routed like this:
Route::any('/searchFriendsToBlock', 'SettingsController#searchFriendsToBlock');
Here is the script that is run through ajax:
public function searchFriendsToBlock() {
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
echo "hello";
return Response::json($newArr);
}
Use dataType parameter in ajax request as you are sending response in json format the default dataType is set to html in jQuery.ajax()
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg.type);
},
error : function(error) {
alert('error');
}
});
});
</script>
And Your script should be like this
public function searchFriendsToBlock()
{
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
$response = array();
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
$response['type'] = 'sussess';
$response['data'] = $newArr;
return Response::json($response);
}

Javascript onClick() issue

Following is my table where each row have 2 onClick event. When I click on each row it call the method's which I defined but Now you see that there are a check box to last column. I want if click on this check box then no need to call this method in Javascript onClick, is that possible ?
note: here php while loop is running :
echo "<tr onclick='getDetails($cdid), visited(this);'>";
echo "<td class='' valign='top' align='left' width='20'>$companyName</td>";
echo "<td class='' valign='top'>$family_name</td>";
echo "<td class='' valign='top'>$given_name</td>";
echo "<td class='' valign='top'>$department</td>";
echo "<td class='' valign='top'>$title<input type='checkbox' name='add_to_project'/></td>";
echo "</td>";
echo "</tr>";
Update:
function getDetails(id) {
try {
keepcontact = false;
if($("#contentText").val() != "" && $("#contentText").val() != null)
{
var toCharNotes = $('#saveToChrNote').is(':checked');
//AUTO save the charnotes if is checked without prompt
if( toCharNotes == true ){
var formData = new FormData($("#addNewNotes").parents('form')[0]);
var cid=$(this).parents('form:first').find('#cdid').val();
$.ajax({
url: 'response.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data){
getDetails2(id);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
} else {
var saveNote = confirm("Save or clear Enter Note before proceeding ?");
if (saveNote == true) {
var formData = new FormData($("#addNewNotes").parents('form')[0]);
var cid=$(this).parents('form:first').find('#cdid').val();
$.ajax({
url: 'response.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data){
getDetails2(id);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
} else {
keepcontact = true;
// do nothing.. :D
//getDetails2(id);
}
}
}
else{
getDetails2(id);
}
}
catch(err){
alert(err);
}
}
Just modify your function a bit
function visited(a)
{
if(a.getAttribute("name")=="add_to_project") return;
// Rest of the code of your function
}
Put this line on the top of the function visited
if(a.getAttribute("name")=="add_to_project") return;
Modify the PHP a bit
echo "<tr onclick='getDetails($cdid, this), visited(this);'>";
And modify the getDetails function
function getDetails(a, b)
{
if(b.getAttribute("name")=="add_to_project") return;
// Rest of the function
}
You can stop event bubbling using return false; at the end of the handler.
Try this demo scenario,
HTML :
<table id="infoTable">
<tr>
<td>Click Here</td>
<td>
<input type="checkbox" id="innerCheckBox" />
</td>
</tr>
</table>
jQuery :
$("#infoTable tr").on("click", function(){
alert("tr");
});
$("#innerCheckBox").on("click", function(){
alert("checkbox");
return false;
});
jsFIddle

Make a submit button POST and AJAX call same time?

I have this form that will POST to show_aht2.php but I also want it to make the AJAX call that you see in my code below. So, how can I do both so the user doesn't go to the other? I want the user to stay on map.php
thanks in advance
map.php
<form action="show_aht2.php" method="post">
<input type="radio" name="date_selected" value="1d" checked="checked"/>1d
<input type="radio" name="date_selected" value="1w" />1w
<input type="radio" name="date_selected" value="1m" />1m
<input type="radio" name="date_selected" value="3m" />3m
<input type="submit" id="aht_btn" name="get_aht" value="Get AHT" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function(){
$.ajax({
type:"GET",
url : "show_aht2.php",
data:{ } , // do I need to pass data if im GET ting?
dataType: 'json',
success : function(data){
//doing stuff
//get the MIN value from the array
var min = data.reduce(function(prev, curr) {
return isNaN(+curr['aht_value']) || prev < +curr['aht_value'] ? prev : +curr['aht_value'];
}, 1000000);
// alert("min:" + min); //return min for debug
//get the MAX value from the array
var max = data.reduce(function(prev, curr) {
return isNaN(+curr['aht_value']) || prev > +curr['aht_value'] ? prev : +curr['aht_value'];
}, -1000000);
//alert("max:" + max); //return max number for debug
//function for calculation of background color depending on aht_value
function conv(x){
return Math.floor((x - min) / (max - min) * 255);
}
//function for background color
//if NA then show white background, either show from green to red
function colorMe(v){
return v == 'NA' ? "#FFF" : "rgb(" + conv(v) + "," + (255-conv(v)) + ",0)";
}
//going through all DIVs only once with this loop
for(var i = 0; i < data.length; i++) { // loop over results
var divForResult = $('#desk_' + data[i]['station']); // look for div for this object
if(divForResult.length) { // if a div was found
divForResult.html(data[i]['aht_value']).css("background-color", colorMe(data[i]['aht_value']));
// alert("station " + data[i]['station'] + " <br>aht value" + data[i]['aht_value'] + "<br>timestamp:"+data[i]['ts_generated']);
}//end if
}//end for
}//end success
});//end ajax
});//end click
});//end rdy
</script>
show_aht2.php
if (isset($_POST['get_aht'])) {
if($_POST['date_selected'] == "1d" )//yesterdays result and using past 10 minute
{
$start_date = $one_day;
//$interval_value = "10 MINUTE";
//echo $start_date;
}
elseif($_POST['date_selected'] == "1w" )//1 week results
{
$start_date = $one_week;
//$interval_value = "7 DAY";
//echo $start_date;
}
elseif($_POST['date_selected'] == "1m" )//1 month results
{
$start_date = $one_month;
//$interval_value = "30 DAY";
//echo $start_date;
}
elseif($_POST['date_selected'] == "3m" )//3 month results
{
$start_date = $three_month;
//$interval_value = "90 DAY";
//echo $start_date;
}
}
/* what I expect from ther call back*/
$result = array();
foreach ($memo as $username => $memodata) {
if (in_array($username, array_keys($user))) {
// Match username against the keys of $user (the usernames)
$userdata = $user[$username];
//if AHT is null give N/A as value
if (is_null($memodata['aht_value'])) {
$result[] = array( 'username' => $userdata['username'],
'aht_value' => 'NA',
'station' => $userdata['station']//,
// "ts_generated" => $userdata['ts_generated']
);
}//end inner if
//else give the actual value of AHT without the decimals
else {
$result[] = array( 'username' => $userdata['username'],
'aht_value' => substr($memodata['aht_value'],0,-3),
'station' => $userdata['station']//,
// "ts_generated" => $userdata['ts_generated']
);
}//end else
}//end outer if
}//end for
echo json_encode($result);
do ajax call first, then submit form with .submit() later with callback of ajax.
<form action="show_aht2.php" method="post" id="formtopost">
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function() {
$.ajax({
type: "GET",
url: "show_aht2.php",
data: {}, // do I need to pass data if im GET ting?
dataType: 'json',
success: function(data) {
//doing stuff
//end success
},
always: function() {
//submit form !!!
$("#formtopost").submit();
}
}); //end ajax
}); //end click
}); //end rdy
</script>
Try :
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function(event){
event.preventDefault();
$.ajax({
type:"GET",
url : "show_aht2.php",
data:{ } , // do I need to pass data if im GET ting?
dataType: 'json',
success : function(data){
//doing stuff
}//end success
});//end ajax
});//end click
});//end rdy
</script>
Use method preventDefault : http://api.jquery.com/event.preventdefault/
You could submit the form with ajax rather than trying to do both at the same time
Something like this maybe?
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function(){
// This prevents the form from submitting
event.preventDefault();
// Capture form input
var $form = $(this);
var serializedData = $form.serialize();
// Run the ajax post
$.ajax({
url : "show_aht2.php",
type:"POST",
data: serializedData
success: function(response) {
// Do something
}
});
});//end click
});//end rdy
</script>

Disabled submit button if inputs are empty

What I have here is a ajax checking the availability of information in database. But what my problem is I want to disabled the submit button if the others inputs/textboxes are empty. I add the disable function in my ajax but when one of the textbox has a value the disabled isn't working. Any help will appreciate.
Index.php
<script type="text/javascript">
$(document).ready(function()
{
$('input[type="text"]').change(function()
{
var pr = $("#pr").val();
var msgbox = $("#status");
var txtbxs = $('.inputs').val();
$.ajax({
type: "POST",
url: "check_ajax.php",
data: "pr="+pr,
success: function(msg){
console.log(msg)
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK' && txtbxs !== '')
{
msgbox.html('<img src="css/available.png" align="absmiddle">');
$("#save").prop("disabled",false);
}
else
{
$("#save").prop("disabled",true);
msgbox.html(msg);
}
});
}
});
return false;
});
});
</script>
<tr>
<td>PR #</td>
<td><input type="text" name="pr" id="pr" autocomplete="off"></td>
</tr>
<tr>
<td></td>
<td><span id="status"></span></td>
</tr>
<tr>
<td>Date1</td>
<td><input type="text" class="datepicker inputs" autocomplete="off" readonly></td>
</tr>
<tr>
<td>Date2</td>
<td><input type="text" class="datepicker inputs" autocomplete="off" readonly></td>
</tr>
<input type="button" value="Save" id="save">
Check_ajax.php
<?php
if(isset($_POST['pr']))
{
$pr = $_POST['pr'];
$sql = $mysqli->query("select id, pr from pr_list where pr='$pr'");
if(($sql->num_rows)>= 1)
{
echo '<STRONG>'.$pr.'</STRONG> is already in use.';
}
elseif($pr == '') {
echo 'Fund is Empty';
}
else
{
echo 'OK';
}
}
?>
ajaxcomplete isn't really the right thing to use here, ajaxcomplete adds an event listener for every ajax call you make but you only need to check the message when this ajax call is successful.
It would still work though but for the msg variable having no scope whithin the ajaxcomplete function. Here is one way I would do it.
<script type="text/javascript">
$(document).ready(function()
{
// I've moved these variables here to give them global-ish scope
// I've also added a variable to assign your save button to
var msgbox = $("#status"),
saveButton = $("#save");
$('input[type="text"]').change(function()
{
var pr = $("#pr").val(),
txtbxs = $('.inputs'),
empty = true;
$.ajax({
type: "POST",
url: "check_ajax.php",
data: "pr="+pr,
success: function(msg){
console.log(msg)
// loop through the txtbxs and check for emptiness :)
$.each(txtbxs, function(key, box) {
if (box.val() != "") {
empty = false;
} else {
empty = true;
}
});
if(msg == 'OK' && !empty) {
msgbox.html('<img src="css/available.png" align="absmiddle">');
saveButton.prop("disabled",false);
} else {
saveButton.prop("disabled",true);
msgbox.html(msg);
}
} // END OF SUCCESS FUNCTION
});// END OF AJAX CALL
});
});// END OF DOCUMENT READY
Another thing I'm not sure about is that when you do your if statement and have txtbxs != '' are you trying to check that the boxes aren't empty or that the variable is not empty.
The way you have it set that the you are checking for the variable to be empty, if you are wanting to check that the txtbxs have a value then you want a some different code

Username availability with AJAX doesn't return any results

Below is a very basic script to check a username availability.
The gif loading icon appears as soon as I type something but then, for some reasons, nothing happens whereas there should be either "OK" or "not available" showing up within #status.
HTML:
<label>Username</label>
<input type="text" class="input" name="username" id="username"/>
<span id="status"></span>
JS part:
<script type="text/javascript">
$(document).ready(function() {
$("#username").change(function() {
var username = $("#username").val();
var msgbox = $("#status");
if (username.length >= 4) {
$("#status").html('<img src="images/gif/ajax-loading.gif">');
$.ajax({
type: "POST",
url: "ajax_check.php",
data: "username=" + username,
success: function(msg) {
$("#status").ajaxComplete(function(event, request) {
if (msg === 'OK') {
msgbox.html('Available');
} else {
msgbox.html(msg);
}
});
}
});
} else {
$("#status").html('Cannot be less than 3 letters');
}
return false;
});
});
</script>
Here's ajax_check.php:
<?php
include('includes/connect.php');
if(isset($_POST['username']))
{
$username = $_POST['username'];
$username = mysql_real_escape_string($username);
$rows = query("SELECT id FROM users WHERE username='$username'");
if (count($rows) == 1) {
echo 'not available!';
} else {
echo 'OK';
}
}
?>
I've checked the query, and it works fine.
Also, the JS console doesn't report any error.
Any ideas?
The $("#status').ajaxComplete line is unnecessary. If you are in success: function(msg) then it is complete. Remove the lines I highlight below with ->>
$.ajax({
type: "POST",
url: "ajax_check.php",
data: "username=" + username,
success: function(msg) {
->> REMOVE THIS $("#status").ajaxComplete(function(event, request) {
if (msg == 'OK') {
msgbox.html('Available');
} else {
msgbox.html(msg);
}
});
->> AND THIS }
});

Categories

Resources