how to use ajax result in click function? - javascript

i make a form in symfony when i submit form through ajax then i store (result.id) in a variable and then i used this variable in click function but the error occur invoiceid does not exist in new.html.twig
how to resolve this problem?
here is my code of ajax:
$("form").submit(function(e) {
e.preventDefault();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: data,
}).done(function( result ) {
var invoiceid=(result.id);
if(result.success) {
$('#result').css({
'color':'black',
'background-color':'#8F8',
'display':'Block',
'width':'200px'
});
$('#result').html('Invoices Record Inserted');
setTimeout(function(){
$('#result').hide();
},3000);
}
});
this.reset();
});
$("#edit").click(function(){
window.location.href= "{{ path('invoices_edit', {'id': invoiceid }) }}";
});

Your templating function {{ path }} is resolved before JavaScript even runs.
Your templating engine is unable to see JavaScript values, and the variable invoiceid does not exist in your template.

Related

Passing javascript variables(array) to php

I have a function where the user inputs are stored in a variable in javascript.
$('#btnsubmit').click(function() {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
var bookseats = seat;
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats},
});
});
When the user clicks on the #btnsubmit button, I want to send this variable(actually an array) to a PHP file named confirm.php.
<form method="POST" action="confirm.php">
<div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div>
</form>
In my PHP file, I've written the code to get the sent variable as follows.
$bookseats = "";
if(isset($_POST['bookseats']))
{
$bookseats = $_POST["bookseats"];
print_r($bookseats);
}
When executed, nothing happens in the PHP file(doesn't print the bookseats).Is there something wrong with this code?
You're not using a "success" callback to get the output of the PHP code. See success callback
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats},
success: function(data) {
console.log(data); // or alert(data);
}
});
Also, I think you should stop the propagation of the default behavior of the button, to prevent the browser to redirect the page to the form's action URL:
$('#btnsubmit').click(function(ev) {
ev.preventDefault();
As #Malovich pointed out, as of jQuery 1.8, you could also use .then():
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats}
}).then(function(data) {
console.log(data); // or alert(data);
}, function(){
console.log("Error");
});

generic ajax form submission

ajax/javascript problem:
I have an app which consist of multiple forms. What i want to achieve is to make a generic js function to submit forms to their respective controllers by getting form id.. I m successfully getting form ids in form_id variable but m unable to use them. I tried replacing $('patient_form') with form _id and got following error: TypeError: form_id.on is not a function
Here is the following code for better understanding of the problem:
$(function () {
var form = document.getElementsByTagName("form");
var form_id = "'#" + form[0].id + "'";
form_id.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $('#patient_form').serialize(),
success: function (result) {
alert(result);
}
});
});
});
The way you have it form_id is a string.
Try:
var form_id = $("#" + form[0].id);
$.ajax is a jquery function. If you want to use jquery (which in this case I think you should), then do it as follows:
$('form').on('submit', function () {
$(this).preventDefaults();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $('#patient_form').serialize(),
success: function (result) {
alert(result);
}
});
});
In addition to the other answers, you want to keep your form ID dynamic, right, so you can insert whatever values you want?
$(function () {
var form = document.getElementsByTagName("form");
// note you have to convert to jQuery object
var form_id = $("#" + form[i].id); // i, so you can put in the id for any form
form_id.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $(this).serialize(), // again, keep generic so this applies to any form
success: function (result) {
alert(result);
}
});
});
});
You should set the event listener to the element, not the string of the id of the element. Also I presume you have jQuery because you are using $. Set an id on the form in the HTML. Then:
$(function () {
var form = $('#theFormId');
form.submit(function(event) {
$.post('Controllers/c_insertPatient.php', form.serialize(), function() {
alert('success');
});
event.preventDefault();
});
});

cancel page loading state in ajax

I have a script which handles post form and uses document.write with event.preventDefault
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').submit(function(event) {
var form = $(this);
var request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).success(function(result) {
document.write(result);
});
event.preventDefault();
});
});
</script>
After I press submit and call document.write - my browser enters in infinite loading page state. If I remove preventDefault() - it works, but I need it for other script part to work..
Is there a way to cancel page loading state right after document.write ?
I can't see why event.preventDefault would be a problem here... Try the following code :
$(document).ready(function () {
$('#myForm').submit(function (event) {
event.preventDefault();
var form = $(this);
var request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).complete(function (result) {
$("body").html(result);
});
});
});
with complete instead of success to be sure that you haven't an error in your AJAX.

