Onclick autocomplete Jquery from JSON - php

I'm trying to make an autocomplete for multiple inputs.
this is the suggestions:
<div id="person" class="204232">
<div class="name" >John Smiths</div>
<div class="age" >25 years</div>
</div>
<div id="person" class="204255">
<div class="name" >Michael Sosh</div>
<div class="age" >31 years</div>
</div>
I need to make something, when I click at div #person, autocomplete this form.
<form ...>
<input type="text" name="name" />
<input type="text" name="age" />
<input type="text" name="adress" />
<input type="text" name="city" />
<input type="text" name="country" />
</form>
I can get these informations JSON encoded on get.php?code=[.className of #person]
This is what i did, but it's not working.
$("#search").on(click, function() {
source: function (request, response) {
$.ajax({
url: "get.php?code="+$(this).attr('class'),
type: "GET",
data: request,
success: function (data) {
response($.map(data, function (el) {
return {
name: el.name
};
}));
}
});
},
select: function (event, ui) {
this.name = ui.item.name;
$('#name').val(ui.item.name);
event.preventDefault();
}
});
NOTE: In this example, I'm trying to autocomplete just the first input but i need to complete all.
Get.php?code=204232 return:
{"age":"25 years",
"name":"John Smiths",
"adress":"KariStr. 112",
"city":"London",
"country":"England"}

If you just want to set the inputs, you don't need to use source/select. Just call the ajax request, set the response type to JSON, and on the callback set the values directly like this:
$("#search").click(function() {
$.ajax({
url: "get.php?code="+$(this).attr('class'),
type: "GET",
dataType: 'json',
success: function (data) {
$("input[name='name']").val(data.name);
$("input[name='age']").val(data.age);
$("input[name='address']").val(data.address);
$("input[name='city']").val(data.city);
$("input[name='country']").val(data.country);
}
});
});
See that you were using the selector #name that means id=name. You either add the id to the input tag or use the name selector as i did above.

Related

How to call two action in one form submission by one button click?

I Have a form in PHP. when I am clicking the submit button I want to take two actions at the same time. how do I do that?
<script>
function myfunction(){
$.ajax({
type: 'post',
url: 'merchants.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
}
</script>
<div class="stdFormHeader"> New Merchant Registration</div>
<form action="" method="POST">
<label class="stdFormLabel">Merchant name : </label><input class="stdFormInput" type="text" name="merchantName" required><br>
<!-- <label class="stdFormLabel">Business Type : </label><select class="stdFormSelect" name="shopMarket" required>-->
<!-- <option value="shop">Shop</option>-->
<!-- <option value="market">Market Place</option>-->
<!-- </select><br>-->
<label class="stdFormLabel">Contact Person : </label><input class="stdFormInput" type="text" name="contactPerson" required><br>
<label class="stdFormLabel">Contact Number : </label><input class="stdFormInput" type="text" name="contactNumber" required><br>
<label class="stdFormLabel">Address : </label><textarea class="stdFormInputBox" name="address"></textarea><br>
<input class="stdFormButton" type="submit" name="submit" onclick="myfunction()" value="Apply">
</form>
Just do a submit again:
function myfunction(){
$.ajax({
type: 'post',
url: 'merchants.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
$.ajax({
type: 'post',
url: 'OtherFunction.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted again');
}
});
}

Sending Multiple data to PHP page without reloading page

Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});

jQuery/Ajax request is being sent twice

I've been scanning my code over and over again but I can't seem to find the problem.
When I click the link #add-user-btn the file actions.php is called twice (and hence the PHP script is executed twice).
Here's the script: I suppose it has something to do with the javascript in front of the ajax request?
$(function () {
$("#add-user-btn").click(function (e) {
e.preventDefault();
var email = $("#email").val();
var name = $("#name").val();
var action = "adduser";
$.ajax({
url: '../actions.php',
type: 'POST',
data: {
action: action,
email: email,
name: name,
},
dataType: 'json',
success: function (data) {
$(".close-reveal-modal").click();
}
});
});
});
The HTML:
<div id="adduser" class="reveal-modal">
<h1>Add new user</h1>
<p><label for="email">E-mail:</label> <input id="email" name="email" type="text" placeholder="name#example.com" /></p>
<p><label for="name">Name:</label> <input id="name" name="name" type="text" placeholder="Adam Smith"/></p>
<p><label for="password">Password:</label> <input id="password" name="password" type="password" placeholder="123456" /></p>
<p>
<label for="authorization">Authorization:</label>
<select id="authorization" name="authorization">
<option value="0">Administrator</option>
<option value="1">Superuser</option>
<option value="2">User</option>
</select>
</p>
<button id="add-user-btn">Submit</button>
<a class="close-reveal-modal">×</a>
</div>
Try
$("#add-user-btn").unbind('click').bind('click', function () { });
This will ensure the click event only gets called once.
This problem also occurs when you include multiple times the same JavaScript file in your HTML file.
<html>
<head>
<script src="utility.js"></script>
<script src="utility.js"></script>
</head>
When I worked with an specific website that I only had access to my javascript, I got this kind of error too. The problem was that there was lots of $(function() and $(document).ready in other codes.
what you can do to prevent this, if you can't correct the core problem is:
var preventRunDefault;
$(function () {
if(!preventRunDefault) {
preventRunDefault = true;
$("#add-user-btn").click(function (e) {
e.preventDefault();
var email = $("#email").val();
var name = $("#name").val();
var action = "adduser";
$.ajax({
url: '../actions.php',
type: 'POST',
data: {
action: action,
email: email,
name: name,
},
dataType: 'json',
success: function (data) {
$(".close-reveal-modal").click();
}
});
});
}
});
But the right way is to search the cause and don't do workarounds.

How to submit and validate a form via ajax

Please I am trying to simultaneously submit and validate my form to my database through the use of Ajax, but it is not working for me.
Here is my jquery
$(document).ready(function(){
$(".button").click(function(){
$("#myform").validate();
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: { firstname: $("#firstname").val()},
success: function(){
$('#message').html(data);
}
});
return false;
});
});
The problem is when I submit the form,the Ajax form submit to itself.
Please What is the right way to use the jquery validate and $.ajax together?
Pass data as a parameter in your success function:
success: function(data){
Your success function won't do anything because you haven't defined data
Try this (working for me as expected):
HTML Form:
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script>
// JQuery Script to submit Form
$(document).ready(function () {
$("#commentForm").validate({
submitHandler : function () {
// your function if, validate is success
$.ajax({
type : "POST",
url : "process.php",
data : $('#commentForm').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
});
</script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required />
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
<div id="message"></div>
PHP Code:
<?php
echo $_POST['email'];
?>
You forget to pass the response
$(document).ready(function() {
$(".button").click(function() {
//check the validation like this
if ($("#myform").valid()) {
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: {
firstname: $("#firstname").val()
},
//you forget to passs the response
success: function(response) {
$('#message').html(response);
}
});
return false;
}
});
});
First of all, why would you submit form if validation is not passed?
Try this, if validate really validates:
$(function(){
$(".button").click(function(){
var myform = $("#myform");
if (myform.validate()) {
$.post("process.php", myform.serialize(), function(data){
$('#message').html(data);
});
}
return false;
});
});

jQuery with Codeigniter AJAX Post problem

I've been trying to figure this out, but it seems to be harder than i first thought. However, what I'm trying to do is make an ajax post request, but the POST seems to be empty when I'm sending it.
My HTML File
<div id="statusUpdate">
<?php echo form_open(base_url() . 'profile/statusUpdate', array('id' => 'statusUpdateForm', 'name' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
My Javascript
$('#statusUpdateForm').submit(function() {
$.ajax({ // Starter Ajax Call
method: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
My PHP (Some of my medhod in the controller)
// Check if the input is a ajax request
if($this->input->is_ajax_request()) {
echo $_POST['profileUpdate'];
}
Notice, when i put echo "Hello World" etc in the controller, i do get "Hello World" in the alert box from the javascript.
I've also tried a var_dump on $_POST and it returns array(0){} When I'm trying to output the specific $_POST['profileUpdate'] variable i get an error like this,
I've also done a alert from the seralize function i JS, this is what i got,
Is there anyone who know how i can fix this problem?
Try changing method to type.
I'm guessing the script is performing a GET request, which is the default setting when using ajax(), instead of a POST request. Like this:
$.ajax({ // Starter Ajax Call
// "method" isn't an option of $.ajax
// method: "POST",
type: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
Try The following Code
In View add the following form
<?php echo form_open('welcome/CreateStudentsAjax'); ?>
<label for="roll">Student Roll Number</label>
<input type="text" id="txtRoll" value="" name="roll"/>
<label for="Name">Students Name</label>
<input type="text" id="txtName" value="" name="name"/>
<label for="Phone">Phone Number</label>
<input type="text" id="txtPhone" value="" name="phone"/>
<input type="submit" name="submit" value="Insert New Students" />
<?php echo '</form>'; ?>
The JQuery Part is below
$(document).ready(function(){
$('form').submit(function(){
//alert('ok');
$.ajax({
url:this.action,
**type:this.method,**
data:$(this).serialize(),
success:function(data){
var obj = $.parseJSON(data);
if(obj['roll']!=null)
{
$('#message').text("");
$('#message').html(obj['roll']);
$('#message').append(obj['name']);
$('#message').append(obj['phone']);
}
else
{
$('#message').text("");
$('#message').html(obj);
}
},
erro:function(){
alert("Please Try Again");
}
});
return false;
});
});
</script>

Categories