jQuery serialize function with multiple values - javascript

I try to use jQuery to post multiple values to PHP page, and then use that values as a single values.
I start with code from Jquery site :
<form ><br>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select>
<br>
<br>
</form>
<p><tt id="results"></tt></p>
<script>
function showValues() {
var str = $( "form" ).serialize();
$( "#results" ).text( str );
}
$( "input[type='checkbox'], input[type='radio']" ).on( "click", showValues );
$( "select" ).on( "change", showValues );
showValues();
</script>
Result is: multiple=Multiple&multiple=Multiple2, and that is fine.
Now mycproblem is how to post these values to test.php page, and then to use unique values, like this :
$multiple=[first value]
$multiple2=[second value]
etc...

Change your multiple to multiple[] in your form. This will submit your values as multiple[]=1st value, multiple[]=2nd value and more.
jQuery,
$('form').on('submit', function(e)
{
e.preventDefault();
formData=$('form').serialize();
$.ajax(
{
type: "POST",
url: "test.php",
data: formData,
success: function(data)
{
alert("Form submitted");
},
error: function()
{
alert("Error in form submission");
}
});
});
At the PHP end,
$multiple=$_POST['multiple']; // Get the array input
Now proceed with the values respectively,
foreach($multiple as $key => $value)
{
echo "value number $key is $value"; // This will print as value number 0 is 1st value, value number 1 is 2nd value and more.
}

You have to post the form to test.php using AJAX. Try this -
$("form").on('submit', function(ev){
ev.preventDefault();
var form = $(this);
var action = 'test.php';
var data = $(this).serialize();
$.post(action, data)
.done(function(response){
if(response.success == false)
{
// If failed
}
else
{
// If successfully submitted
}
});
});
And on the other side (test.php), you'll get an array of your multiple values like this,
$multiple1 = $_POST['multiple']['0'];
$multiple2 = $_POST['multiple']['1'];

Related

Two or more select option only first one works Ajax