On PHP script end send message to jquery, print to page with jquery

I have a page with buttons, that when pressed send an ajax request through jquery to a PHP script. This script runs with these variables. When this PHP script is finished I would like to send a message back to the jquery function, which then prints out this message. Currently I have:
$('button').click(function () {
nombre = $('input').val();
buttonz = $(this);
buttonz.text('Loading...');
request = $.ajax({
type: "POST",
url: 'administrator.php',
data: {
'method': buttonz.attr('id'),
'results': nombre
},
});
request.done(function (response, textStatus, jqXHR) {
buttonz.text('Finished');
});
});
Instead of 'finished' I would like to echo a varaible from my php script.
First need to check console error if you have any error then try to alert response in success section try
$('button').click(function () {
nombre = $('input').val();
buttonz = $(this);
buttonz.text('Loading...');
$.ajax({
type: "POST",
url: 'administrator.php',
data: {
'method': buttonz.attr('id'),
'results': nombre
},
success: function (data) {
buttonz.text(data);
// or use buttonz.val(data);
}
});
});
You cannot ECHO from jQuery as this is PHP and the server-side script has already been run. What you need to do is enter the text or html into an existing element.
For example..
On your page (before ajax is done) create a blank DIV with space to put the response ie...
<div id="MyAnswerHere"></div>
Then in your ajax call in the success area add the code to insert the answer. For example
$("#MyAnswerHere").html(response);
Or if just text you could use...
$("#MyAnswerHere").text(response);
So in your code..
$('button').click(function () {
nombre = $('input').val();
buttonz = $(this);
buttonz.text('Loading...');
request = $.ajax({
type: "POST",
url: 'administrator.php',
data: {
'method': buttonz.attr('id'),
'results': nombre
},
});
request.done(function (response, textStatus, jqXHR) {
$("#MyAnswerHere").text(response);
buttonz.text('Finished');
});
});
And add the div to enter the message do with the ID that we are selecting in the DOM before hand.
`<div id="MyAnswerHere"></div>`
simply put the response from ajax in your button,
buttonz.text(response);
cheers
You could try something like this, which will change your button text when the ajax has succeeded:
$('button').click(function () {
nombre = $('input').val();
buttonz = $(this);
buttonz.text('Loading...');
request = $.ajax({
type: "POST",
url: 'administrator.php',
data: {
'method': buttonz.attr('id'),
'results': nombre
},
success: function (data) {
buttonz.text(data);
}
});
});
Change buttonz.text('Finished'); to:
buttonz.text('<?php echo json_encode(utf8_encode($your_Value))?>');
So why not just to echo the variable with php??
Change buttonz.text('Finished'); to:
buttonz.text('<?php echo $your_variable;?>');
The value of the variable will be parsed by the PHP engine, it will appear in your HTML page as requested

Enable to send data to servlet using AjAx and post method

function validate (user_value){
var name = user_value;
$.ajax({
url:"ggs.erm.servlet.setup5.AjaxS",
data:{ namee :name},
success:function(){
alert("worked");
}
});
}
This is my Code. Is something wrong with it?? Any kind of syntax or semantics error. Problem:Not able to send parameter to servlet in URL.?????
If you want your servlet's doPost method to handle the request you should add property type with value post.
function validate (user_value){
var name = user_value;
$.ajax({
url:"ggs.erm.servlet.setup5.AjaxS",
data:{ namee :name},
type: 'post',
success:function(){
alert("worked");
}
});
}
This way your Ajax request will be post instead of get (the default one).
It seems that your function is in doc ready handler check this out and see if helps:
function validate (user_value){
var name = user_value;
$.ajax({
url:"ggs.erm.servlet.setup5.AjaxS",
type:'POST', //<-----------------added this
data:{ namee :name},
success:function(data){
if(data){
alert("worked");
}
},
error:function(){
alert('not worked.');
}
});
}
$(document).ready(function(){
// your other code stuff for calling the function
});

Categories

Resources