Cakephp :How to post data on two actions - ajax

I am trying to post data by a form.
I need to submit the form on other website and have to save the data in my database as well. I tried my best but did not find the solution for this.
Here is my form:
<form class="formaction" action="http:www.demo.com" method="post">
<input type="text" value="1" name="quantity" class="form-style pull-left">
<input type="hidden" name="stock" value="1100">
<input type="submit" value="Add" style="display: block;" class="button-style">
</form>
Case I:
In this case form is submitted to www.demo.com , but it causes error at mystagingserver/addtotrolley
Ajax function:
$('.formaction').submit(function() {
$.ajax({
type: 'POST',
url: 'mystagingserver/addtotrolley',
data: {
quantity: $( "input[name$='quantity']" ).val(),
stockcode: $( "input[name$='stockcode']" ).val()
}
});
});
Case II:
In this case Form is not submitted to www.demo.com but ajax works properly, and it saves my data to database from mystagingserver/addtotrolley
$('.formaction').submit(function() {
$.ajax({
type: 'POST',
url: 'mystagingserver/addtotrolley',
data: {
quantity: $( "input[name$='quantity']" ).val(),
stockcode: $( "input[name$='stockcode']" ).val()
}
});
return false;
});

From Case I what I gathered is, when the user clicks Submit, it makes an ajax call. And immediately attempts to submit the form to www.demo.com. Meaning you are moving away from the page and probably losing the connection. What error message are you getting exactly?
The best approach would be to make an AJAX call to your staging server. If it succeeds only then proceed with the regular form submission or make another AJAX post request to the third party domain.
Something like below would be ideal:
$('.formaction').submit(function() {
$.ajax({
type: 'POST',
url: 'mystagingserver/addtotrolley',
data: {
quantity: $( "input[name$='quantity']" ).val(),
stockcode: $( "input[name$='stockcode']" ).val()
},
success: function(resp) {
$.ajax({
type: 'POST',
url: 'http:www.demo.com',
data: {
quantity: $( "input[name$='quantity']" ).val(),
stockcode: $( "input[name$='stockcode']" ).val()
},
success: function(resp) {
alert("Successfully submitted to both!");
}
});
}
});
return false;
});

Related

Ajax response in a text field

I have this ajax form that gets the value of the user field, I need the answer of everything of all the process I do in the php file to be seen in the same user field but it doesn't work how can I do this thanks
<form method="post" id="form">
<input type="text" id="user" name="user"/>
<input type="button" id="btn" value="button" />
</form>
$.ajax({
type: "POST",
url: url,
data: $("#form").serialize(),
success: function(data) {
$('#user').html(data); //print answer in text field
}
});
You use the val() method to set text in an textbox
$.ajax({
type: "POST",
url: url,
data: $("#form").serialize(),
success: function(data) {
$('#user').val(data); //print answer in text field
}
});

Form validation in codeigniter when ajax used to form submit

