Jquery-confirm and passing POST variables to an externally loaded form - php

Is there a way to send POST variables to an external PHP form?
I'd like to pass, in this example, XXX and YYY using POST (not GET).
I'm using this plugin: https://github.com/craftpip/jquery-confirm
<a id="btn" data-value1="XXX" data-value2="YYY">CLICK ME</a>
<script>
$('#btn').on('click', function (e) {
e.preventDefault();
$.confirm({
title: 'Title',
content: 'url:form.php',
buttons: {
......
}
});
});
form.php:
<?php
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
?>
<div class="form-group">
<label class="control-label">Default values from parent page:</label>
<input type="text" id="value1" class="form-control" value="<?php echo $value1; ?>">
<input type="text" id="value2" class="form-control" value="<?php echo $value2; ?>">
</div>
UPDATE: tried this also, without success. Form doesn't load in modal:
content: function() {
var self = this;
return $.ajax({
url: 'form.php',
dataType: 'json',
async: false,
method: 'post',
data: { 'value1': 'XXX', 'value2': 'YYY' }
}).done(function (response) {
self.setContent(response);
});
}

You simply need to specify
dataType: 'html'
instead of
dataType: 'json'
This is because form.php returns a HTML string, not a JSON object. You likely have an error in your console complaining that jQuery cannot parse the response as JSON, because it isn't JSON. If you tell jQuery to expect HTML instead, it will pass the reponse through as a string instead which you can directly display on screen, without trying to turn it into an object.

Related

How to pass the array value to PHP using AJAX?

I am trying to submit data to the database using AJAX. I have one array and I have to pass the value of the array to PHP using AJAX to display all the related records.
<form id="search-form" method="POST">
<input value="4869" name="compare_id[]" type="hidden">
<input value="4884" name="compare_id[]" type="hidden">
<input value="5010" name="compare_id[]" type="hidden">
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
AJAX
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'response.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html(response);
//alert(response);
}
});
});
});
</script>
PHP
$sql='SELECT Name, Email FROM request WHERE Id IN (' .( is_array( $_POST['compare_id'] ) ? implode( ',', $_POST['compare_id']) : $_POST['compare_id'] ).')';
$records = array();
$query=$conn->query($sql);
if ($query->num_rows > 0) {
while($row=$query->fetch_assoc()){
$records[]=$row;
}
}
echo json_encode($records);exit();
HTML
<form id="search-form" method="POST">
<input value="4869" name="compare_id[]" type="hidden">
<input value="4884" name="compare_id[]" type="hidden">
<input value="5010" name="compare_id[]" type="hidden">
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
JS
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'response.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html(response);
}
});
});
});
</script>
PHP
var_dump($_POST['compare_id']);
// it is already an array of ids. You can do whatever you want with it.
change your script as below. Your output is in array so you cant add it in div directly
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'action.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html();
for(data in response) //loop over your data
{
$('#response').append(response[data].Email); //add email
}
//alert(response);
}
});
});
});
</script>
There are errors in your code. A good way to debug this is to print_r your POST value in your php script.
First $_POST["All"] does not exist. It is all. (php)
Second, you send a GET request not a POST one. (jQuery)
Third, format your date into json. A good way to do this is to create a variable right after compare_id.push, it's more readable, as so :
var json_data = {"my_array" : [1,2, "bonjour", 4]};
Your problem is mostly related to "how to debug". I think you should print what's happening along the way to figure out what's happening.

not receiving data in php codeigniter when sending ajax post

