I'm trying to send data from a script using Ajax to a script PHP. And I have this error : Notice: Undefined index: background. Thanks for your help.
ajax.php :
<?php
$mavariable2=$_POST['background'];
echo $mavariable2;
?>
script.js :
function open_script(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "ajax.php";
var back = "blue" ;
var backgroundf = "&background="+back;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(backgroundf); // Actually execute the request
//window.location.assign('ajax.php');
}
If you already have jQuery as a dependency in your project try using $.ajax().
var request = $.ajax({
url: "script.php",
method: "POST",
data: { background : 'blue' },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
More Information: http://api.jquery.com/jquery.ajax/
Related
In ajax I got it working but in javascript.
Ajax
// Get base64URL
var base64URL = canvas.toDataURL('image/jpeg').replace('image/jpeg', 'image/octet-stream');
AJAX request
$.ajax({
url: 'https://url/ajax.php',
type: 'post',
data: {image: base64URL},
success: function(data){
console.log('Upload successfully');
}
});
In JavaScript
var request = makeHttpObject();
request.open("POST", "https://url/ajax.php", true);
request.send(base64URL);
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
console.debug(request.responseText);
} else {
console.debug(request.responseText);
}
};
JS uploads to server image with 0 kb.
Should it append in image file base64 ? That's why it is 0? Tried several things searching but still not working.
I am trying to use ajax to pass a file (for upload it to server) and some other parameters to the server (perl cgi) but the server doesn't get the parameters.
The ajax:
$(function() {
$('#upload_file').click(function (){
var file = document.getElementById('file').files[0];
var formdata = new FormData();
formdata.append("Content-Type", "multipart/form-data");
formdata.append("sid", "1234");
formdata.append("file", file);
formdata.append("file_path_on_server", "/path/");
formdata.append("local_file_name", "sidebar_custom.css");
formdata.append("add_timestamp", "1"); // add timestamp to file name
$.ajax({
url : 'upload_file.cgi',
type : 'POST',
data : formdata,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
console.log(data);
alert(data);
}
});
// var xhr = new XMLHttpRequest();
// xhr.open("POST","upload_file.cgi",true);
// if (xhr.status != 200) {
// alert("Error '" + xhr.status + "' occurred when trying to upload your file.");
// }
// xhr.send(formdata);
});
});
When I am using XMLHttpRequest instead (which commented out) all parameters pass to the server script as requested.
e.g.
I tried to print the parameter "sid" but it is empty with ajax and "1234" with XMLHttpRequest.
I don't want to use XMLHttpRequest because I can't receive respond from the server (e.g. some file name string).
Am I doing something wrong?
I have a php script that makes my page load slowly because it fetches API data from another site and parses it so I want to make it load last. I'm reading AJAX is the way to go because it is asynchronous. Below is my AJAX code so far. All I want to do at the moment is have AJAX fetch a variable from PHP and display it but I can't get it to work. I think I'm really close though.
Here is the DIV I want it to load to and the script trigger.
<div id="results"></div>
<script type="text/javascript">ajax_lastcount();</script>
Here is the AJAX script
<script type="text/javascript">
function ajax_lastcount() {
var hr = new XMLHttpRequest();
hr.open("GET", "/viewcount.php", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
var results = document.getElementById("results");
results.innerHTML = data;
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
Here is viewcount.php page
header("Content-type", "application/json");
$lastcount = "ten";
echo json_encode($lastcount);
Using jQuery this could be achieved by this code (called automatically after the page's DOM is loaded):
$(document).ready(function() {
$.ajax({
url: '/viewcount.php',
type: 'get',
dataType: 'json',
})
.success(function(data) {
$('div#results').html(data);
});
});
If you want to perform simplified GET or POST request, you can also call this instead:
$(document).ready(function() {
$.get('/viewcount.php', {'optional_params_object':'value'})
.success(function(data) {
$('div#results').html(data);
});
});
or
$(document).ready(function() {
$.post('/viewcount.php', {'optional_params_object':'value'})
.success(function(data) {
$('div#results').html(data);
});
});
I have been trying to create an ajax request in codeigniter. I've seen this question: Simple Ajax/Codeigniter request but I wasn't able to absorb that as there were the answers in which people were using PHP inside Javascript. I didn't know it was possible, however I gave that a try but it seems like the PHP wasn't being executed.
So here are my questions:
Is it really possible to use PHP inside Javascript, or am I mistaken?
What's the right way to perform an Ajax request in Codeigniter? What I've tried is the following:
var param = {name : event_name, date : event_date, time : event_time};
$.ajax({
// As seen from the question here at stackoverflow.
url : "<?php echo base_url('event/new_event'); ?>",
type : 'POST',
data : param,
beforeSend : function(){ },
success : function(){
alert("Event created! Feel free to add as much details as you want.");
namebox.val("");
$("#new-event-modal").find(".close").trigger('click');
window.location.href = "<php echo base_url('user/dashboard'); ?>";
},
complete : function(){ },
error : function(){ }
});
I know the possibility that I could hardcode the URL in the request but that wouldn't be a good practice!!
the easiest way for you to accomplish this is by using some jquery:
function getBaseUrl() {
var l = window.location;
var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
return base_url;
}
var postdata = {name : event_name, date : event_date, time : event_time};
var url = getBaseUrl()+"/event/new_event";
$.post(url, postdata, function(result){
...alert(result);
});
or call it straight from JS by caching it:
<script>
var test = "<?php echo base_url(); ?>"+"event/new_event";
alert(test);
</script>
Here is a dirty hack that I was going to use:
Create a hidden field somewhere on the page and when this page loads echo out the base_url() as the value of that hidden field.
Now when you want to make an ajax request, access that hidden field
and grab the base url and use it however you want.
The right way is always the simplest way, there is no need to import Jquery in your client if you are not already using it.
This is your controller
<?php if (!defined('BASEPATH')) die();
class Example_ctrl extends CI_Controller {
public function ajax_echo()
{
// get the ajax input
$input = json_decode(file_get_contents('php://input'));
// $input can be accessed like an object
$password = $input->password;
$name = $input->name;
// you can encode data back to JSON
$output = json_encode($input);
// and the response goes back!
echo($output);
}
}
?>
This goes into your client
<script>
// here's the data you will send
var my_data = {name: "Smith", password: "abc123"};
// create the request object
var xhr = new XMLHttpRequest();
// open the object to the required url
xhr.open("POST", "example_ctrl/ajax_echo", true);
// on success, alert the response
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200)
return;
alert("Success: " + xhr.responseText);
};
// encode in JSON and send the string
xhr.send(JSON.stringify(my_data));
</script>
There is no better way to do this .
Php codes can't be executed from external javascript files.
Try any of these :-
1) base_url() is something's that's will not change , better store it in cookie and then access it in both server side code and client side code
2) you can store the same base_url() in local storage , it will be available in your external JavaScript files
Hope it helps you :)
In order to have my code written almost fully written in Jquery, I want to rewrite an AJAX call in Jquery.
It's a call from a webpage to a Tomcat servlet.
Similar code of my present situation:
var http = new XMLhttpRequest();
var url = "http://example.com/MessageController?action=send";
http.onreadystatechange = function ()
if (http.readyState == 4)
{
if (http.status == 200){ var response = http.responseText;}
else {/*code2*/}
};
http.async = false;
http.open("POST", url, true);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(string);
Which would be the best way to do this? .ajax or .post? Could you help me with some pseudo code to start this?
Use .ajax or (as you are using POST) .post:
$.ajax({
url: "http://example.com/MessageController",
type: "POST",
data: { action: "send", yourStringName: "something" },
async: false, // make sure you really need it
contentType:'application/x-www-form-urlencoded'
}).done(function(response) {
console.log(response);
});
It doesn't matter which one you use, because .post is shorthand for .ajax.
You can use jQuery post.
var url="MessageController"
$.post(url, { action : "send"} ,function(data){
//response from MessageController is in data variable
//code 1
alert(data)
}).error(function(){
alert("error"); //code 2
})
Assuming MessageController is some url in your domain and you are aware of the same origin policy