I have the below code.
jQuery(document).on('submit', '#myform', function (e) {
e.preventDefault();
var formdata = jQuery(this).serialize();
jQuery.ajax({
url: this.action,
data: formdata,
success: jQuery( "#popup" ).load( this.action + '?' + formdata )
});
});
What I have works however I think there must be a better (proper way to do this)?
I thought I could load data from my line above in the success but data is not defined?
Based on the description of jQuery.load:
Load data from the server and place the returned HTML into the matched element
It looks like you should just be able to do something like:
jQuery(document).on('submit', '#myform', function (e) {
e.preventDefault();
var formdata = jQuery(this).serialize();
jQuery('#popup').load(this.action, formdata);
});
This should take whatever HTML is returned from the server on this.action and pop it into your element with id="popup".
Related
I would want to post data to my "mail.py" script. But I don't know the URL to that file.
My jQuery AJAX code and this javascript file is placed in
RKProjects/scripts_js/contactform.js
My python script is placed in
RKProjects/scripts_js/mail.py
Here is my jQuery ajax code (without the URL)
var toPost = {
voornaamPost: document.getElementById('fnameInput').value,
achternaamPost: document.getElementById('lnameInput').value,
gsmPost: document.getElementById('gsmInput').value,
mailPost: document.getElementById('emailInput').value,
berichtPost: document.getElementById('berichtInput').value
};
var jsonToPost = JSON.stringify(toPost);
$.ajax({
type: 'POST',
url:'',
data: toPost,
success: function(){
alert('succes')
},
error: function (){
alert('error')
}
})
You have to specify the URL where to send the request to, otherwise it will point to the URL of the page you are on.
You have the following options:
$.ajax({
url: 'http://example.com/path/mail.py', // absolute
});
$.ajax({
url: '/path/mail.py', // relative to root
});
If you add the URL without the first "/" it will just append whatever you have to the URL of the page you are on.
In the below code, I'm able to transfer data but when I use the function append to transfer file and data it's not working. Can someone tell me how to transfer file from upload? Looking forward to some help
$(document).ready(function() {
var loader = '<img src="../assets/media/loader.gif" />';
$('#submit').click(function() {
confirm("Do you really want to send messages?");
$('.loading').html(loader).fadeIn();
var msg_area_cst = $('textarea[name=msg_area_cst]').val();
var num_cst = $('textarea[name=num_cst]').val();
var form_data = new FormData();
form_data = 'msg_area_cst=' + msg_area_cst + '&num_cst=' + num_cst;
form_data.append('upload', $('input[name=upload]'));
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: form_data,
success: function(html) {
if (html == 1) {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
});
});
});
The problem is because you correctly declare a FormData object, but then in the next line overwrite it immediately with a string.
You need to append() all data to the FormData object. In addition you need to provide the file data to the append() method, not the jQuery object referencing the input type="file" control.
var form_data = new FormData();
form_data.append('msg_area_cst', msg_area_cst);
form_data.append('num_cst', num_cst);
form_data.append('upload', $('input[name=upload]')[0].files[0]);
That being said, you can make this much more simple if the controls you're reading the values from are contained in a form element. Then you can use the submit event of that form and pass a reference to it to the FormData constructor.
Also you don't do anything with the result of the confirm() I assume you want to stop the form submission if Cancel is clicked, which the above example now does using preventDefault().
Finally, using html == 1 is very unreliable. Firstly html will be a string so relying on implicit type coercion to an integer is not ideal. Also, returning a plain text response can cause issues if there's any whitespace included. I'd strongly suggest you change your server side logic to return a serialised format, such as JSON, and use a boolean value for a 'success' flag.
With all that said, try this:
$('#yourForm').on('submit', function(e) {
if (!confirm("Do you really want to send messages?")) {
e.preventDefault();
}
$('.loading').html(loader).fadeIn();
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: new FormData(this),
success: function(html) {
if (html.trim() === "1") {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
}
});
});
Try this ajax code
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
async: true,
success: function(html) {
if (html == 1) {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
});
I'm having an issue with AJAX as for some reason it either isn't being called or isn't working
$(document).ready(function() {
$("#my_form").submit(function(event) {
alert("submited");
event.preventDefault("#my_form");
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
alert(post_url + "" + request_method + " " + form_data);
$.ajax({
type: post_url,
url: request_method,
data: form_data,
success: function(data) {
alert(data);
$("server-results").html(data);
}
});
$('#loadingDiv').hide().ajaxStart(function() {
$(this).show();
});
//.ajaxStop(function() {
// $(this).hide();
//});
});
});
I've debugged as much as I could and there is no issue with the form function being activated in JavaScript or the 3 variables being transported into the JS code block. However ajaxStart doesn't activate which makes me believe that the problem is with just ajax.
I also checked the link to ajax and it seems to be working however I'm not sure if its the right link or if it's not valid for whatever reason.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
FYI the ajax link is at the top of the page above both HTML and JS.
You have passed wrong parameters:
type: post_url,
url: request_method,
You need to pass post_url in url and request_method in type. Just change it to:
type: request_method,
url: post_url,
$("server-results").html(data); here you have not specified if server-results is a class or id and therefore the output of the server will never be printed on the page
jQuery .ajaxStart()
As reported in jQuery's official documentation, the ajaxStart event can not be activated by the #loadingDiv element, but you must use the document.
$( document ).ajaxStart(function() {
$( ".log" ).text( "Triggered ajaxStart handler." );
});
Summing up the code should be something like this.
$(document).ready(function() {
$("#my_form").submit(function(event) {
alert("submited");
event.preventDefault("#my_form");
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
alert(post_url + "" + request_method + " " + form_data);
$.ajax({
type: post_url,
url: request_method,
data: form_data,
success: function(data) {
alert(data);
$(".server-results").html(data);
}
});
$(document).ajaxStart(function() {
$('#loadingDiv').show();
});
.ajaxStop(function() {
$('#loadingDiv').hide();
});
});
});
Everytime a page loads I need to load text into the CK Editor using JQuery, in order to get data from CK Editor I use
var editor_data = CKEDITOR.instances['editor1'].getData();
now is there a similar function I could use to put the data back into the editor?
I'm using ajax to set the data like this
$.ajax({
type: "POST",
url: "/inc/ajax/basic.php?menu_id="+menu_id+"&info=3",
success: function(msg){
CKEDITOR.instances['editor1'].setData(msg);
}
});
What am I doing wrong
Try this:
CKEDITOR.instances['editor1'].setData(html)
Where 'html' is a string containing content to edit.
Because its not an array then
just replace the instance like this
CKEDITOR.instances.editor1.setData(html)
var editor = CKEDITOR.instances.help_ldesc;
editor.setData('');
$.ajax({
url: urlstr, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:{action:"ex_form"}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache:false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
//alert(data);
var data1=data.split("~`");
$('#help_id').val(data1[0]);
$('#help_title').val(data1[1]);
$('#help_sdesc').val(data1[2]);
editor.setData(''+data1[3]);
var edata = editor.getData();
alert(edata);
}
});
Use this code its works for me and (help_ldesc) is my textarea name.
you should use data, and method for sending query string like this:
$(document).ready(function()
{
var querystring="menu_id="+menu_id+"&info=3";
$.ajax({
method: "POST",
url: "/inc/ajax/basic.php",
data:querystring,
success: function(msg)
{
CKEDITOR.instances['editor1'].setData(msg);
}
});
});
var jqxhr = $.get( "file.php", function(data) {
CKEDITOR.instances.idOftextAreaName.setData( data );
alert( "success" );
})
.done(function() {
//alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
// alert( "finished" );
});
CKEDITOR.instances['<%=ckEditor.ClientID%>'].setData(value);
From my experience using inside a function sometimes doesn't work properly. I'll suggest to use in:
$(document).ready(function () {
...
// instance, using default configuration.
CKEDITOR.replace('editor1');
//set data
CKEDITOR.instances['editor1'].setData(data);
...
});
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