I'm trying to send data by post using ajax (with codeigniter) and I don't know why but I don't receive anything...
This is how I send it:
var sendData = $('#formContact').serialize();
$.ajax({
type: 'POST',
url: '<?php echo base_url()?>/intranet/update/updateProfile',
data: sendData,
dataType: 'json',
success: function (data)
{
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
and this is an example of my form:
<form id="formContact" action="update" method="POST">
<input class="headInput" type="text" name="userName" value="Tito"/>
<input class="headInput" type="text" name="userLastName" value="Lancreo"/>
<input class="headInput" type="text" name="phone[]" value="666666"/>
<input class="headInput" type="text" name="phone[]" value="111111"/>
<input class="headInput" type="text" name="phone[]" value="222222"/>
</form>
And when I debug it, I always get 0...
[false, false, Array[0], false, null]
My controller:
$this->load->helper('form');
$this->load->library('form_validation');
//1 way
$ret=$this->input->post();
//2 way
$return=$this->input->post(NULL, TRUE);
//3 way
$all=$_POST;
json_encode($all);
//4 way
$contact=$this->input->post("userName");
//return everything...
$var[0]=$return;
$var[1]=$contact;
$var[2]=$all;
$var[3]=$ret;
$var[4]=$data;
echo json_encode($var);
How can I fix it??
SOLVED!
The problem was not to replace with:
serialize().replace(/%5B%5D/g, '[]');
But I think it's usefull...
My problem was that I'm using a library for internationalization (https://github.com/bcit-ci/CodeIgniter/wiki/CodeIgniter-2.1-internationalization-i18n) and I must add language to my url, even if I change my routes.php
url: '<?php echo base_url()?>en/intranet/update/updateProfile'
Thanks a lot!
The issue, as it seems, Is the serialize itself.
As can be seen here :
How to send serialize form data using JQuery if the input element is an array
Serialize has an issue with an array in the input fields, It replaces the square barckets :
The fiddle :
http://jsfiddle.net/3vr0dtgn/
from my fiddle:
data = $('form').serialize();
$('div').append(data);
Using the stackoverflow I supplied above gives the solution(regex replacing certain elements)

CodeIgniter and AJAX form submit

I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.
Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.
My problem is the form won't submit with e.preventDefault(); in place, but without it the form does the normal method of posting to the db then refreshing the page.
Here is my AJAX call:
$(document).ready(function() {
$('form#feedInput').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $('.feed-input').val(),
dataType: "html",
success: function(data){
debugger;
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
});
I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault(); function.
How can I get this form to submit via AJAX if the e.preventDefault() function is stopping it before it can reach the $.ajax() function?
The data attribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() } or in query format 'key='+$('.feed-input').val().
Also there is an unnecessary debugger variable in the success method.
A working code could be:
$('form#feedInput').submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function(data){
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
Html part in view
<form id="comment" method="post">
<h2>Enter Your Details</h2>
<center><div id="result"></div></center>
<div class="form_fld">
<label>Name</label>
<input type="text" placeholder="Enter Your Full Name" name="name" required="">
</div>
<div class="form_fld">
<label>Email ID</label>
<input type="text" placeholder="Enter Email ID" name="email" required="">
</div>
<div class="form_fld">
<label>Contact Number</label>
<input type="text" placeholder="Enter Contact Number" name="contact" required="">
</div>
<div class="form_fld">
<label>Developer</label>
<select name="developer">
<option>Lotus</option>
<option>Ekta</option>
<option>Proviso</option>
<option>Dosti</option>
<option>All</option>
</select>
</div>
<div class="form_fld">
<button type="submit" id="send">Submit</button>
</div>
</form>
After Html Part Just put ajax request
<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "home/contact",
data: dataString,
success: function(data){
// alert('Successful!');
$("#result").html('Successfully updated record!');
$("#result").addClass("alert alert-success");
}
});
return false; //stop the actual form post !important!
});
});
</script>
Within Controller
public function contact()
{
$ip = $_SERVER['REMOTE_ADDR'];
$data = array('name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'number' => $this->input->post('contact'),
'developer' => $this->input->post('developer'),
'ip' => $ip,
'date' => date("d/m/Y"));
$result = $this->User_model->contact($data);
print_r($result);
}
You don't have to use preventDefault(); you can use return false; in the end of function submit() but I doubt this is the problem.
You should also use url encoding on $('.feed-input').val() use encodeURIComponent for this.
You should also check if you have errors in your console.
To determine if default action is prevented you can use e.isDefaultPrevented(). By default action in this case I mean submit action of the form with id feedInput.
You didn't name your param in data. Check jquery ajax examples.
You are probably getting an error e.preventDefault(); is not stopping the ajax.
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $("#form").serializeArray(),
success: function(resp){
$('#container').html(resp);
},
error: function(resp) { alert(JSON.stringify(resp)); }
});

Display content dynamically based on user input using php and jquery

I have a form that will display a list of transactions based on the name and date.
<form id="form1" name="form1" method="post" action="<?php echo base_url() ?>options/history">
Name
<input name="name" type="text" id="name" />
date
<input name="date" type="text" id="date" />
<input name="find" type="submit" id="find" value="find" />
</form>
Once the form is submitted all the relevant details are being displayed.
Can someone explain to me how I can use jquery to loads the data on the same page?
I'm new to jquery and learning stuff. I did some research and below is what I have found:
<script type="text/javascript">
$(document).ready(function() {
$('#find').click(function() {
$.ajax({
type: "GET",
cache: false,
url: "<?php echo base_url() ?>options/history",
success: function(data) {
alert('Data Loaded');
}
});
});
});
</script>
And also how do I pass the form variables to my controller? Is it possible to directly pass the values to the controller or do I have to pass it along with the URL?
<script type="text/javascript">
$(document).ready(function() {
$('#form1').submit(function() {
// get the data of the form
var data_form = $('#form1').serialize();
$.ajax({
type: "GET",
cache: false,
data: data_form,
url: "<?php echo base_url() ?>options/history",
success: function(data) {
alert('Data Loaded');
// Your data is in the var data returned, you can use it with, for example: $("#content").html(data);
}
});
// Prevent default behaviour
return false;
});
});
</script>
I am a bit confused here. But I suppose you actually want this:
$('form#form1').submit(function(evt){
$.ajax({
type: "GET",
data: $(this).serialize(),
cache: false,
url: "<?php echo base_url() ?>options/history",
success: function (data) {
alert('Data Loaded');
}
});
evt.preventDefault();
return false;
});
You can use .submit() to bind to the JavaScript's submit event instead. By returning false at the end of this handler you can stop the form submission as shown above; or, by using evt.preventDefault().
The data property in $.ajax specifies the data to be sent to the server. As for getting this data you can use .serialize(), it will encode the form elements ready for submit them.

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