When a build name is clicked the inner html is passed into a JavaScript variable loadDump then passed over to PHP.
$.ajax({
url:"http://custom-assembly.tcad.co.uk/wp-content/themes/custom-assembly/grp-enclosure/load.php",
method: "post",
data: { loadDump: JSON.stringify( loadDump )},
success: function(res){
var key_map_obj = '<?php echo $key_map_loaded; ?>';
console.log(key_map_obj);
var key_map_obj_string = key_map_obj;
localStorage.setItem("key_map_obj_string", key_map_obj_string);
console.log(localStorage);
}
})
Once this happens the php in load.php executes. The loadDump variable is used in a sql query to find the matching field.
$loadDump = wp_unslash( $_POST['loadDump'] );
$table_name= $wpdb->prefix. 'product_configurator';
$DBP_results= $wpdb->get_results("SELECT * FROM $table_name WHERE keymap_key = $loadDump");
$DBP_current_user = get_current_user_id();
foreach($DBP_results as $DBP_cols){
$user_id= $DBP_cols->user_id;
$enclosure_type= $DBP_cols->enclosure_type;
$keymap_key= json_decode($DBP_cols->keymap_key, true);
$key_map_loaded=json_decode($DBP_cols->key_map, true);
}
?>
How can i get $key_map_loaded to pass to the JavaScript and save in the local storage using Ajax.
In you php file try to return the result :
e loadDump variable is used in a sql query to find the matching field.
$loadDump = wp_unslash( $_POST['loadDump'] );
$table_name= $wpdb->prefix. 'product_configurator';
$DBP_results= $wpdb->get_results("SELECT * FROM $table_name WHERE keymap_key = $loadDump");
$DBP_current_user = get_current_user_id();
foreach($DBP_results as $DBP_cols){
$user_id= $DBP_cols->user_id;
$enclosure_type= $DBP_cols->enclosure_type;
$keymap_key= json_decode($DBP_cols->keymap_key, true);
$key_map_loaded=$DBP_cols->key_map;
}
echo $key_map_loaded;
?>
Then in the JavaScript receive it for the ajax request:
$.ajax({
url:"load.php",
method: "post",
data: { loadDump: JSON.stringify( loadDump )},
success: function (data) {
var key_map_obj = data;
console.log(key_map_obj);
var key_map_obj_string = (key_map_obj);
localStorage.setItem("key_map_obj_string", key_map_obj_string);
console.log(localStorage);
},
})
Related
i want to assign javascript variable value to php variable to loop products
here is my php code:
$products = wc_get_products( array(
'include' => $products_ids // `**i want to pass value from javascript here**`
) );
foreach ( $products as $product ) {
// fetching my product details
}
here is my js code:
(function($){
$(document).ready(function(){
$(document).on('change', '#myform', function(e) {
e.preventDefault();
data = $(this).serialize();
var settings = {
"url": "<?php echo WC_AJAX::get_endpoint( 'myajaxfunction' ) ?>",
"method": "POST",
"data": data,
}
$.ajax(settings).done(function (result) {
// i want to make $products_ids = result
// result value is array(1,2);
});
});
});
})(jQuery);
**
i want to make $products_ids = result so i can pass it in my php
code,
result value is array(1,2);
**
I am using CI 3.0.1 was uploading and inserting image to db successfully before i used ajax, i guess trying to do it with ajax i'm missing something which isn't even sending data to upload maybe because we have to use multipart() in form while in ajax we are just sending data direct to controller, another thing i don't know how to receive the variable in response
my Ajax request function is:
<script type="text/javascript">
$(document).ready(function() {
alert("thirddddddddd");
$('#btnsubmit').click(function()
{
alert("i got submitted");
event.preventDefault();
var userfile = $("input#pfile").val();
alert("uploading");
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload', //how to receive var here ?
type: 'POST',
cache: false,
data: {userfile: userfile},
success: function(data) {
alert(data);
$('.img_pre').attr('src', "<?php echo base_url().'uploads/' ?>");
$('.dltbtn').hide();
},
error: function(data)
{
console.log("error");
console.log(data);
alert("Error :"+data);
}
});
});
});
And my controller Upload's function do_upload is:
public function do_upload()
{
$config['upload_path'] = './uploads/'; #$this->config->item('base_url').
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('layouts/header');
$this->load->view('home_page', $error);
$this->load->view('layouts/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$imagedata = $this->input->post('uerfile');
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$result = $this->model_edit->update_dp($id, $imagedata);
$image_name = $result->images;
$this->session->set_userdata('image', $image_name);
echo json_encode($name = array('image' => $image_name));
// $image_name = $this->upload->data('file_name');
// $data = array('upload_data' => $this->upload->data());
// redirect("account");
}
}
Now image is not even going to uploads folder, if any other file is needed tell me i'll post it here. Thanks
You cannot send file data using $("input#pfile").val();
var len = $("#pfile").files.length;
var file = new Array();
var formdata = new FormData();
for(i=0;i<len;i++)
{
file[i] = $("input#pfile").files[i];
formdata.append("file"+i, file[i]);
}
and send formdata as data from ajax
Hope it helps !
Try with the below ajax code
var formData = new FormData($('#formid'));
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload',
data: formData ,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
The file contents may not send through ajax as per your code. Try with the attributes mentioned in above code.
Hey guys im with a problem getting a value from php. I know we have a lot of problems with this kind of issues, but i need help.
This is my javascript
$( document ).ready(function() {
$(".loading_bg").hide();
});
$( document ).ajaxStart(function() {
$(".loading_bg").fadeIn("slow");
});
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = 'function=validate_user' + '&username=' + username + '&password=' + password;
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php',
data: datastring,
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
and this is my php
<?php
require_once('../#configs/db_connect.php');
//Lets send our data back to index
if(isset($_POST['function'])) {
$user = $_POST['username'];
$password = $_POST['password'];
echo login::validate_user($user, $password);
}
class login {
static function validate_user($username, $password) {
//Call a new default connection
$db = db::connect();
//Prepare our sql
$stmt = $db->prepare("SELECT * FROM Accounts WHERE username = :username AND password = :password");
//Bind our values to the SQL statement
$stmt->bindValue(':username', $username, PDO::PARAM_STR);
$stmt->bindValue(':password', $password, PDO::PARAM_STR);
$stmt->execute();
//Get number of affected rows
$results = $stmt->rowCount();
//If to check if we can find any row with username and password
if($results === 1) {
//return json_encode("valid account");
} else {
return json_encode($username);
}
}
}
?>
When i do the request im getting a undifned error from my var, i dont know how to fix it, can someone help me, if possible.
I think its something with my $_POST.. because if run the php with login::validate_user("teste","teste); i can get the json result..
Everything else is fine, you are not passing data correctly to ajax call. You are making query string but you have to pass JSON object if you want to capture it in $_POST in php and can append to url if you want to capture in $_GET array. I have corrected your function in both ways below:
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = { 'function': 'validate_user', 'username': username, 'password': password }
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php',
data: datastring,
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
When you want to capture data in $_GET at server side
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = 'function=validate_user' + '&username=' + username + '&password=' + password;
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php?' + datastring,
data: {},
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
Here is PHP Code
<?php
require_once('../#configs/db_connect.php');
//Lets send our data back to index
if(isset($_GET['function'])) {
$user = $_GET['username'];
$password = $_GET['password'];
echo login::validate_user($user, $password);
}
.... // Remaining Class will come here
Im sorry to bother all of you, the real problem its my form input feilds.. i forgot to set a class... Thank you all, and once again, im sorry to make you lose time with such a silly problem.
I'm working on a simple Ajax post method and here is my code:
<script type="text/javascript">
jQuery(document).ready(function($) {
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
var nextUrl = "<?PHP echo $nexturl;?>";
$('#Loading').show();
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'html',
data: {
next_url: nextUrl
},
}).done(function ( html ) {
$('#LoadedResults').html( html );
$('#Loading').hide();
});
}
});
});
</script>
This code is sending post data to ajax.php:
<?PHP
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$client_id = "1e0f576fbdb44e299924a93cace24507";
$Next_URL = $_POST["next_url"];
$url = $Next_URL;
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
$maxid = $results['pagination']['next_max_id'];
$nexturl = $results['pagination']['next_url'];
//Now parse through the $results array to display your results...
echo json_encode(array(
'next_url_link' => $nexturl
));
The ajax.php is echoing result as:
{"next_url_link":"https:\/\/api.instagram.com\/v1\/tags\/sweden\/media\/recent?count=24&client_id=1e0f576fbdb44e299924a93cace24507&max_tag_id=1427904820688670"}
I was looking here and there and i think there is some method with json with which i can get the result of next_url_link.
So guys, how can i get back the result printed for next_url_link and set is active jQuery/JavaScript variable ?
For example:
var NextUrlLink = data.next_url_link;
Is it possible somehome ?
Should i create two .ajax post methods or how, i have no idea ?
Thanks in advance!
Use the function JSON.parse() for it.
So here is how you will do it :
.done(function ( html ) {
var data = JSON.parse(html);
//now use data.next_url_link
$('#LoadedResults').html(data.next_url_link);
$('#Loading').hide();
});
Maybe you can use the success function to retrieve the data you encoded in your json
var NextUrlLink = []; //declare it as a global variable or somewhere within the same level or scope of where you want to use it so that you can use it
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'json',
data: {
next_url: nextUrl
},
success:function(data){
NextUrlLink = data.next_url_link;
}
})
i am using zf2. i want to load my second drop down by using the ajax call. i have tried with following code. i can get hard coded values. but i dont know how to add database values to a array and load that values to the drop down using ajax.
Ajax in phtml :
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
//code to load data to the dropdown
},
error:function(){alert("Failure!!");}
});
});
});
</script>
Controller Action:
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$projectusers[] = $this->getRoleTable()->fetchRoles($projectid);
// eturn a Json object containing the data
$result = new JsonModel ( array (
'projectusers' => $projectusers
) );
return $result;
}
DB query :
public function fetchRoles($id) {
$resultSet = $this->tableGateway->select ( array (
'projectid' => $id
) );
return $resultSet;
}
your json object new JsonModel ( array (
'projectusers' => $projectusers
) json object become like this format Click here for Demo
var projectkey = [];
projectkey = projectname.split(" - ");
var projectname = { "textData" : "+projectkey[1]+" };
$.ajax({
type:"POST",
url : "url.action",
data : projectname,
success : function(data){
$.each(data.projectusers,function(key,value){
$('#divid').append("<option value="+key+">"+value+"</option>");
});
});
});
<select id="divid"></select>
This is what i did in my controller. finaly done with the coding.
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$i=0;
$text[0] = $data->id. "successfully processed";
$projectusers = $this->getRoleTable()->fetchRoles($projectid);
foreach ($projectusers as $projectusers) :
$users[$i][0] = $projectusers->username;
$users[$i][1] = $projectusers->id;
$i++;
// eturn a Json object containing the data
endforeach;
$result = new JsonModel ( array (
'users' => $users,'count'=>$i
) );
return $result;
}
and the ajax is like this
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
// alert(data.users[0][0]+" - " + data.users[0][1] );
var count= data.count;
alert(count);
$('#myDropDown').empty();
for(var i=0;i<count;i++){
$('#myDropDown').append($('<option></option>').attr('value', data.users[i][1]).text(data.users[i][0]));
}
},
error:function(){alert("Failure!!");}
});
});
});
</script>
used the same zf2 query to access the database. thanks for the help everyone :)