I have two jquery function get and post.
I retrieve data from get method first and post my data with post method.
I want to know how to combine this two function.
POST Method
var url = '/api/sample?id=' + id ;
AJAXnotification("Saving...", 'info');
$.post( url , form)
.done(function(){
AJAXnotification("Saved", 'success', 5000);
})
.fail(function() {
AJAXnotification("Cannot save", 'error');
});
GET Method
AJAXnotification("Loading...", 'info');
var fail_callback = function() {
AJAXnotification("Cannot load ", 'error');
}
$.get('/api/samples', {
'id' : id,
'merge' : 'departures',
'departures.from_date': from_date,
'departures.to_date' : to_date
}).done(function( tours ){
AJAXnotification(" loaded", 'success', 5000);
});
Just embedding the $.post inside the .done function of your $.get will make the $.post fire after the $.get returns, and you'll be able to access all of the returned data:
$.get('/api/samples', {
'id' : id,
'merge' : 'departures',
'departures.from_date': from_date,
'departures.to_date' : to_date
}).done(function( tours ){
AJAXnotification(" loaded", 'success', 5000);
var url = '/api/sample?id=' + id ;
AJAXnotification("Saving...", 'info');
$.post( url , form)
.done(function(){
AJAXnotification("Saved", 'success', 5000);
})
.fail(function() {
AJAXnotification("Cannot save", 'error');
});
});
You can add your POST operation to the .done callback of the GET operation.
$.get('/api/samples', {
...
}).done(function( tours ){
$.post( url , form)
.done(function(){
...
})
.fail(function() {
...
});
});
You can do this way :
<form id="myForm">
<input type="text" name="nameGet" id="nameGet" />
<input type="text" name="namePost" id="namePost" />
<input onclick="submitGetPostForm();" type="button" name="submitBtm" id="submitBtm" value="submit" />
</form>
<script>
function submitGetPostForm()
{
nameGet=$('#nameGet').val();
namePost=$('#namePost').val();
$.ajax({
url: "testPage.php?nameGet="+nameGet,
type: "post",
data: {namePost:namePost},
success: function(response_msg){
response_msg=$.trim(response_msg);
alert(response_msg);
},
error:function(){
alert("Failure, some problem");
}
});
}
</script>
Related
I have this html code
<button onclick="var pdata = $('textarea').froalaEditor('html.get');">Submit article</button>
So I want to send this pdata variable to controller. How do I do this? Or should I use a form?
If you already use jQuery, consider the jQuery.post() method.
$.post("controller/path", pdata)
.done(function(response) {
comsole.log("Response: " + response);
});
You could move this code to a function, for example, like this:
<button onclick="submitArticle()">Submit article</button>
and in JS:
function submitArticle() {
var pdata = $('textarea').froalaEditor('html.get');
$.post("controller/path", pdata).done(function(response) {
comsole.log("Response: " + response);
});
}
Note that according to jQuery docs your pdata should be
A plain object or string that is sent to the server with the request.
$("#button").click(function(){
$.ajax({
type : "POST",
url :"url",
data : {id: $("#field").val()},
timeout : 100000,
success : function(response) {
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);},
done : function(e) {
console.log("DONE");
}
});
Hey here is working example of post action ajax+jquery
consider one textfield and one button for example
MyButton
see following ajax call:
function updatData() {
var value= $("#sample").val();
$.ajax({
type : "POST",
url :"url",
data : {id:value},
timeout : 100000,
success : function(response) {
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);},
done : function(e) {
console.log("DONE");
}
});
}
I have a POST method Jquery. Ajax and I can't send my data to the controller, I have tried every solution on the net, but no result.......
My JavaScript
$(document).ready(function(){
$('#submitForm').click(function(){
var data1 = {request : $('#request').val()};
$.ajax({
type: "POST",
url: "/Manufacturer",
data: data1,
success: function(dataBack) {
console.log(dataBack);
},
contentType: "application/json",
dataType: 'json'
});
});
});
MY controller
public function indexAction(Request $request)
{
//$name = $request->request->get('data');
//return new Response($name);//or do whatever you want with the sent value
if($request->isXmlHttpRequest()){
$name = $request->request->get('data1');
If($name == 1)
{
return new Response('Yeap');
}
else
{
return new Response(';(');
}
}
return $this->render('MyIndex/Manufacturer_LIST.html.twig' );
}
HEre is my Console ::
And my response is as it's obvious ";("
First you need to install FOSJsRoutingBundle to be able to "expose" your Symfony routes into the javascript code. Follow the steps in the official documentation.
Then, in your twig template if you have a form like:
<form>
<input type="text" id="name"> <br>
<button type="submit" id="submitForm">Submit</button>
</form>
your js code could look liks this:
$('#submitForm').click(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajax({
method: 'POST',
url: Routing.generate('Manufacturer_LIST');
// OR: url: "/Manufacturer", if you don't want to install FOSJsRoutingBundle
data: { name:name }
}).done(function(msg){
console.log(msg);
}).fail(function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus + ' ' + errorThrown);
});
});
And in your controller:
/**
* #Route("/Manufacturer", name="Manufacturer_LIST", options={"expose"=true})
*/
public function indexAction(Request $request){
if($request->isXmlHttpRequest()){
$name = $request->request->get('name');
return new Response($name);//or do whatever you want with the sent value
}
return $this->redirectToRoute('homepage');
}
I have a view file which contains a button (link):
<a href id="savebutton" class="btn btn-warning">Save</a>
Somewhere else in this view I have also declared some hidden fields in a form that contain my userid and vacancyid.
echo form_input(dataHiddenArray('userid', $this->auth_user_id));
echo form_input(dataHiddenArray('vacancyid', $vacancydetails[0]->vacancy_id));
These hidden fields translate to:
<input type="hidden" value="2" class="userid">
<input type="hidden" value="1" class="vacancyid">
Now I want to be able to send these values to my controller (via AJAX) so that I can insert them in my database.
My JS file looks like this:
$(function() {
var postData = {
"userid" : $("input.userid").val(),
"vacancyid" : $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
cache: false,
type: 'POST',
url: "<?php echo base_url();?>dashboard/vacancy/saveVacancy",
contentType: 'application/json',
dataType: 'text'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function(data) {
alert(data); // plausible [Object object]
//alert(data[0]); // plausible data
console.log(data); // debug as an object
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
And my controller looks like this (it is not doing much because it doesn't return anything):
public function saveVacancy() {
//$this->load->model('user/usersavedvacancies_model');
/*$data = array(
'userid' => $this->input->post('userid'),
'vacancyid'=>$this->input->post('vacancyid')
);*/
echo $this->input->post('userid');
}
Minor changes to javascript
$(function () {
var postData = {
"userid": $("input.userid").val(),
"vacancyid": $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
type: 'POST',
url: "<?php echo base_url('dashboard/vacancy/saveVacancy);?>",
dataType: 'json'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function (data) {
console.log(data); // debug as an object
if (data.result === 'success') {
alert("Yeah, it saved userid " + data.userid + " to vacancy id " + data.vacancyid);
}
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
});
In the controller
public function saveVacancy()
{
//assigning a more useable object name to the model during load
$this->load->model('user/usersavedvacancies_model', 'save_vacancy');
$data = array(
'userid' => $this->input->post('userid'),
'vacancyid' => $this->input->post('vacancyid')
);
//send data to model and model returns true or false for success or failure
$saved = $this->save_vacancy->doSaveId($data); //yes, I made up the method, change it
$result = $saved ? "success" : "failed";
echo json_encode(array('result' => $result, 'userid' => $data['userid'], 'vacancyid' => $data['vacancyid']));
}
You need to understand that $.ajax takes two methods i.e GET and POST and from the documentation you can see that default method is GET so Since you have not defined method as GET/POST probably the method is taken GET so first change define ajax method to POST as well as you need to be clear about dataType of ajax it may be one of JSON/html and default is json.
$.ajax({
method: "POST",
url: url,
data: data,
dataType:'html'
});
I guess this helped you can learn detail from
Learn more.
I am trying to get the value of a textbox without pass through form actions (because i cannot neither redirect to another page or refresh the current one).
index.php
into head
<script type="text/javascript">
function send() {
$.ajax({
type:"POST",
url: "script.php",
data: {
fname: document.getElementById("fname").value,
lname: document.getElementById("lname").value
},
success: function callScriptAndReturnAlert() {
var sdata = new XMLHttpRequest();
sdata.onload = function() {
alert(this.responseText);
};
sdata.open("get", "script.php", true);
sdata.send();
}
});
}
</script>
into body
<button class="myclass" onclick="send();">MyButton</button>
<input type="text" id="fname" placeholder="First name here" />
<input type="text" id="lname" placeholder="Last name here" />
Button is before input just for UI stuffs
script.php
$prev = $_SESSION['prev'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
[....do something....]
echo 'You used '.$fname.' and '.$lname;
Well.. the script.php doesnt receive the value of the inputs fname and lname.
You are trying to make two ajax calls when you only need one.
<script type="text/javascript">
function send() {
$.ajax({
type:"POST",
url: "script.php",
data: {
fname: $("#fname").val(),
lname: $("#lname").val()
},
beforeSend: function(){
alert('Sending');
},
success: function(data) {
//Received data from PHP script
alert(data);
},
error: function(){
alert('Error !');
},
complete: function(){
alert('Done');
}
});
}
</script>
$.post(
'script.php', // Your PHP file
{ // The data to pass
'fname' : $('#fname').val(),
'lname' : $('#lname').val()
}
).done(function(data) { // Here your AJAX already finished correctly.
alert(data); // Show what the PHP script returned
});
The $.ajax(), $.get() and $.post() jQuery methods are for making AJAX calls and, due to that, they already manage their own XMLHttpRequest object.
im trying to send values in a form via POST in ajax, how do i capture them in send them, this is wat i have now while in GET
function test(ans_field_uuid){
var result = "";
var url="ajax_pages/remove_answer_field_ajax.php"
url += '?uuid=' + ans_field_uuid;
$.get(
url,
function (data) {
result = data;
}
)
.success(function () {
if (result != "") {
addTableRow('tb_add_field', result);
$('#ajaaxDiv').html(result);
}
})
.complete(function () {
$('#img_create_subcat').hide();
$('#dialog').dialog('close');
})
.error(function () {
alert('An error has occurred.');
});
return false;
}
since you already use jQuery
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
data: name and location are your POST variable.
You can fetch the POST variable in this example in some.php with
$_POST["name"]
which equals "John"
If you want to receive something then like "Hello".
Inside your some.php
echo "Hello";
and it will be send to your ajax function as response in your done function as variable msg
Documentation for jQuery post
// ...
var url = "ajax_pages/remove_answer_field_ajax.php";
$.post( url, "uuid=" + ans_field_uuid, function (data) {
result = data;
}
// ...