This is my blade
<select name="{{$bank_invited_user->role}}[]" id="role" class="form-control">
<option value="2" #if($bank_invited_user->role == 2) selected='selected' #endif >Co-author</option>
<option value="3" #if($bank_invited_user->role == 3) selected='selected' #endif >Contributor</option>
<option value="4" #if($bank_invited_user->role == 4) selected='selected' #endif >Guest</option>
</select>
And here I have my javascript code:
<script type="text/javascript">
$(document).ready(function(){
$( "#role" ).on( "click", function( event ) {
event.preventDefault();
var role_value = $(this).val();
var user_id = $("#role_id").val();
var bank_id = $("#removecollaborator").val();
$.ajax({
method: "POST",
url: "{{ url('/banks/change-role-in-bank') }}",
data: {
_token: "{{ csrf_token() }}",
role_value: role_value,
user_id: user_id,
bank_id:bank_id
},
success: function () {
$("select[id=role][value=" + role_value + "]");
alert('Role changed');
},
error: function () {
console.log("error");
}
});
});
});
</script>
When I click the the first select dropdown it changes just fine, but I have this select inside a foreach so it means I have more than one selections, so the other dropdown the second one it does not work.. I tried putting event.preventdefault but it does not work.. Can someone please help me, why the js code it does not work for the second selection(dropdown)..?
Can you check your brower console , mybe you have an ajax error
in js fiddle , the code is executed in the second event
https://jsfiddle.net/50k483nn/1/
You can also change event click to change for select dropdown
$( "#role" ).on( "click", function( event ) {
by
$( "#role" ).on( "change", function( event ) {

get multiple data using jquery and split

i want to get query1 and query2 from a span tag and im using split(_). for example query i want to get.
<span id='post1_query1_query2'>
and here my js code
$(document).ready(function(){
$( " span" ).tooltip({
track:true,
open: function( event, ui ) {
ui.tooltip.css("max-width", "600px");
var id = this.id;
var split_id = id.split('_');
var image = split_id[1];
var title = split_id[2];
$.ajax({
url:'fetch_details.php',
type:'post',
data:{image:image},
data:{title:title},
success: function(response){
$("#"+id).tooltip('option','content',response);
}
});
}
});
$(" span").mouseout(function(){
// re-initializing tooltip
$(this).tooltip();
$('.ui-tooltip').hide();
});
});
and then i call it to fetch_details.php
$post = htmlentities ($_POST['image']);
$title = htmlentities ($_POST['title']);
but not working.
you can pass multiple key-pair in data object.
$.ajax({
url:'fetch_details.php',
type:'post',
data:{image: image, title: title},
success: function(response){
$("#"+id).tooltip('option','content',response);
}
});

jQuery AJAX not returning false

I want my program below to return false if the employee ID exists. My PHP file echoes true if the employee ID exists and it is returned to the AJAX function.
$.post("connect_ajax_php.php",
{type: "checkId", val: val, field: "emp_id", table: "employee"})
.done(function(data, succ){
data = $.trim(data);
if( succ =="success" && data=="true" ){
$( errContId ).html( val+" already exist" );
$( id ).css( {"border":"1px solid red"} );
$('#'+sucImg).html("<img src='images/background/error.png'>");
return false;
}else{
$( errContId ).html("");
$( id ).css( {"border":"1px solid #ccc"} );
$('#'+sucImg).html("<img src='images/background/success.png'>");
}
});
If you are using the ajax call as a validation step you will manually submit the form in the ajax callback. Then move the return false to the click handler rather than call it from the ajax response handler.
<form id="myform" action="/url" method="post">
...
<button id="submitbtn" type="submit">Submit</button>
</form>
$("#submitbtn").on("click", function(event) {
$.ajax({
url: "connect_ajax_php.php",
method: "post",
data: {type: "checkId", val: val, field: "emp_id", table: "employee"}
})
.done(function(result) {
if (result == "true") {
// id exists
}
else {
$("#myform").submit();
}
});
return false; // prevent standard form submission
});

onSubmit form - Ajax request to validate the form

I have this scenario where when submiting html form we call javascript method to validate the form. Problem is that validation is done through Ajax request calling php function which returns json array which is empty or contains array with errors.
I am using Ajax request as this newValidation function will be used on all forms on my application so all field ids names and stuff is dynamic same as validation messages.
Console log results are:
Undifiend
It should be True or False.
So it looks like .done run after console.log.
I thought .done is waiting until ajax is finished and only then proceed?
Reason why I am asking I need this .done to run first so it can assing answer variable and only then return boolean to the form. Does this even possible?
UPDATED:
Html form:
<form id="systemManagementSettings" action="#" method="POST" onsubmit="return newValidation('systemManagementSettings')">
JavaScript
function newValidation(formId){
var answer;
var $inputs = $('#'+formId+' :input');
var values = {};
$inputs.each(function() {
values[this.id] = $(this).val();
$( "div#"+this.id+"_validation" ).text("");
});
var FinalValidation = $.ajax({
url: "validation/getValidationData",
type: "POST",
data: {form: formId, values: values},
});
FinalValidation.done(function(data){
var resultArray = JSON.parse(data);
if($.isEmptyObject(resultArray))
{
answer = true;
}
else
{
$.each( resultArray, function( key, value ) {
$( "div#"+key+"_validation" ).text(value);
});
answer = false;
}
});
console.log(answer);
return answer;
}
How do you prevent the form from actually being submitted?
Use event.preventDefault().
UPDATE
Submit the form in the done function.
function newValidation(formId){
var answer;
var $inputs = $('#'+formId+' :input');
var values = {};
$inputs.each(function() {
values[this.id] = $(this).val();
$( "div#"+this.id+"_validation" ).text("");
});
var FinalValidation = $.ajax({
url: "validation/getValidationData",
type: "POST",
data: {form: formId, values: values},
});
FinalValidation.done(function(data){
var resultArray = JSON.parse(data);
if($.isEmptyObject(resultArray))
{
$.ajax({
url: $('#'+formId).attr('action'),
type: "POST",
data: {form: $('#'+formId).serializeArray()},
});
}
else
{
$.each( resultArray, function( key, value ) {
$( "div#"+key+"_validation" ).text(value);
});
}
});
return false; //all the time
}

Retrieving AJAX value from a different Javascript function

In this simplified example of a larger web app, consider a simplistic registration form with fields: username, firstname, lastname and a Register button type="button".
<form action="" method="post" id="cns_form">
<table id="companyTable"><tr>
<td width="200">
First name*:<br />
<input type="text" id="first_name" name="first_name">
</td>
<td width="200">
Last name*:<br />
<input type="text" id="last_name" name="last_name">
</td>
</tr></table>
<input type="button" value="Register" id="register" >
</form>
<div id="alert" title="Alert"></div>
When the username field is completed, jQuery fires an ajax search of a database to see if that username already exists. This same search is also triggered when one clicks Register (for reasons removed from this simplified example).
PROBLEM: Everything works great when leaving the username field. However, after clicking Register, I don't know how to retrieve the result of the AJAX search and stop the form from submitting if the username already exists. I've tried all kinds of different things, but have returned the code to this state so it is easiest for the reader to assist.
For example, I tried integrating the suggested solution from this question, but I was unsuccessful applying it to my situation... I tried setting async:false inside the ajax function... I also tried calling the checkUsername(uname) from inside the checkForm function, but that didn't work either. A little help?
jQuery document.ready:
$(function(){
$('#username').blur(function() {
var uname = $.trim($(this).val());
checkUsername(uname);
}); //END BLUR username
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkUsername(uname);
checkForm();
});
}); //END document.ready
AJAX Call:
function checkUsername(uname) {
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
}
checkForm Function:
function checkForm() {
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
}
One both rejoices and weeps when answering his own question, but here goes. The solution was to send the checkUsername() function as an input param to the checkForm() function, and to make the checkUserName() function return a value that we could check inside checkForm().
Therefore, we must modify the $('#register').click function thusly:
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkForm(checkUsername(uname)); //<===========================
});
THEN the checkUsername() function, thus:
function checkUsername(uname) {
var returnVal = 0; //<=================================
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
returnVal = 0; //<============================
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
return returnVal; //<==============================
}
AND the checkform() function thus:
function checkForm(exists) { //<============================
alert('sub checkForm(). value of exists: ' + exists);
if (exists==9) { //<================================
$( '#alert' ).html( 'That username is already in use' + existing +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
}else{ //<==========================================
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
} //<===================================================
}
Thanks and kudos to Felix Kling for this helpful post.
Might put return false in the function call in the HTML form markup.
<form>
<bunchOfElements />
<button onclick="checkUserName(); return false">Check Name </button>
</form>
Also, you might bind the function to the button's click event using
$(document).ready(function(){
$("#buttonID").bind('click', function(){
//do your thing
checkForm();
});
});
Put a return false at the end of your #register button click function, right below checkForm(). The button is continuing to fire the form submit. when you have that handled by your javascript function.

Categories

Resources