How to get only the newest value response from Ajax? - javascript

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>');
}
}
});
});

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 input tag and option tag separately and load inside div and inside select

I have empty <div> and <select> want to load label and input tags inside div and option inside select after ajax response. How would i do that?
here is the response
i want to separately extract label and input for <div> & extract option for <select>.
here is my code:
<div class="form-group">
<select id="student" name="student" class="form-control" onchange="getName(this.value)">
</select>
</div>
<div name="state" id="state">
</div>
<script>
function getschool() {
var st = $('#school option:selected').val();
$.ajax({
type: "POST",
url: '<?php echo base_url();?>Choice/student',
type: 'POST',
data: {
// fname: fname
st:st
},
dataType: 'text',
success: function(data) {
alert(data);
//alert(data[0].id);
// for(k in data){
// alert(data[k].id);
$('#student').html(data);
//$('#state').html(data.input);
$('#state').html(data);
// }
//$('body').html(data);
// console.log(data);
//alert(data);
//alert("Succesful ");
//location.reload(false);
//window.location.href = "http://localhost:8080/choicelaunch/Choice/order_fullmenu";
}
});
}
</script>
After doing so i get every thing inside div like:
Plus i am getting this reponse from my Codeigniter controller:
public function student()
{
$sch= $this->input->post('st');
$swt=$this->data['school'] = $this->catering_model->selstu($sch);
//echo(json_encode( $swt));
if(!empty($swt))
{
if(($sch == "1"))
{
echo ('<label class="checkbox-inline">
<input type="checkbox" id="offer1" name="offer" value="Monday">Monday
</label>');
}
foreach($swt as $in)
{
echo ('<option value="'.$in->id.'" select="select">'.$in->fname.' '.'</option>');
}
}
//var_dump($data['school']);
}
i dnt knw why. i only need checkbox not non-checkbox.
You could use filter():
$('#student').html($(data).filter('option'));
$('#state').html($(data).filter('label'));
I know it's little bit tricky. But, try this one.
Why don't you try to add a separator between div content and select content on controller. Here what I mean:
public function student()
{
$sch= $this->input->post('st');
$swt=$this->data['school'] = $this->catering_model->selstu($sch);
//echo(json_encode( $swt));
if(!empty($swt))
{
if(($sch == "1"))
{
echo ('<label class="checkbox-inline">
<input type="checkbox" id="offer1" name="offer" value="Monday">Monday
</label>');
}
echo "##"; //the separator
foreach($swt as $in)
{
echo ('<option value="'.$in->id.'" select="select">'.$in->fname.' '.'</option>');
}
Then, after success receive data, try to split it.
success: function(data) {
alert(data);
var res = data.split("##");
$('#student').html(res[0]);
$('#state').html(res[1]);
}

JQuery Display Alert Message on Form Submit

I am trying to display alert messages on jquery from the client side. The jquery will be called once the submit button is clicked. The form then will call the server side php. Here is my code:
FORM
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
JQUERY
$(document).ready(function(){
var $form = $('#formAdd');
$form.submit(function(){
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.post($form.attr('action'), $(this).serialize(), function(response){
alert("DATA SUCCESSFULLY ADDED");
},'json');
return false;
});
});
But the alert message does not pop up inside the $.postmethod
And I also want to know how I can pop up the alert message from the server side. Here is my sample code:
SERVER SIDE
<?php $query = mysqli_query($conn, "SELECT * FROM table1
INNER JOIN table2
ON table1.col1= table2.col1
WHERE table2.col3= '".$_REQUEST['id']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>alert('ERROR')</script>";
return false;
} ?>
In summary, the code above works but I need to display messages that would tell me if the query is successful or not. Thanks
My new problem is that the code below bring me to another page:
FORM
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
JQUERY
$(document).ready(function(){
$('#formAdd').on('submit', function (e) {
e.preventDefault();
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.ajax({
context: this,
url: $(this).attr('action'),
type: 'POST',
data: new FormData(this),
dataType: 'json'
}).done(function (data) {
if(data == 'ok') {
alert("DATA SUCCESSFULLY ADDED");
}
if(data == 'no') {
alert("ERROR");
}
}).fail(function (data) {
console.log('failed');
});
});
});
SERVER
$query = mysqli_query($conn, "SELECT * FROM table1
INNER JOIN table2
ON table1.col1= table2.col1
WHERE table2.col3= '".$_REQUEST['id']."'");
if (mysqli_num_rows($query) != 0) {
mysqli_close($conn);
echo json_encode('no');
return false;
}
I need to return after the json_encode because there are still methods below that.
HTML Form
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
Script :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
$(document).on('submit', "#formAdd", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: "post",
data: $(this).serialize(),
error:function(){
alert("ERROR : CANNOT CONNECT TO SERVER");
},
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
PHP server side like this:
<?php
$insert = mysqli_query($conn, "insert query here");
if($insert) {
echo json_encode('ok');
} else {
echo json_encode('no');
}
?>
Just you need to put id="id" in input type text.
<input type="text" name="id">
Working Code
$(document).ready(function(){
var $form = $('#formAdd');
$form.submit(function(){
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.post($form.attr('action'), $(this).serialize(), function(response){
alert("DATA SUCCESSFULLY ADDED");
},'json');
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" id="id" name="id">
<input type="submit" value="submit">
</form>

How to use ajax in PHP foreach?

I have a form with two select html tags and an input submit. To populate the value of option tags and to display the equivalent values of selected option tag, I use PHP, please see snippet below.
Now, I want to use AJAX using JS to avoid the reloading of the browser when the user clicked the button. But I don't know how. Please help me
Here's the link
Snippet:
if(isset($_POST['mall_list'])){
$mall_list= $_POST['mall_list'];
$malls= $wpdb->get_results($wpdb->prepare("SELECT stores FROM tablename WHERE malls = '" . $mall_list. "' GROUP BY stores ORDER BY stores", OBJECT));
echo '<div class="\record\">';
foreach ($malls as $record){
echo '<div>' . $record->stores . '</div>';
}
echo '</div>';
} elseif(isset($_POST['store_list'])){
$store_list= $_POST['store_list'];
$stores= $wpdb->get_results($wpdb->prepare("SELECT malls FROM tablename WHERE stores= '" . $store_list. "' GROUP BY malls ORDER BY malls", OBJECT));
echo '<div class="\record\">';
foreach ($stores as $record){
echo '<div>' . $record->malls. '</div>';
}
echo '</div>';
}
HTML
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" value =""/> <br/>
Last Name: <input type="text" name="lname" value ="" /> <br/>
Email : <input type="text" name="email" value=""/> <br/>
</form>
JAVASCRIPT
//callback handler for form submit
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
if you want to post data through ajax jquery. this code work for you.
$( "form" ).submit(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: "your post url",
data: $('#yourformname').serialize(),
success: function (data)
{
}
});
});
javascript
$("#form").submit(function(e){
var data = $(this).serialize();
var url = $(this).attr("action");
$.post({
url,
data,
function(res)
{
if(res.code == 0)
{
//success
//code somthing when the server response
alert(res.message);
}
}
});
})
server
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
#is ajax request
# code your business logic
#response data
$response = [
'code' => 0,
'message' => 'success',
'data' => []
];
echo json_encode($response);exit;
} else {
#is normal request
}

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