I'm trying to send variables from my JavaScript to a PHP file using AJAX but it's not working. I've looked through all the similar asked questions (there are a bunch) but have yet to find a solution.
This is my first php file (one with the form, sends data to JavaScript):
<option value="imageOne" data-cuteform-image='assets/SketchThumbnails/imageOne.png></option>
<input id="inputURLID" type="text" name="inputURL">
<button type="submit" onclick="handleInputs(document.getElementById('sketch').value, document.getElementById('inputURLID').value); return false;">Submit</button>
JavaScript (where AJAX call is):
var content = {
'sketch': pickedSketch,
'songUrl': enteredURL
};
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
PHP (loadSketch.php):
if(isset($_POST['songUrl']))
{
$temp = $_POST['songUrl'];
echo $temp;
echo "received AJAX data";
} else {
echo "nothing in post variable";
}
When I get redirected to loadSketch.php (from the successful ajax call), "nothing in post variable" gets echoed out. Any ideas what I'm doing wrong?
Any insight is much appreciated! :)
Nothing is in songURL because when your Ajax function returns it is redirecting to the same page you just posted to. It is creating a new HTTP request to that PHP file with no data sending to it. Remove the comments on the console messages and you'll see the correct echo messages.
$.ajax({
type: "POST",
url: "loadSketch.php",
data: content,
success: function (data, text) {
alert("success");
console.log(data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
You should not use a submit button because it makes the whole page reload; instead use normal buttons and handle the click events calling your AJAX function.
HTML:
<button onclick="doAjaxFunction(param1, param2);">Calling Ajax Function<button>
JavaScript:
function doAjaxFunction(val1,val2){
$.ajax({
type: "POST",
url: "loadSketch.php",
dataType: "json",
data: {"'value1':'"+ val1+"', 'value2':'"+ val2+"'"},
success: function (data, text) {
// alert("success");
// console.log(data);
// console.log(text);
window.location.href = "loadSketch.php";
},
error: function (request, status, error) {
alert(request.responseText);
}
});
Then just pick your POST parameters in loadSketch.php and use them.
PHP:
$x = $_POST['value1'];
$y = $_POST['value2'];
Related
In my dashboard.php I have a Javascript function that is called based on the user clicking a button. When the button is clicked, it calls a JavaScript function called getTeamMembers and values are passed across to it. The values passed across to this function are then sent to a PHP function (which is also located in dashboard.php).
However I am not getting any success and was hoping that someone could guide me on where I am going wrong. I am a noob when it comes to AJAX so I assume I am making a silly mistake.
I know my function is definitely getting the intended variable data passed to it, after doing a quick window.alert(myVar); within the function.
This is what I have so far:
function getTeamMembers(teamID,lecturer_id) {
var functionName = 'loadTeamMembersChart';
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: { functionName: 'loadTeamMembersChart', teamID: teamID, lecturer_id: lecturer_id },
success: function(){
alert("OK");
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
}
);
}
Before calling the desired php function, I collect the sent varaibles just before my php Dashboard class starts at the top of the file. I plan to pass the variables across once I can be sure that they are actually there.
However, when I click the button, nothing can be echo'd from the sent data.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if (!empty($_POST["teamID"]) && !empty($_POST["lecturer_id"]))
{
$teamID = $_POST['teamID'];
$lecturer_id = $_POST['lecturer_id'];
echo $teamID;
echo " is your teamID";
}
else
{
echo "no teamID supplied";
}
}
you else statement in you success function , and that's not how you set fail callback, try the following and tell us what do you see in the console.
function getTeamMembers(teamID,lecturer_id) {
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: {functionname: 'loadTeamMembersChart', arguments: [teamID, lecturer_id]},
success: function(data) {
console.log(data);
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
});
}
Seems like your function is not returning a success message when getting into the following statement.
if ($result) {
"Awesome, it worked"
}
Please try to add a return before the string.
if ($result) {
return "Awesome, it worked";
}
It can be other factors, but the information you provided is not enough to make any further analysis.
So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});
i want to post an input and select to an php site using ajax and get the result displayed in a span using the success function.
After searching, I can't get it really done, below is my code so far:
<span id="span_to_post_response"></span>
$(document).on("click", "#btn_to_click", function () {
var form_to_send_in_var = $("#form_to_serialize").serialize();
$.post('<?php echo base_url();?>api/mySite',form_to_send_in_var);
});
Where do I put my success function?
Instead of using .post function,Try using something like this
jQuery.ajax({
url: '<?php echo base_url();?>api/mySite',
type: 'POST',
data: {
// Send the data you want
// email: jQuery('.address').val()
},
success: function(data){
jQuery('#span_to_post_response').text(data);
},
error: function() {
jQuery('#span_to_post_response').text('Sorry, an error occurred.');
}
});
AJAX:
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
//alert(BASE_URL);
$.ajax({
type: "POST",
ContentType: 'application/json',
data: data,
url: BASE_URL + 'index.php?deo/dashboard',
error: function () {
alert("An error occoured!");
},
success: function (msg) {
alert('result from controller');
}
});
alert(data);
});
});
CONTROLLER:
public function dashboard() {
$data = $this->input->post('data');
$data = json_decode($data);
echo "<script>alert('count ".$data."');</script>";
}
Am trying to send value from my jquery, ajax to controller, am able to get value from my view page to jquery page and able to print that. But unable to send the value from ajax page to controller page, after sending the data i got the success data. but unable to get and print the data in my controller page. Thanks in advance
If your using firefox a good thing to use is firebug add on and then you can use the console to check for errors on there. To see if the ajax has any errors while sending.
Remove question mark after index.php? and I think your base url is not working correct try just.
Url
// With index.php
url: 'index.php/deo/dashboard',
// Or without index.php
url: 'deo/dashboard',
Or
// With index.php
url: <?php echo site_url('index.php/deo/dashboard');?>,
// Or without index.php
url: <?php echo site_url('deo/dashboard');?>,
Script
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
$.ajax({
type: "POST",
data: data,
url: 'index.php/deo/dashboard',
// url: <?php echo site_url('index.php/deo/dashboard');?>,
success: function (msg) {
alert('result from controller');
},
error: function () {
alert("An error occoured!");
}
});
alert(data);
});
});
Controller
public function dashboard() {
$data = $this->input->post('data');
echo "<script>alert('count ".$data."');</script>";
}
I am designing some PHP pages to process forms. In these pages I want to redirect if result is successful or print a message if there was an error. Structure of pages is like this:
$arg = $_POST["arg"];
if (isset($arg)) {
if (function($arg)) {
header ("Location: page2.php");
}
else {
echo "Response was not successfully";
}
}
else {
echo "$arg parameter was not defined";
}
When I need to print messages I use cftoast for JQuery (http://www.jqueryscript.net/other/Android-Style-jQuery-Toaster-Messages-Plugin-cftoaster.html)
To handle all forms I am using this Javascript function:
$(document).ready(function() {
$("#asynchronousForm").submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$("body").cftoaster({content: data});
window.location.href = ""; //Refresh page to clear possible errors
}
})
return false;
});
My problem is, when form redirects, sometimes appears problems like no redirection and shows empty toast, refreshing page with duplicated input fields... How can I solve this problem? I am using JQueryMobile as skeleton of my webpage.
A good way to handle AJAX responses is to use JSON.
It will allow you to send multiples data and do a redirect or show message depending of AJAX result.
In PHP you can use json_encode() to convert and array to JSON.
$arg = $_POST["arg"];
if (isset($arg)) {
if (function($arg)) {
exit(json_encode(array('redirect' => 'page2.php')));
}
else {
exit(json_encode(array('message' => 'Response was not successfully')));
}
}
else {
exit(json_encode(array('message' => $arg.' parameter was not defined')));
}
AJAX:
You just have to add dataType: 'json'.
You can also use $.getJSON()
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(json) {
if ( json.redirect )
window.location.href = json.redirect;
else
$("body").cftoaster({content: json.message});
}
})