URL jQuery ajax - javascript

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.

Related

How to use javascript to append the header of request before loading that page

I have 2 html files belong to two different controllers
This is belong to Index action of SignupController
Index.html
<div class="signup-small-font pull-right">Forgot password?</div>
When click at this link , it will go to that url and make a request to get the view of the ResetPassword Action of AccountController and get the resetPAssword.html
Now what i want is before making that request , i need to append a custom header in the request for the server side .
I was using ajax javascript :
function appendHeader(urlCulture){
$.ajax({
type: 'GET',
url: urlCulture,
headers: {
"Culture": 'zh'
},
})
}
What should i do in the index.html anchor link to call this function before requesting for the resetPassword.html
Like what I want is when I click at it , it will navigate to Account/Resetpassword and use the response getting from javascript file to render instead of a normal response
In your html file
<div class="signup-small-font pull-right"><a onclick="appendHeader(urlCulture)" href="#">Forgot password?</a></div>
In your js
function appendHeader(urlCulture){
$.ajax({
type: 'GET',
url: urlCulture,
headers: {
"Culture": 'zh'
},
success: function(res) {
window.location = 'Account/ResetPassword';
}
})
}
Give it a try. Im not quite sure if this is what you want to do.
you are using routes, you need to get the url from the javascript function
there is an example of that here:
Get local href value from anchor (a) tag
you could make something similar:
<div class="signup-small-font pull-right"><a onclick="return appendCustomHeader(this);" href="/Account/ResetPassword">Forgot password?</a></div>
in your js function like the previous reply you could make something like this:
function appendCustomHeader(element){
var url = element.href; // to get full url
$.ajax({
type: 'GET',
url: url,
headers: {
"CustomHeader": 'YourCustomHeader'
},
success: function(res) {
// here you make anything else with your response
}
})
return false;
}
I've not tested it, I hope it works for you.
it seems you can disable href redirecttion returning false,
see this:
How can I disable HREF if onclick is executed?

Ajax URL Path not Replacing current URL

get a problem with ajax url.
Here's the code:
onConfirm: function(){
var id = $(".branchid").data('id');
var url = "view-merchants-branch/" + id;
console.log(url);
$.ajax({
url: url,
type: "POST",
data: {_method: "DELETE", id:id},
success: function() {
alert("Data has been deleted");
location.reload();
},
error: function(){
console.log(url)
}
});
},
onCancel: function(){
return;
}
my url not replacing the current url and its become 404.
the result is:
http://localhost/admin/public/view-merchants/9/view-merchants-branch/273
expected result is:
http://localhost/admin/public/view-merchants-branch/273
I've tried change the type to "DELETE" but still no hope.
is there wrong with my ajax?. as i know ajax url will replace current url.
use
url: '<?php echo "http://" .$_SERVER['SERVER_NAME']."/admin/public/";>'+url,
type: "POST",
Hi instead pass absolute url like,
onConfirm: function(){
var id = $(".branchid").data('id');
var url = SITE_URL+"view-merchants-branch/" + id;//SITE_URL IS GLOBAL VARIABLE,WHICH IS ABSOLUTE PATH COMES UPTO http://localhost/admin/public/
console.log(url);
Check your network requests to see how the url is constructed,
Also visit this link to get better understanding about how ajax works
http://www.sitepoint.com/use-jquerys-ajax-function/
also this link
https://learn.jquery.com/ajax/key-concepts/#ajax-and-firebug

Reading a file into a string in jQuery/JS

The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.

jQuery function to check if background page fully loaded?

I was wondering if it's possible to use the $().ready function to test if another page is fully loaded.
Here I'm talking about a newsfeed updater, where the function will send a POST request to a background php page to update the database, and then, using ajax, the newsfeed will reload to grab new data.
function send_data(){
var head = $("#headline").val();
var news = $("#news").val();
var info = '&headline='+head+'&news='+news; //update string
$.ajax({
url: 'recieve_update.php', //updating php file
type: 'POST',
data: info //data string
});
$().ready(function() {
$("#newsfeed").load("load_news.php"); //reload the newsfeed viewer
});
}
Use the callback function of $.ajax():
$.ajax({
url: 'recieve_update.php', //updating php file
type: 'POST',
data: info, //data string
success: function(){
$("#newsfeed").load("load_news.php"); //reload the newsfeed viewer
}
});
I believe something alone these lines would be what you're looking for. Straight from the jQuery source. http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});

Execute php url with JS

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

Categories