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
}
});
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 am using this jQuery plugin for making toggle, but I have an issue that when I make multiple toggles that have same ids and class so in that case I am not able to identify particular toggle for applying auto load ajax on changing value.
I would to ask that how I make same toggle with this same plugin but different ids or class or name so I make ajax function like when I click toggle it will update in PHP without submitting submit button.
The plugin I am using is this one
The code I am using is this:
HTML
<p>Default: <span class="easyswitch"></span></p>
<p>Checked: <span class="easyswitch" data-default="1"></span></p>
SCRIPT
<script>
$('.easyswitch').easyswitch();
</script>
AJAX
$('MY_CLASS_NAME').change(function(){
var mode= $(this).prop('checked');
$.ajax({
type:'POST',
dataType:'JSON',
url:'test.php',
data:'mode='+mode,
success:function(data)
{
$("body").html('Operation Saved');
}
});
You can not handle easyswitch's change event. you need to create click event of it, and from it you can get the status of current toggle.
$('.easyswitch').easyswitch();
$('.easyswitch').click(function () {
var mode = $(this).hasClass('on');
toogleStatus(mode);
});
// for all controlls.
$(".easyswitch").each(function() {
var mode = $(this).hasClass('on');
toogleStatus(mode);
});
function toogleStatus(mode)
{
if (!mode) {
alert('checked')
}
else {
alert('unchecked')
}
}
Try using callback option
$('.easyswitch').easyswitch({
callback: function(val, ele) {
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'test.php',
data: { mode: val },
success: function(data) {
$("body").html('Operation Saved');
}
});
}
});
So I have this ajax request. When the user clicks an edit link, I fetch the ID of the entry and refresh the page with the data of that entry loaded into a form.
Here's my problem: This only works with the alert showing before the ajax call. When I leave out the alert, I get an ajax error (though the id is being posted) and the PHP page just reloads. Moreover, it only works when I put the newDoc stuff as a success callback. The exact same lines as a complete callback and the page reloads. Moreover, this occurs in Firefox only.
jQuery('a.edit').on('mousedown', function (e) {
e.preventDefault();
var id = jQuery(this).attr('data-title');
alert('test');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
});
What can I do?
EDIT: This must be a timing issue. I just noticed that when I click and hold the edit link for a second or so, everything works fine. When I do a short click, it doesn't. So I tried wrapping the ajax in setTimeout(), but that didn't help. Any other ideas?
Try to use location.href in place of document.location,
jQuery.ajax({
url: location.href,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string.
Got it!
The problem is the way Firefox handles the mousedown event. It seems to abort the ajax call as soon as you relase the mouse button. I changed the event to click and everything is fine now.
jQuery('a.edit').on('click', function () {
var id = jQuery(this).attr('data-title');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
}
});
});
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
Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request