I have a javascript function which I'm using to change the action field of a form and then submit it. Here's the function
function printmulti(){
form=document.forms['form2'];
form.action="http://localhost/output_sample1.php/";
form.target = "_blank"; // Open in a new window
form.submit();
form.action="http://localhost/output_sample2.php/";
form.target = "_blank";
form.submit();
return true; }
But somehow only output_sample2.php is being shown. Why isn't the first part of the code being executed?
you cant submit to multiple forms like that, you need to use something like ajax and make the requests that way. Currently you are starting the submit for the first and then starting the second right after so the second one stops the first one from submitting.
Ajax Tutorial
Use ajax like this:
$.ajax({
type: 'POST',
url: 'http://localhost/output_sample1.php/',
data: 'var1='+var1+'&var2=var2', //your variables sent as post at output_sample1.php
success: function( data ) {
//do success stuff
},
error: function(xhr, status, error) {
alert(status); //if any error
},
dataType: 'text'
});
$.ajax({
type: 'POST',
url: 'http://localhost/output_sample2.php/',
data: 'var1='+var1+'&var2=var2', //your variables sent as post at output_sample2.php
success: function( data ) {
//do success stuff
},
error: function(xhr, status, error) {
alert(status); //if any error
},
dataType: 'text'
});
Hope will give you some idea to start your work. For more info visit this link ajax example
Related
I have a voting function which submits a user vote using AJAX and updates the DB without having to refresh the page. All good so far. But I also want to retrive the updated values from the DB and update this on the page.
I've nested a second AJAX request inside my first request. This second request calls on the file new_values.php which gets the latest values and puts them into an array and returns as JSON like below
$new_vals = array(
'new_total' => $new_total,
'poll_option_1_val' => $poll_option_1_val,
'poll_option_2_val' => $poll_option_2_val,
);
echo json_encode($new_vals);
Below is the Ajax request - the first request works just fine to update the DB but the inner AJAX request isn't working. In the below example I try to use alert to show new_total value but nothing happens
$(function () { // SUBMIT FORM WITH AJAX
$('#poll-form').on('submit', function (e) { //on form submit
e.preventDefault(); // prevent default behaviour
if($("form")[0].checkValidity()) { // check if the form has been validated
$.ajax({ // submit process
type: 'post',
url: 'vote-process.php',
data: $('form').serialize(),
success: function () {
$('#vote_submitted').modal('show');
$("input").attr("disabled", "disabled");
$("textarea").attr("disabled", "disabled");
$("#vote_button").attr("disabled", "disabled");
$("#vote_button").text("Vote submitted");
$.ajax({
url : 'new_values.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (result) {
alert(result['new_total']);
},
error : function () {
alert("error");
}
});
},
error: function() {
$('#error').modal('show');
}
});
return false;
} else { // if the form is not valid
console.log("invalid form");
}
});
});
This has been driving me crazy. Any help would be very much appreciated!
Second Ajax data:data will give you this issue need to pass proper parameter
$.ajax({
url : 'new_values.php',
type : 'POST',
data : {data_return:'yes'},
dataType : 'json',
success : function (result) {
alert(result['new_total']);
},
error : function () {
alert("error");
}
});
What is data in the second ajax request ? data : data ? data is not defined so javascript maybe stop to execute entire code especially if use 'use strict'
i need help because i'm stuck and don't know what's wrong ,i try to send user clicked button "id" to php to get related data from database in the same page
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
console.log(res, data);
},
error: function(err) {
alert(err);
}
});
});
the ajax print success in console log ,here is php code to get the value if clicked id
<?php
if(isset($_POST['ToEditId'])){
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
}
but nothing happen in php file !!
Which is the expected behaviour.
PHP is not dynamic. It doesn't "update".
PHP only runs once. This means that once your page is rendered, you cannot use PHP to change it again. You actually would have to use javascript to change the page, like so;
PHP side:
<?php
if(isset($_POST['ToEditId'])){
echo $_POST['ToEditId'];
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
die(); // prevent entire page from re-rendering again.
}
JS side:
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
//Add your PHP file's response to the body through javascript.
$('body').append(res);
},
error: function(err) {
alert(err);
}
});
});
As #IncredibleHat mentioned, you should make sure your page doesn't render any of its usual HTML, so it won't return the entire page back to your ajax call. So put the PHP all the way above your html!
The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}
I have a have a button that calls a JavaScript method that looks like this:
processSelection = function(filename) {
//alert('method reached');
$.ajax({
url: "sec/selectUsers.php",
data: "filename="+filename,
cache: false,
dataType:'html',
success: function(data) {
//$('#uploader').html(data);
$('#noUsers').sortOptions();
values = $('#noUsers').children();
for (i = 0; i < values.length; i++) {
$(values[i]).bind('dblclick',switchUser);
}
$('#addButton').bind('click',addSelection);
$('#removeButton').bind('click',removeSelection);
$('#submitButton').bind('click',addUsersToFile);
},
error: function (request, textStatus, errorThrown) {
alert('script error, please reload and retry');
}
}); /* ajax */
}
It is not going to the selectUsers.php script, nor is it posting the error message. When I click on my button 'add users' it does nothing. The other methods: switchUser, removeSelection, addSelection, and addUserstoFile are already defined.
I am fairly new to JavaScript and php and have been assigned this project running maintenance on our website. My php_error.log shows no error either. If anyone has any advice on this specific problem, or debugging in general I would very much appreciate it.
here is the click event:
<input type="button" value="add users" onclick="processSelection('<?=$drFile['name']?>')"/>
Okay,
To simplify my problem, I have done this:
processSelection = function(){
//alert('method reached');
$.ajax({
url: "sec/testPage.php",
cache: false,
success: function() {
alert('success');
},
dataType:'html',
error: function (request, textStatus, errorThrown) {
alert('script error, please reload and retry'); }
});
}
where testPage.php is just a table with some values in it.
Now when I click the button it show 'success', but never shows testPage.php
dataType: 'HTML'
has to be before your success method as far as i know. If still does not work try the following:
it will not show the test page because you are not appending anything to your current body. Your script executes successfully if you see "success"on your screen. All you need to do is if you have html generated in your testPage, assign all html to a php variable and then just echo it instead of returning it like
echo $myhtmlgenerated
and change
success: function() { ....
TO
success: function(result) {
$(body).append(result);
}
or you can play around with it and specify a special div which will hold the content from that page.
How can I bind an ajaxStart function for a specific event, using :
$(document).ajaxStart(function () {
alert("started");
});
$(document).ajaxStop(function () {
alert("Ended");
});
Tried this code but it runs whenever autocomplete starts.
Scenario must be like this : whenever I submit a form, that function will be called.
But when I'm just fetching values using autocomplete via ajax, ajaxStart and ajaxStop shouldn't be called.
But when I'm just fetching values using autocomplete via ajax,
ajaxStart and ajaxStop shouldn't be called.
You can create a boolean variable to keep track of whether user is typing or not something like:
<script>
var isTyping = false;
// inside your autocomplete handler set isTyping to true
$(document).ajaxStart(function(){
if (! isTyping) alert("started");
});
$(document).ajaxStop(function(){
if (! isTyping) alert("Ended");
});
</script>
It is better if you uses the main function and it's sub-functions.
$.ajax({
url: 'url_to_page'
beforeSend: function(req){ //Before the request is taking off},
error: function(req){ //If there were a error},
success: function(req){ //When it all was done}
});
$.ajax({
url :'your url',
data: {
//data to send if any
},
type: 'POST',
success:function(msg){
//eqv to ajaxstop if OK
},
beforeSend:function(){
//before ajax starts
},
error:function(){
//failure in ajax
}
});