I am trying to post data to an php site which only contains php code which should be executed when the ID #mR-RateableFramePicture is being clicked on the first page. This is being done by a ajax request:
$('#mR-RateableFramePicture').dblclick(function() {
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: { rateableUserID: rateableUserID, rateablePictureID: rateablePictureID},
success: function() {
$('#DynamicContent').load('moduleRateable/scriptSavedStyle.php');
}
});
});
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
And here the url destination which ajax posts to:
<?php
// Start the session (enable global $_SESSION variable).
session_start();
// Include database-link ($conn).
include '../../scriptMysqli.php';
// Make global variable to simple variable.
$userID = $_SESSION["ID"];
//Save the rateable style to one owns libary of saved styles.
$ratedUserID = $_POST['rateableUserID'];
$ratedPictureID = $_POST['rateablePictureID'];
$sql = $conn->query("UPDATE styles WHERE userID = '$ratedUserID;' AND
pictureID = '$ratedPictureID' SET savedByUser = '$userID'");
?>
I get the following error messages:
Notice: Undefined index: rateableUserID in C:\xampp\htdocs\mystyle\app\moduleRateable\scriptSavedStyle.php on line 12
Notice: Undefined index: rateablePictureID in C:\xampp\htdocs\mystyle\app\moduleRateable\scriptSavedStyle.php on line 13
You are not passing the value of the variables rateableUserID and rateablePictureID in your $.ajax({}) call like below -
data: { rateableUserID: rateableUserID, rateablePictureID: rateablePictureID}. Unless they are defined globally you will get undefined value at the PHP end.Make sure you have the value assigned to rateableUserID and rateablePictureID before you make the call. However still you have to check whether you are actually passing that variable in your post request or not because PHP cannot find the key name.
The function should be like below
$('#mR-RateableFramePicture').dblclick(function() {
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: { "rateableUserID": rateableUserID, "rateablePictureID": rateablePictureID},
success: function() {
$('#DynamicContent').load('moduleRateable/scriptSavedStyle.php');
}
});
});
Related
I am working on the jquery to call a function to get the return value that I want to store for the variable email_number when I refresh on a page.
When I try this:
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
I will get the return value as 6 as only when I use alert(email_number) after the email_number = data;, but I am unable to get the value outside of a function.
Here is the full code:
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
return email_number;
}
However, I have been researching and it stated that I would need to use callback via ajax but I have got no idea how to do this.
I have tried this and I still don't get a return value outside of the get_emailno function.
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
async: true,
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
email_number = data;
}
});
I am getting frustrated as I am unable to find the solution so I need your help with this. What I am trying to do is I want to call on a get_emailno function to get the return value to store in the email_number variable.
Can you please show me an example how I could use a callback function on ajax to get the return value where I can be able to store the value in the email_number variable?
Thank you.
From the jquery documentation, the $.ajax() method returns a jqXHR object (this reads fully as jquery XMLHttpRequest object).
When you return data from the server in another function like this
function get_emailno(emailid, mailfolder) {
$.ajax({
// ajax settings
});
return email_number;
}
Note that $.ajax ({...}) call is asynchronous. Hence, the code within it doesn't necessarily execute before the last return statement. In other words, the $.ajax () call is deferred to execute at some time in the future, while the return statement executes immediately.
Consequently, jquery specifies that you handle (or respond to) the execution of ajax requests using callbacks and not return statements.
There are two ways you can define callbacks.
1. Define them within the jquery ajax request settings like this:
$.ajax({
// other ajax settings
success: function(data) {},
error: function() {},
complete: function() {},
});
2. Or chain the callbacks to the returned jqXHR object like this:
$.ajax({
// other ajax settings
}).done(function(data) {}).fail(function() {}).always(function() {});
The two methods are equivalent. success: is equivalent to done(), error: is equivalent to fail() and complete: is equivalent to always().
On when it is appropriate to use which function: use success: to handle the case where the returned data is what you expect; use error: if something went wrong during the request and finally use complete: when the request is finished (regardless of whether it was successful or not).
With this knowledge, you can better write your code to catch the data returned from the server at the right time.
var email_number = '';
// check if page refreshed or reloaded
if (performance.navigation.type == 1) {
var hash = window.location.hash;
var mailfolder = hash.split('/')[0].replace('#', '');
var emailid = 'SUJmaWg4RTFRQkViS1RlUzV3K1NPdz09';
get_emailno(emailid, mailfolder);
}
function get_emailno(emailid, mailfolder) {
$.ajax({
url: 'getemailnumber.php',
type: 'POST',
data : {
emailid: emailid,
mailfolder: mailfolder
},
success: function(data)
{
// sufficient to get returned data
email_number = data;
// use email_number here
alert(email_number); // alert it
console.log(email_number); // or log it
$('body').html(email_number); // or append to DOM
}
});
}
I have a simple HTML Form and in this form there is a section where the user can select one or more checkboxes.
I have written a JS function that gets the value of every checked box and puts it into a string:
function getSupportedDevices() {
var supportedDevices = "";
$('.devices:checkbox:checked').each(function () {
let sThisVal = $(this).val();
supportedDevices += sThisVal + ";";
});
console.log(supportedDevices);
return supportedDevices;
}
This function is called before the Ajax call and the result should be appended to the FormData so that I can use the string later on.
Here is the code from where I try to add the list:
var $debForm = $('#formDeb');
if ($debForm.length > 0) {
$debForm.on('submit', function (event) {
event.preventDefault();
if (!isSubmitting) {
let $form = $(this);
let targetUrl = $form.attr('action');
let method = $form.attr('method');
let $btnSubmit = getElement($form, '.js-btn-submit');
var myFormData = new FormData(this);
var supportedDevices = getSupportedDevices();
myFormData.append("supportedDevices", supportedDevices);
$.ajax({
type: method,
url: targetUrl,
data: myFormData,
async: true,
beforeSend: function () { ...
Running this code throws an error:
Uncaught TypeError: Illegal invocation
at add (jquery.js:8430)
at buildParams (jquery.js:8417)
at Function.jQuery.param (jquery.js:8450)
at Function.ajax (jquery.js:9040)
at HTMLFormElement. (submitdeb.js:45)
at HTMLFormElement.dispatch (jquery.js:5206)
at HTMLFormElement.elemData.handle (jquery.js:5014)
Line 45 is $.ajax. If I try data: new FormData(this).append("supportedDevices", getSupportedDevices()) as ajax parameter I get no error but the $_POST Array is empty.
What am I doing wrong that I get this error? The function to generate the string works on it's own and if I only send the FormData without anything appended, the $_POST Array is not empty.
Set processData:false to prevent $.ajax trying to serialize the FormData object using $.param() which it does by default when an object is passed to data.
The browser will handle the serializing internally
I'm adding a new record in my MySql DB with javascript and I have to elaborate this function in PHP.
$(document).on('submit', '#product_form', function(event){
event.preventDefault();
//btn_action="add_pricelvl"; //Set variable to call the add new item
var valdata = $(this).serialize(); //Array with field value
var tax = $('#item_tax').val(); //checkbox tax
var taxvalue = $('#item_taxvalue').val(); //inputbox tax
var tabledets = it_det //Read the detail table
.rows()
.data();
var arr1=[];//Declare the array
var i=0;
//Put the datatable(item_details) rows in the array
for (i=0; i<tabledets.length; i++){
arr1[i]=tabledets.rows(i).data();
}
//call ajax function and send variable to php file.
$.ajax({
processData: false,
url:'item_action.php',
method:"POST",
data:{
//btn_action:btn_action,
valdata:valdata,
tax:tax,
taxvalue:taxvalue,
arr1:arr1
},
success : function(data)
{
....
}
error : function () {
....
}
})
});
<?php
if ($_POST['btn_action']=='add_pricelvl'){
$query="....."
//Getting variables by JavaScript
}
?>
I can't get any variable in my PHP file... how is that possible?
Trying to check any $_POST[variable] in the PHP File they are NULL... why?
Try removing processData: false,. That command is telling jQuery to not turn the object into a query string. If you want to use $_POST[] in your script, it will expect it to be sent over as a query string.
http://api.jquery.com/jQuery.ajax/
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
To get the body from a POST call you should use something like this
$json = file_get_contents('php://input');
$json = urldecode($json);
$obj = json_decode($json, true);
Then you can manipulate $obj variable as a regular php array.
I am getting some basic info of the visitor on my site using javascript.
var userinfo = "";
//printing user info
$.get("http://ipinfo.io", function (response) {
alert("IP: " + response.ip);
alert("Location: " + response.city + ", " + response.region);
alert(JSON.stringify(response, null, 4));
userinfo = (JSON.stringify(response,null,4)); //saving json in js variable (not working, it says undefined)
}, "jsonp");
Then I want to access this value in my PHP variable:
<?php
echo $getuserinfo ; // How to store JS var here in this php var?
?>
The JS variable value is not being saved, what I am doing wrong?
And how can I store JS variable value in PHP variable?
You could make a stat page/api that you make a ajax call to from javascript.
$.ajax({
type: "POST",
url: '/setstats.php',
data: {userdata: userinfo},
success: function(){
console.log("Userdata send");
},
dataType: "json"
});
This will first be avalible at a later time then when the page initally loads, but you could now have it saved in the session for the next requests.
You are using jQuery.get method.
This method support a parameter called Data
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
After it is sent to the server to http://ipinfo.io it is available in the called script (index.php or what you have as default) in the $_GET array.
If you send data: {var1: value1, var2: value2} you will have $_GET["var1"] and $_GET["var2"]
Simply send data: userinfo and in php do a var_dump($_GET) and check what you got
I solved it by using the PHP version of the API:
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}");
$details = json_decode($json);
//echo $ip;
return $details;
}
$details = ip_details($userIp);
I am doing an Ajax request on an XML file and mapping the XML into a JavaScript object my problem is that am logging the object and seeing the values I won't but when I try to return the values I keep getting undefined, even that all the code is inside the success callback of the AJAX request, my code is as bellow:
// Errors Object
var ErrorsObject = {};
var ErrorApplet = $('.AppletStyle1 table td');
// Ajax Request
$.ajax({
type: "GET",
url: "ECA_ADMIN_IO.xml",
dataType: "xml",
cache: false,
success: function (xml) {
$(xml).find('EcaAdminBc').each(function () {
var code = $(this).find('code').text();
var msg = $(this).find('msg').text();
ErrorsObject[code] = msg;
});
// Reformat Errors
if(ErrorApplet.length > 0) {
$(ErrorApplet).each(function(){
var Error = $(this).text();
if(Error.indexOf("SBL") >= 0){
var ErrorCode = Error.split('(')[1].replace(")","");
var ErrorText = ErrorsObject[ErrorCode];
// The Log is showing the values correctly but i cant access the object values
console.log(ErrorsObject);
// ErrorText And ErrorCode Are always undefined !!
if(typeof ErrorText != 'undefined'){
$(this).text(ErrorText);
}
}
});
}
}
});
I need additional context, but I guess what the problem is. You are trying to do some thing like this:
var myFunction = function(){
// Error Object
var ErrorsObject = {};
var ErrorApplet = $('.AppletStyle1 table td');
$.ajax(
type: "GET",
url: "ECA_ADMIN_IO.xml",
dataType: "xml",
cache: false,
success: function (xml) {
//using response to fill ErrorsObject
ErrorsObject['Ok'] = 'This key has Value!';
//more awesome code here
//... lets check again:
console.log(ErrorsObject['OK']); //Outputs 'This key has Value!'
}
);
return ErrorsObject;
};
var myAwesomeErrorObject = myFunction();
console.log(myAwesomeErrorObject['OK']); //undefined!
console.log(myAwesomeErrorObject); //Empty object!
The problem is that myFunction finished before the success callback function gets executed (the callback is asynchronous). That is why logging myAwesomeErrorObject['OK'] shows undefined. I guess that you also tried return ErrorsObject inside the success callback, but that won't work either.
In order to fix your code you must either:
Use the ErrorsObject inside the success callback (i.e. don't return it).
Call a second function from inside the success callback, passing it the ErrorsObject.
Pass a calback function to myfunction and execute it from inside the success callback.