Form submit is not happened in this scenario..
$.ajax({
type: "POST",
async: false,
url: base_url+"register/registration_val",
data: "register_first_name="+first_name,
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
In your view you can add this:
<script type="text/javascript">
var base_url = "<?php print base_url(); ?>";
</script>
Plus try to alert and see the value of final url in ajax i.e alert(url);
Try adding a id to the firstname input
<script type="text/javascript">
$(document).on('submit','#form-reg',function(){ // #form-reg is id on form open tag
$.ajax({
url: "<?php echo base_url('register/registration_val');?>",
type: 'POST',
data: {
firstname: $('#firstname').val(),
},
dataType: 'html', // I perfer to use json
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
}
});
});
</script>
I would use dataType: json much easier that way to get data from controller
You used data: "register_first_name="+first_name, it's not correct. Correction is data: {register_first_name:first_name},
base_url like this var base_url = <?php echo base_url(); ?>
So, Bellow final code :
<script type="text/javascript">
jQuery(document).ready(function ($) {
var base_url = <?php echo base_url(); ?>
$.ajax({
url: base_url+"register/registration_val", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {register_first_name:first_name}, // Data sent to server, a set of key/value pairs representing form fields and values
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
}).done(function (data) {
$('#inferiz').html(data);
}).fail(function (data) {
console.log('failed');
});
}(jQuery));
</script>
Please verify your view part that whether you provided id same as in ajax function.
view part:
<form id="form-reg">
<input name="firstname" id="firstname" type="text" required placeholder="Enter firstname " >
<span id="name_validation" class="text-danger"></span>
<button name="submit" id="submit_button" onClick="myFunction();" >submit</button>
</form>
Then correct the base url path which has to be given inside php tag.
function myFunction() {
$.ajax({
url: "<?php echo base_url();?>register/registration_val",
type: "POST",
data:'firstname='+$("#firstname").val(),
success: function(msg)
{
alert('done..!');
}
});
}

Second $.ajax call stuck the code

I have an ajax+jquery navigation system with $.ajax, and I`m trying to do a second call to $.ajax to send a contact form infos, but, when I add the second $.ajax all just stop working.
First Call -
function loadPage(url)
{
url=url.replace('#!','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "loader.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#conteudo').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Second Call
$("#enviar").click(function() {
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function(mn) {
if(parseInt(mn)!=0)
{
$("#conteudo").html(mn);
$("#enviado").css('visibility','visible');
}
}
return false;
});
#EDIT
Very good! The first ajax is not stucking anymore, but this second is not working as expected.
This is intended to parse $_POST values to a php script and if ok just turn div visible..
How I`m doing that -
<form name="formcontato" id="form">
<fieldset>
<label>Seu nome</label>
<input type="text" name="nome" class="input-block-level">
<label>Email</label>
<input type="email" name="email" placeholder="seu#email.com" class="input-block-level">
<div class="form-actions">
<input type="button" name="enviar" value="Enviar" id="enviar" class="btn btn-baixar" />
</div>
</fieldset>
</form>
This is the form.
$("#enviar").click(function () {
var str = $("#form").serialize();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function (mn) {
alert("Ok!");
if (parseInt(mn) != 0) {
$("#conteudo").html(mn);
$("#enviado").css('visibility', 'visible');
}
}
});
return false;
});
This is the js
if($_POST) {
$nome = trim($_POST['nome']);
echo $nome;
}
This is the update.php
In what you posted, the second function does not properly close the $.ajax() function with a }); so it would generate a parse error and none of the code in this block would be available.
Try this where the $.ajax() call is succesfully closed.
$("#enviar").click(function () {
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function (mn) {
if (parseInt(mn) != 0) {
$("#conteudo").html(mn);
$("#enviado").css('visibility', 'visible');
}
}
});
return false;
});
FYI, proper and consistent indentation is essential to spotting these issues.

passing array of values from view to controller using ajax

I have a form in my view page.it contains 5 text boxes,one search button.while the user enters values in textbox(Entering all fields are not mandatory)and click on the search button,the values I have to store it in an array and pass it to the controller and depending upon the search results i have to display the results of those searched records.
I am able to store the searched values in an array,now i want how to pass this array to the controller and how to access these values in the controller.
as Jose referred , your request may look like this :
$("#submit").click(function () {
var searchData = new Array();
$(".search-input").each(function () {
searchData.push($(this).attr('value'));
});
$.ajax({
type: "POST",
url: "/Home/Index",
data: {"searchData" : searchData},
success: function (data) {
// do something on success
},
traditional: true,
dataType: "json"
});
return false;
});
and your controller action could be :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index([Bind(Prefix="searchData")] List<string> searchData)
{
return Index();
}
and your form have to have markup like this:
<form id="myform">
<input type="text" class='search-input' />
<input type="text" class='search-input' />
<input type="text" class='search-input' />
<input type="text" class='search-input' />
<input type="submit" id="submit" />
</form>
Use ajax. If jQuery is an option you could write something like this
$(form).submit(function()
{
var ;
$.ajax({
type: "POST",
url: "/Controller/Action",
data: JSON.stringify(_yourArrayObject),
success: function(data){
alert(data.Result);
},
dataType: "json"
});
})

Jquery .ajax() function not returning values from codeigniter controller

I have a site i'm working on and i'm trying to make an ajax request to a controller (codeigniter framework). I see in firebug that my controller is receiving my post value just fine but for some reason it is not sending back a response. I've set it up to be VERY simple without a database call at this point just for testing and its still not working. Any ideas?
Here is my form in my view:
<div class="purchaseState">
<input type="text" name="city" id="city" class="grayGrad"/>
</div>
<div>
<ul id="cityResults">
<!-- AJAX results here -->
</ul>
</div>
Here is my controller returning the value:
function citySearch() {
echo '<li>test</li>';
}
Here is my Jquery ajax
//New City Search
$('#city').keyup( function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
}).done(function( data ) {
$('ul#cityResults').append(data);
});
});
you should use ajax success callback:
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});
Please change the url in the AJAX function in the following way.
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "<?php echo base_url; ?>page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});

Resources