I have one problem with function in Javascript. When I insert text in textarea, function sends text to PHP script with AJAX, but I have problem when I insert two or three words, e.g Bosnia and Herzegovina then the script does not work. I used string replace :
function provjeraDrzave(rijec) {
rijec = rijec.replace(" ", "%20");
$.ajax({
type: "GET",
url: "/drzava.php?slovo=" + randomslovo + "&drzava=" + rijec,
success: function (odgovor) {
$('#rezultati').replaceWith($("<span id='rezultati'>" + odgovor + "</span>"));
},
error: function () {
alert('Doslo je do pogreske');
}
});
}
It should work as follows: When I insert Bosnia and Herzegovina that must change to Bosnia%20and%20Herzegovina but that change to Bosnia%20and Herzegovina and that does not work. Where is the problem ??
Why don't you use, for example, the native encodeURIComponent function, which is made for this?
Or, even better, let jQuery take care of URL encoding for you, using the data config param:
function provjeraDrzave(rijec) {
$.ajax({
type: "GET",
data: {
slovo: randomslovo,
drzava: rijec
},
url: "/drzava.php",
success: function (odgovor) {
$('#rezultati').replaceWith($("<span id='rezultati'>" + odgovor + "</span>"));
},
error: function () {
alert('Doslo je do pogreske');
}
});
}
jQuery $.ajax can receive url arguments via the data property and should automatically serialize it for you.
data
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests... Object must be Key/Value pairs...
$.ajax({
type: 'GET',
url: '/drzava.php'
data : {
'slovo' : randomslovo,
'drzava' : rijec //no need to replace
}
success: function (returndata) {...},
error: function () {...}
});
If you absolutely want to do this way try
rijec = rijec.replace(/\ /g, "%20");
but encodeURIComponent would be more appropriate.
Related
I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>
I am trying to edit my Javascript to pull different data via an AJAX call based upon only part of a URL. Currently, my if/else script looks like this:
if (window.location.href=="london") {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data-london.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
} else {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
}
This doesn't work as currently written since if window.location.href=="london") is only part of the URL, not the full URL. Is there a way to edit this script to run only based off of the last bit of the page URL? For example: /london, /nw, etc.? Is there a better way to accomplish this task?
Instead of
if (window.location.href=="london") {
Use below code
var URL = window.location.href;
if(URL.indexOf("london") !== -1)
The .indexOf function will find out a substring is exist or not in a string. And in your case you wants "london" is exist or not in URL.
I assume you are asking, when the url something like 'https://example.com/london' , so you just want to include or get the value of london. below code will help to provide always last bit of value of the url.
window.location.pathname.splitOnLast('/')[1]
it will give you '/london'. or you can just check the existence of theondon in the url.
Firstly it is not necessary to use if else like above
You can use like below
var dataurl = document.URL
$.ajax({
url: 'somepage.php',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});
in somepage.php file you can process the data however you want based on the dataurl
And also in javascript you can do like below
var urlTopost="other.php";
if(document.url.indexOf("london")!==-1)
{
urlTopost="london.php";
}
$.ajax({
url: urlTopost,
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});
I have a Java servlet, that i need to call and pass it a variable using Ajax. I have written an Ajax script, to get the variable that needs to be passed to the servlet. However i am not sure how to do so. Any help on this matter please?
This is my ajax code:
var data;
data = "NUMBER ='" + Number + "'";
var Key = '';
$.ajax({
type: "POST",
url: "Record?DB=EMP&Table=EMP_HISTORY&",
dataType: 'xml',
data: {
"Where": data
},
success: function(xml) {
$(xml).find('record').each(function() {
key = $(this).find("PK").text();
});
},
error: function(error) {
}
});
Your url parameter has & at last, I don't know if you have done it purposefully. However you may try this :
$.ajax({
url:"Record?DB=EMP&Table=EMP_HISTORY",
data:{Where:data},
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(xml) {
$(xml).find('record').each(function() {
key = $(this).find("PK").text();
});
},
error:function () {
}
});
It's unclear that which step u r in.Since that ,i would rather give u some advice.
1、if u dont use any webframework, then goto file web.xml and edit the servlet tag.configure the url and the according serlvet.Then u can overwrite the doPost() method in the servlet and receive the http request.
2、if u use webframework like struts.u can modify the configuration in struts.xml and write the according method in ur action to deal with the request.
3、if u use jsp as ur solution.u can simple do it in the jsp file. Deal with the request variables through getRequestParameter and out.print the result.
hope my advice is helpful!
I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});
I have a file list, when the user double clicks a file, it is displayed in an editor,
The problem is, after opening a javascript file, all bootstrap functions get undefined.
UPDATE:
function openFile(file){
var filename = file.getPath();
$.ajax({
url: "${fileStorageServiceBaseUrl}" + applicationId + "/files/"+ resType + filename,
type: "GET",
success: function(response) {
editor.setFile(filename, response);
}
});
openResType = resType;
$("#saveButton").prop("disabled",false);
}
After calling this function, bootstrap functions get undefined. I'm calling it from the console, not via events now.
function openFile(file){
var filename = file.getPath();
$.ajax({
url: "${fileStorageServiceBaseUrl}" + applicationId + "/files/"+ resType + filename,
type: "GET",
dataType: "text", // THIS LINE SOLVED IT!
success: function(response) {
editor.setFile(filename, response);
}
});
openResType = resType;
$("#saveButton").prop("disabled",false);
}
From the jquery documentation:
dataType: (default: Intelligent? Guess (xml, json, script, or html)) Type: String.
The type of data that you're expecting back from the server.
"script" (this was getting selected by default): Evaluates the response as JavaScript and returns it as plain text.