I have this codes that will display words with checkbox. As you can see they are delimited by comma, and I used split() function to explode the string making it an array. I used for loop to iterate the words, but I'm getting an "undefined" for the words. It should automatically display the words with checkbox but the words display undefined. When I hit refresh, it displays the word properly and the there is a checkbox. I'm not sure where is the problem. Any idea on this?
$(document).on('click', '#wordlistsave', function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var word = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var words = word.split(", ");
for(var i = 0; i < words.length; i++)
{
var dataString = 'user='+user+'&title='+title+'&words='+words[i]+'&id='+postID;
<?php if (is_user_logged_in()): ?>
if(words[i])
{
$.ajax({
type: "POST",
url: "<?= plugins_url('wordlistsave.php', __FILE__) ?>",
data: dataString,
cache: true,
success: function(postID)
{
var testBoxDiv = $(document.createElement('div')).attr("id", words[i]);
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words[i]+'" style="cursor:pointer">\
<img src="./wp-content/plugins/wordwork/admin/pdfpreview/delete_icon.png" title="Delete word"></span>\
  <input type="checkbox" name="words[]" value="'+ words[i]+ '">'+words[i] );
testBoxDiv.appendTo("#test_container");
}
});
}
<?php else: ?>
alert('Please login.');
<?php endif; ?>
}
});
words is visible from success function, but when it executes you can't be sure for i value because it doesn't execute syncronously.
So, you can pass an extra param, words, to ajax setup dictionary and access it from success function. Like this:
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: true,
word : words[i],
success: function(postID)
{
var testBoxDiv = $(document.createElement('div')).attr("id", this.word);
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+this.word+'" style="cursor:pointer"><img src="./wp-content/plugins/wordwork/admin/pdfpreview/delete_icon.png" title="Delete word"></span>  <input type="checkbox" name="words[]" value="'+ this.word+ '">'+this.word );
testBoxDiv.appendTo("#test_container");
}
});
Also, you do not need to construct the data string for $.ajax, you can simply pass the data like:
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: {
user: user,
title: title,
words: words[i],
id: postID
}
Related
I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});
I'm trying to fill two text boxes with a single ajax whisperer. I got the following code:
HTML:
<input type="text" name="ICZ" id="ICZ">
<input type="text" name="ODB" id="ODB">
respond.php:
<?php
require_once("../inc/dbconnect.php");
$return_arr = array();
$term=iconv('UTF-8' ,'WINDOWS-1250',$_GET["term"]);
$SQL="some sql";
$RS=sqlsrv_query($Conn,$SQL);
while($row=sqlsrv_fetch_array($RS)) {
$id_lekar=iconv('WINDOWS-1250', 'UTF-8',$row["ID_LEKAR"]);
$jmeno=iconv('WINDOWS-1250', 'UTF-8',$row["JMENO"]);
$odborn=iconv('WINDOWS-1250', 'UTF-8',$row["ODBORN"]);
$row_array['value'] = $id_lekar;
$row_array['value1'] = $odborn;
$row_array['label'] = $id_lekar." - ".$jmeno." - ".$odborn;
array_push($return_arr,$row_array);
}
sqlsrv_close($Conn);
echo json_encode($return_arr);
?>
and jQuery:
$(function() {$('#ICZ').autocomplete({
source: 'respond.php',
minLength:5
});
});
This works but only affect one input field. I would like to fill both so I extend SQL query and extend respond.php with $row_array['value1']. Then I try to redone jQuery:
$(function() {$('#ICZ').autocomplete({
minLength: 5,
source: function(request, response){
$.ajax({
url: "respond.php",
type: "GET",
dataType: "json",
data: {term: request.term},
success:function(response){
var len = response.lenght;
if (len > 0){
var icz = response[0]['value'];
var odb = response[0]['value1'];
document.getElementById('ICZ').value = icz;
document.getElementById('ODB').value = odb;
}
}
});
}
});
});
But this just doesn't do much, no errors in console, I can see the GET request going on when I fill the field with 5 and more characters, but no response. When I try access respond.php?term=XXXXX I'm getting same response in both ways.
use JSON.parse
$.ajax({
url: "respond.php",
type: "GET",
dataType: "json",
data: {term: request.term},
success:function(response){
var response=JSON.parse(response); // parse json to object
var len = response.length;
if (len > 0){
var icz = response[0].value;
var odb = response[0].value1; //access values like this
document.getElementById('ICZ').value = icz;
document.getElementById('ODB').value = odb;
}
}
});
Look if you need to parse json. Print response in console and check if you need to parse it.
Var result =JSON.parse(response);
First of all i know there are multiple topics about this on stackoverflow, i read most of them but i still cant figure out why the following is not working.
So i have a form like this:
echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\" modifyPassword();\">
this is the modifyPassword function:
function modifyPassword(){
var newpw=prompt("Enter a new password");
if(newpw !== null){
$.ajax({
type: "GET",
url: "admin.php",
data: newpw,
success: function(data)
{
console.log(data);
}
});
}}
And when the form is actually submitted i want to get the value from what is typed in like this:
echo $_GET['data'];
This is all in the same file.
The output of $_GET['data'] does not show anything.
Can someone tell me what i am doing wrong?
//edit, more code:
I am using multiple forms, so here is the code that handles the form:
}elseif (isset($_GET['Modify'])){
echo $_GET['data'];
Form itself:
echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\" modifyPassword();\">
<input type='hidden' name='counter' value=\"$count\"/>
<input type=\"submit\" value=\"Modify\" name=\"Modify\"/>
Function that is provided:
<script type="text/javascript">
function modifyPassword(){
var newpw=prompt("Enter a new password");
if(newpw !== null){
$.ajax({
type: "GET",
url: "admin.php",
data: {data: newpw}, // passing a key/value pair
success: function(data)
{
console.log(data);
}
});
}}
</script>
data: newpw, should be data: {data: newpw}, This will result in $_GET['data'] being populated. In this case 'data' becomes the key, while 'newpw' is the value.
function modifyPassword(){
var newpw=prompt("Enter a new password");
if(newpw !== null){
$.ajax({
type: "GET",
url: "admin.php",
data: {data: newpw}, // passing a key/value pair
success: function(data)
{
console.log(data);
}
});
}}
I will argue that you should not use so many variables with the same name - just to make things less confusing during bug hunting.
I have some page with form, which loading some data to POST when i submit it. Then it links user to the next page. On this page I catch data from POST, and I have two dropdownlists, where the second one depends on the first. The first get's value from POST data:
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'"); </script>';
Where $GLOBALS["i"] = id from DB, which has kept in data from POST by previous page.
But it doesn't work for the second dropdownlist which depends on it:
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
I think it can be from the part of code, which realises depending of the second dropdown list:
<script>
jQuery(function(){
var id = jQuery(".mark").val();
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
jQuery(".mark").change(function(){
var id = jQuery(".mark").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
});
Where "mark" - first dropdownlist, "comm" - the second one.
This is the first part of my problem.
The second: I have some value on the page which depends on the value of the second dropdownlist. I tried to:
jQuery(".comm").change(function(){
var id = jQuery(".comm").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function(data){
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type:"POST",
url: "../wp-content/price.php",
data: {price1: price1,price2: price2,price3: price3,price4: price4,price5: price5,price6: price6,price7: price7,price8: price8, price9: data},
success: function(data){
jQuery(".summPrice").html(data);
}
});
}
});
But it works only one time, and i don't know why.
I'll be glad for any offers.
I don't have a full visibility of the rendered html and of the ajax responses, but I would give a try with:
Remove this lines
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'");
</script>';
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
And do something like this where you print the html
...
<select id="markid" data-val="<?php echo isset($GLOBALS["i"]) ? $GLOBALS["i"] : -1;?>"></select>
<select id="comm" data-val="<?php echo isset($GLOBALS["i1"]) ? $GLOBALS["i1"] : -1;?>"></select>
And in your javascript have something like
<script>
(function ($) {
//when everything is ready
$(fillUpCommOptions);
$(watchSelectsChanges);
function fillUpCommOptions() {
var id = $('#markid').data('val') ? $('#markid').data('val') : $('#markid').val();
$('#markid').removeAttr('data-val');//remove data-val, at next change event we want the select new val
$.ajax({
type: "POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function (data) {
//assuming data is something like
// '<option value="niceValue">nice value</option>
$("#comm").html(data);
if ($("#comm").data('val')) {
//apply values from post also for the second dropdown
// assuming that data contains and option with value == $("#comm").data('val')
$("#comm").val($("#comm").data('val'));
$('#comm').removeAttr('data-val');
$("#comm").change()//trigger change after setting the value
}
}
});
}
function watchSelectsChanges() {
$('#markid')
.off('change')//just in case, could not be needed
.on('change', fillUpCommOptions);
$('#comm')
.off('change')//just in case, could not be needed
.on('change', handleDependentValues);
}
function handleDependentValues() {
var id = $("#comm").val();
if (id) {
$.ajax({
type: "POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function (data) {
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type: "POST",
url: "../wp-content/price.php",
data: {
price1: price1,
price2: price2,
price3: price3,
price4: price4,
price5: price5,
price6: price6,
price7: price7,
price8: price8,
price9: data
},
success: function (data) {
jQuery(".summPrice").html(data);
}
});
}
})
}
}
})(jQuery);
I have the code at the bottom that get's a name from a hidden input type, and I want to send that to a php page but the ajax data returns empty. The console.log on line 4 returns the value, but the console.log on the bottom returns empty. I tried changing the way I assign data inside the ajax call according to this article but this didn't change anything. Any ideas?
$('.uploadImage input[name="userImage"]').on("change", function(){
var image = new FormData($('input[name="userImage"]')[0].files[0]);
var name = $('.hidden').attr("name");
console.log(name);
$.ajax({
type: "POST",
url: "includes/ajax-image.php",
processData: false,
data: name,
success: function(data){
console.log(name);
}
});
});
ajax-image.php
<?php
$name = $_POST["name"];
$dir = ("../user_img/".$name."");
if (!file_exists($dir)) {
mkdir($dir,0700);
}
?>
I added the ; at that line
Feel free to edit both of my code's, I really don't have and idea what to do next
The processData option here is not needed remove that and try again
try this
$('.uploadImage input[name="userImage"]').on("change", function(){
var image = new FormData($('input[name="userImage"]')[0].files[0]);
var name = $('.hidden').attr("name");
$.ajax({
type: "POST",
url: "includes/ajax-image.php",
processData: false,
data: {"name": name },
success: function(data){
console.log(data);
}
});
});
<?php
$name = $_POST["name"];
$dir = ("../user_img/".$name."");
if (!file_exists($dir)) {
mkdir($dir,0700);
}
echo $name;
?>