I am trying to send an array from javascript to PHP script using ajax. This is the code I have so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" >Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
$(".output")
.each(function() {
var parms = [];
parms.push($(this).text());
});
</script>
<script>
function loadXMLDoc()
{
$.ajax({
type: "POST",
url: "update.php",
data: { value : $(parms).serializeArray() },
success: function(data)
{
console.log (data);
}
});
}
$("button").on('click',function(){ loadXMLDoc(); });
</script>
In my $.output function, I am using the parms [] array to store all the UI slider values which I am trying to pass on to the next PHP script page on a button click event as defined in loadXMLDoc() function. In my PHP page, I am accessing them as below.
<?php
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
// Do whatever you want with the $uid
?>
However, I am not able to view the data in my update.php script. Can someone please let me know what am doing wrong?
This is the link to my work so far.
serializeArray returns the json object ,maybe you could try json_decode in your php script,simply like:
$uid_arr = json_decode($uid,true);
print_r($uid_arr);
Just Use
data: $(parms).serializeArray()
Related
I'm trying to evaluate the values of all checked checkboxes and pass the result
to html text input I'm trying to do that using php and ajax but I have no good result please help
this is my code:
$(document).ready(function ()
{
$("#check").click(function ()
{
var data = $("#check").val();
//get selected parent option
$.ajax(
{
type: "GET",
data:data,
url: "total.php?val="+data,
cache: false,
success: function (data)
{
$("#tot").html(data);
}
});
});
});
</script>
</head>
<?php
$conn = mysqli_connect("localhost", "root", "", "voucher_test");
$result = mysqli_query($conn, "SELECT * FROM vouchers where cat_id = 1");
while ($row = mysqli_fetch_array($result)) {
$userSet[] = $row;
}
?>
<form action="index.php" method="post">
<?php
foreach ($userSet as $key=>$value){
echo $value['service_name']."<input type='checkbox' id='check' name='{$value['service_name']}' value='{$value['service_price']}'>";
}
?>
<br>
<div id="tot"></div>
</form>
and this is total.php
<?php
$itot = 5;
$itot+=$_GET['val'];
echo"<input type='text' value='$itot'>";
You can use this code to sent value to server y o n
var data = ($("#check").is(":checked") ? 'y' : 'n';
If you want send the value of checkbox, try this code:
var data = new FormData();//Create FormData
if($("#check").is(":checked")){//Verified if the input os checked
data.append('data-check',$("#check").val());//Add data of the checkbox to FormData
}
$.ajax(
{
type: "GET",
data: data,
url: "total.php",
cache: false,
success: function (data)
{
$("#tot").html(data);
}
});
In yur php
$_GET['data-check'];
I don't think you need to use the total.php file, but if you really want to use it I recommend to change your code to this:
<?php
$itot = 5;
$itot+=$_GET['val'];
echo"<input type='text' value='" . $itot . "'>";
The only change is the concatenation of the string you are printing
I have been trying to make to make a page where i could select a customer and would get the corresponding customer details from a database.
It should look something like this:
<select id="select_customer">
<option value='1'>customer 1</option>
<option value='1'>customer 2</option>
</select>
public function getCustomerDetails($customerId) {
if(isset($customerId)) {
$customer = DB::getInstance()->query("select * from customers");
foreach($customer->results() as $customer) {
$str = "<li>{$customer->name}</li>";
$str .= "<li>{$customer->name_contactperson}</li>";
$str .= "<li>{$customer->email}</li>";
$str .= "<li>{$customer->address} {$customer->house_number}</li>";
$str .= "<li>{$customer->postalcode}</li>";
$str .= "<li>{$customer->city}</li>";
$str .= "<li>{$customer->country}</li>";
}
return $str;
}
return false;
}
What i now would like to do is to get the value from the select_customer post this with ajax to the getCustomerDetails method and get the corresponding details without a page reload.
I tried to make it work with ajax and with xAjax but i coulden't get it to work.
I tried this:
<?php include 'xajaxAIO.inc.php';
$xajax = new xajax();
$xajax->register(XAJAX_FUNCTION, 'getCustomers');
$xajax->processRequest(); ?>
<input type="button" onclick="xajax_getCustomerDetails(1);" value="Click Me" />
The other thing i tried was this:
<script>
document.getElementById('select_customer').addEventListener('change', function() {
var $userId = this.value;
$.ajax({
type: "POST",
url: "classes/invoice.php",
data: "getCustomerDetails("+$userId+")"
})
});
</script>
I dont get any error messages in my console but it seems like the requested function doesnt execute.
Anybody who could tell me how it could get this to work?
Thanks in advance!
I would recommend just sending $userId alone then call getCustomerDetails($userId) in the invoice.php page.
$.ajax({
type: "GET",
url: "classes/invoice.php",
data: $userId
})
});
OR
$.ajax({
type: "GET",
url: "classes/invoice.php&function=getCustomerDetails&userId="+$userId
dataType: "json", //Dont need this if youre returning a string
success: function(result) {
alert(result);
}
})
});
Then in the invoice page you could call the function using the $_GET variable like so:
$response = 'error;
if($_GET['function'] == 'getCustomerDetails'){
if(!empty($_GET['userId'])){
$_GET['userId'] = 0;
}
$userID = $_GET['userId'];
$response = getCustomerDetails($userID);
}
die(json_encode($response)); //for array
die($response); //for a string
If you use xajax framework... you need register the new function...
<?php include 'xajaxAIO.inc.php';
$xajax = new xajax();
$xajax->register(XAJAX_FUNCTION, 'getCustomers');
$xajax->register(XAJAX_FUNCTION, 'getCustomerDetails');
$xajax->processRequest(); ?>
<input type="button" onclick="xajax_getCustomerDetails(1);" value="Click Me" />
<?php function getCustomerDetails($id){
///////////////////////////////////////////////
///// And use framework xajax to response /////
///////////////////////////////////////////////
}?>
I have searched through a couple of QA here at stackoverflow, none of solutions seemed to help. I am trying to pass input to my PHP file but for some reason the inputdoesn't get passed from javascript to and it keeps on returning undefined on the console.
my javascript:
$.ajax({
type:"GET",
url:"go.php",
data:{input:input},
success:function(data){
console.log(data); //data outputs https://mp3skull.wtf/search_db.php?q=&fckh=1d41a1579f21a921d1008d90dc6246a7
}
});
my php:
<?php
$input = $_GET['input']; //$input here is empty
$keywords= explode(" ",$input);
$link = "https://mp3skull.wtf/search_db.php?q=" . $keywords[0];
for($i = 1; $i < count($keywords); $i++){
$link .= "+" . $keywords[$i];
}
$link .= "&fckh=1d41a1579f21a921d1008d90dc6246a7";
echo $link; //$keywords is not appended to $link
?>
the code works you probably console.log from outside the ajax call.
hi first you need to declare it as a variable. Second does your variable really have a value? I'll give u sample you can run your code do it something like this
var input = $("#input").val();
$.ajax({
type:"GET",
url:"go.php",
data:{input:input},
success:function(data){
console.log(data); //data outputs https://mp3skull.wtf/search_db.php?q=&fckh=1d41a1579f21a921d1008d90dc6246a7
}
});
hope this helps
If you have the following Html:
<input type="text" class="field" />
<input type="button" class="button">
You should use the following script:
$(document).ready(function() {
$('.button').click(function(){
$.ajax({
type:"GET",
url:"go.php",
data:{'input':$('input.field').val()},
success:function(data){
console.log(data);
}
});
});
});
I think it's because when you send data in "data: { input: input } " are defining the variable input with the same name. It should be like that
var inputValue = $("#idInput").val();
$.ajax({
type:"GET",
url:"go.php",
data:{input:inputValue},
success:function(data){
console.log(data);
}
});
I have created an AJAX that can store and delete data from database. The adding of data is working fine also the delete function is working fine when the page is already refresh but the delete is not working when data is newly added or when the page is not refresh.
This how it works. When a new data is added, the data will display, the user has an option to delete the data or not. The data has a "X" to determine that it is a delete button. Right now, The delete only works when the page is refresh.
This my SAVING script, as you can see if saving is success it displays the data automatically, together with the span that has the delete function.
$("#wordlistsave").click(function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var words = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var ctrtest = 2;
var testBoxDiv = $(document.createElement('div'))
.attr("id", words);
var dataString = 'user='+user+'&title='+title+'&words='+words+'&id='+postID;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(postID)
{
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words+'" style="cursor:pointer">x '+postID+'</span>  <input type="checkbox" name="words[]" value="'+ words+ '">'+words );
testBoxDiv.appendTo("#test_container");
ctrtest++;
}
});
<?php else: ?>
alert('Fail.');
<?php endif; ?>
});
This is my delete function , when the user click the "X" span, the data will be deleted, but this only works after the page is refresh.
$("span").click(function()
{
var queryword=$(this).attr('id');
var postIDdel = $("#getPostID").val();
var dataString = 'queryword='+queryword+'&postID1='+postIDdel;
<?php if (is_user_logged_in()): ?>
$.ajax({
type: "POST",
url: "<?=plugins_url('worddelete.php', __FILE__ )?>",
data: dataString,
cache: false,
success: function(html)
{
$('div[id="'+queryword+'"]').remove();
}
});
<?php else: ?>
<?php endif; ?>
});
This is my HTML, the one that holds the querying of data and displaying of data.
<?php
global $wpdb;
$query_wordbanklist = $wpdb->get_results("SELECT meta_value, meta_id FROM wp_postmeta WHERE post_id = '$query_id' AND meta_key = '_wordbanklist'");
if($query_wordbanklist != null)
{
echo "<h3> Wordlist </h3>";
foreach($query_wordbanklist as $gw)
{
?> <div id="<?php echo $gw->meta_value ?>">
<span id="<?php echo $gw->meta_value ?>" style="cursor:pointer">x</span>   <input type="checkbox" name="words[]" value="<?php echo $gw->meta_value ?>"><?php echo $gw->meta_value; ?>
</div>
<?php
}
}
?>
All I wanted to achieve is to make the delete function works right after the data is stored. Right now it only works when the page is refresh. Any idea on this?
Perhaps try this...
$(document).on('click', 'span', function() {
// delete stuff in here
}
I am passing an array from javascript to PHP using ajax. This is the code I have so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" >Update</button>
<head>
<script>
var parms = [];
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
$(".output")
.each(function () {
parms.push($(this).text());
});
function loadXMLDoc(parms) {
$.ajax({
type: "POST",
url: "update.php",
data: {
value: $(parms).serializeArray()
},
success: function (data) {
alert(data);
}
});
}
$("button").on('click', function () {
loadXMLDoc(parms);
});
alert(parms);
</script>
</head>
On click of button, I am trying to call the PHP script to edit the display of my web page. However, the ajax call to the below PHP statement alerts only the "Am I printed" line.
<?php
$uid = $_POST['value'];
echo "Am I printed";
echo $uid;
// Do whatever you want with the $uid
?>
Why is the $uid value not returned to my javascript? Is there something am doing wrong?