How can I return an id value from a div already populated through ajax - ajax

I am having some difficulty passing a correct id function back to AJAX.
I'm creating a product bulletin generator that lets items to be added by their SKU code (which works fine). My problem is that when a bulletin is clicked on, a preview of that bulletin is loaded into a div and shows all products associated with that bulletin.
From inside those results, I am trying to add the ability to delete a product from the bulletin. The problem is that the value being passed back to AJAX belongs to the first product only. It won't send the value belonging to the particular item if it is any other item than the first one.
This is the code (belonging to main.php) that gets loaded via AJAX into a div and is looped with each product associated with a selected bulletin
echo "<form name='myDelForm'>
$news_gen_id<br>
<input type='hidden' id='delccode' value='".$news_gen_id."'>
<input type='hidden' id='deledit' value='".$edit."'>
<input type='button' onclick='ajaxDelCcode()' value='Delete' /><br></form>
</td>";
The AJAX code (on index.php, where the div that calls in main.php is also located) is this
function ajaxDelCcode(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new
ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("ajaxMain2");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var deledit = document.getElementById("deledit").value;
var delccode = document.getElementById("delccode").value;
var queryString = "?delccode=" + delccode + "&deledit=" + deledit;
ajaxRequest.open("GET", "main.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
Currently, using those two pieces of code, I can successfully delete only the first product. The delccode variables do not seem to change when the products are looped (although when I echo the variables during the loop, it is definitely changing to the appropriate value...it's just not passing it correctly back to AJAX.)
I tried taking the AJAX code, putting it inside the main.php product loop, and change the function name during each loop (so ajaxDelCcode$news_gen_id() for example) and also to the button itself so that it is calling the AJAX specific to it. And it works if you are visiting main.php directly...but not from index.php after main.php has been called into the div.
I can't figure out how to pass the correct looped value from main.php within the div, back to the AJAX code on index.php
Can anyone help me with this?
Thanks,
Dustin

Instead of storing the id in the input, just pass it as an argument to the function:
function ajaxDelCcode(delccode) { ...
<input type='button' onclick='ajaxDelCcode(\"".$news_gen_id."\")' value='Delete' />
Also, I'd swap the quotes if I were you. Or better yet, instead of using echo, break the PHP code and just write HTML:
<? ... ?><input type="button" onclick="ajaxDelCcode('<?= $news_gen_id ?>')" value="Delete" /><? ... ?>

What does the code you use to delete look like? Is it in the same php file as the form you posted above? If so, is the form getting submitted to itself accidentally? Like perhaps when a user presses enter while on an input type=text control? I understand that you want to do this by ajax but I am suspecting that the form is your problem.
Seconding the jQuery comment.

Here try this
1) add jquery to your document.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
2) give your inputs name attributes
<input type='hidden' name='delcode' id='delccode' value='".$news_gen_id."'>
<input type='hidden' name='deledit' id='deledit' value='".$edit."'>
3) Use a function something like this instead of all that code above
function ajaxDelCcode() {
$.ajax({
url: "main.php",
type: "GET",
dataType: "text",
data: $("#myDelForm").serialize(),
success: function(rText) {
$("#ajaxMain2").text(rText);
}
});
}

Related

Can't get wordpress ajax form to submit

I am porting an application to WordPress. It uses a form to select what attributes the customer is looking for in an Adult Family Home via checkboxes and drop-downs. It re-searches the database on each onchange and keyup. Originally I had the application standalone in PHP, but when I migrated it to WordPress I started having issues.
Currently in WP I have the code conditionalized ($DavesWay == 1) to do ajax the normal no-WordPress-way and ($DavesWay == 0) to do it the WordPress-way.
In the non-WordPress-way, the ajax works fine EXCEPT that I get a WP header and menu between the search form and the results-div that Ajax puts the data in. I get no errors from WP or in the JS console. In the WP-way The search form displayed, but nothing happens when I check any of the checkboxes. The JS console displays
POST http://localhost/demo4/wp-admin/admin-ajax.php 400 (Bad Request)
But I don't see any way to tell exactly what it is complaining about. How should I troubleshoot this?
Troubleshooting = Examine the HTML output, lots of echos and exits in PHP code, look at JS console.
function submitPg1(theForm) {
// Used with onChange from "most" form elements, but not on those that change the page
// rather than the select criteria. Such as rowsPerPage, pageNumber etc.
setById("pageNo", "1"); // set inital page
mySubmit();
}
function mySubmit(theForm) { // The actual ajax submit
// DO NOT set page number
jQuery.ajax({ // create an AJAX call...
data: jQuery("#asi_search_form").serialize(), // get the form data
type: jQuery("#asi_search_form").attr("method"), // GET or POST
url: jQuery("#asi_search_form").attr("action"), // the file to call
success: function (response) { // on success..
jQuery("#result").html(response); // update the DIV
}
})
}
function setById(id, value) { // Used to set vales by Id
x = document.getElementById(id).value;
x.value = value;
}
// 1st submit with blank selection
jQuery(document).ready(function () { submitPg1(this.form) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Code fragments: (from the displayed page source)
<div id="asi_container" class="asi_container" >
<noscript><h2>This site requires Javascript and cookies to function. See the Help page for how to enable them.</h2></noscript>
<div id="searchForm">
<form id="asi_search_form" name="asi_search_form" method="post" action="http://localhost/demo4/wp-admin/admin-ajax.php">
<input type="hidden" name="action" value="asi_LTCfetchAll_ajax" style="display: none; visibility: hidden; opacity: 0;">
<table id="greenTable" class="asi_table" title="The Green areas are for site administration, not typical users">
<tbody>
PHP code:
$DavesWay = 0;
if ($DavesWay == 1){ //echo "Daves Way Setup"; // Dave's way, which works but prints the menu twice
if( $operation == "submit"){
require("asi_LTCfetchAll.php"); // for each onchange or onkeyup
}else{
add_filter( 'the_content', 'asi_tc_admin', '12' ); // Initial page refresh # must be >12
}
}else{
// The WordPress way that I could't get to work -- asi_LTCfetch never gets called
function asi_LTCfetchAll_ajax(){
//echo "<br /> Goto to Submit function"; // DEBUG
require($asi_plugin_dir . "/includes" . '/asi_LTCfetchAll.php');
}
add_action( "wp_ajax_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // admin users
add_action( "wp_ajax_nopriv_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // non-logged in users
add_filter( "the_content", "asi_tc_admin", "12" ); // Initial page refresh # must be >12
}
Try changing the JavaScript to the way WordPress recommends it in their documentation:
var data = {
'action': 'my_action',
'whatever': 1234
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
I suggest trying following URL: https://codex.wordpress.org/AJAX_in_Plugins
Also you can use the plugin: https://wordpress.org/plugins/ajax-search-lite/

Ajax send parameters through url

I'm new with ajax and thought i'd be a fun experiment to put into my project. I've created my own lightbox type feature to send a message on a website I'm creating. When the user clicks "Send Message", that's when the lightbox appears, and at the top I'm trying to get it to say "Send message to User", where User is the name of the user they're sending a message too. My lightbox html elements are actually on a seperate webpage, which is why I'm using ajax. this is what I have so far, and can't seem to figure out what the problem is:
user.php page
<div id = "pageMiddle"> // This div is where all the main content is.
<button onclick = "showMessageBox(UsersName)">Send Message</button>
</div>
Note: The username passes correctly into the javascript function, I have checked that much.
main.js page
function showMessageBox(user){
alert(user); // where i checked if username passes correctly
var ajaxObject = null;
if (window.XMLHttpRequest){
ajaxObject = new XMLHttpRequest();
}else if (window.ActiveXObject){
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (ajaxObject != null){
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.send("u="+user);
}else{
alert("You do not have a compatible browser");
}
ajaxObject.onreadystatechange = function(){
if (ajaxObject.readyState == 4 && ajaxObject.status == 200){
document.getElementById("ajaxResult").innerHTML = ajaxObject.responseText;
// use jquery to fade out the background and fade in the message box
$("#pageMiddle").fadeTo("slow", 0.2);
$("#messageFormFG").fadeIn("slow");
}
};
}
message_form.php page
<div id = "messageFormFG">
<div class = "messageFormTitle">Sending message to <?php echo $_GET['u']; ?></div>
</div>
Note: When accessing this page directly through the URL, giving it a parameter of u and a value, it displays correctly
Use jQuery.ajax();
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
url: "message_form.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
freakish way to do it (old school) :)
anyway i think the problem may be that you are loading an entire html page to a div! meaning tags and stuff, a good way to understand what's wrong would be to use a debugger and see what comes in ajaxObject.responseText.
Hope this helps.
Btw convert to jQuery ajax!! saves you loads of time =)
I believe that you need to add a request header prior to sending your data. So you'd have this:
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxObject.send("u="+encodeURIComponent(user));
Instead of what you have.
However, it may be a good idea to allow a library to do this for you. It looks like you already have jQuery loaded, so why not let it handle your AJAX requests instead?
I figured it out after watching some ajax tutorials from bucky :) aka thenewboston. If I'm using the GET method, i just had to add the parameter to the end of the url in the .open function, instead of passing it through the send function (like you would a post method).
if you want to send number of field values using ajax.you can use serilalize function.
Example:
jQuery.ajax({
url: 'filenamehere.php',
type: 'post',
data: $("#formidhere").serialize(),
success: function(data){
..//
}
});

Strange issue with ajax POST

I have this html page with the form
<form method="post" id="form1" name="form1" action="/status_comment/save">
//Some text inputs
<input type="text" name="new_comment" id="new_comment" onkeydown="post_comment(event,'13')" >
</form>
And this is my javascript function to do the POST call
function post_comment(event,item_id)
{
var keyCode = ('which' in event) ? event.which : event.keyCode;
if(parseInt(keyCode)==13 && event.shiftKey!=1)
{
var str = $('#form1').serialize(); // Gets all the filled details
$.post('/status_comment/save',
str,
function(data){
alert(data);
});
}}
Backend is done using Django and this is the return statement
data=simplejson.dumps(data)
return HttpResponse(data, mimetype='application/json')
The referral url is say "/xyz".
The thing is, after the form gets submitted, it is being automatically redirect to the "/status_comment/save" page instead of remaining on the same page.
I tried the get method and it works fine but not the POST method.
I tried debugging it, so changed the url in post call to the referral url, then it refreshs the page instead of doing nothing.
Also the alert() command inside the function above doesnt work, so its probably not being entered into.
Interesting thing I have noticed, when looking at the web developer console, the Initiator for the POST call in this page is being displayed as "Other" while the initiator for GET call and POST call (in other pages, where its working) is "jquery-1.8.0.min.js:2"
Any thoughts? Thanks...
First you really shouldn't try to capture the enter if you can avoid it. Use the submit binding. It makes everything more obvious and easier for your fellow developers (I bet I am not the only one who thought "What the heck is KeyCode 13?").
I'm wondering if perhaps being more explicit might help. Have you tried calling preventDefault and stopImmediatePropagation?
$('#form1').submit(function(evt) {
evt.preventDefault();
evt.stopImmediatePropagation();
// serialize and be AJAXy yada yada yada
If that doesn't work, or for some reason you prefer to handle capturing enter on your own, then you might want to have the above code in addition to your keydown handler. So it would be:
<input type="text" name="new_comment" id="new_comment" onkeydown="post_comment(event,'13')" >
...
$('#form1').submit(function(event) {
event.preventDefault();
event.stopImmediatePropagation();
}
function post_comment(event,item_id)
{
event.preventDefault();
event.stopImmediatePropagation();
var keyCode = ('which' in event) ? event.which : event.keyCode;
if(parseInt(keyCode)==13 && event.shiftKey!=1)
{
var str = $('#form1').serialize(); // Gets all the filled details
$.post('/status_comment/save',
str,
function(data){
alert(data);
});
}
}
Start by getting rid of the onkeydown attribute from the input:
<form method="post" id="form1" name="form1" action="/status_comment/save">
//Some text inputs
<input type="text" name="new_comment" id="new_comment" />
</form>
And then simply subscribe to the .submit() event of this form using jquery and perform the AJAX request in there. Don't forget to return false from it to ensure that the default action is canceled and the browser stays on the same page:
$('#form1').submit(function() {
var str = $(this).serialize(); // Gets all the filled details
$.post(this.action, str, function(data) {
alert(data);
});
return false; // <!-- that's the important part
});

Upload onload don't work on firefox iframe

I am having a problem in Firefox with a file uploading into an iframe. An anchor should call the function dosubf() that posts the form to the iFrame to upload a XML file that will be parsed later with Ajax and displayed in another form on the same page.
The iframe is generated dynamically into a div tag. When it loads the first time, works fine, but, in Firefox, when reloading the content into the div, result on an error 'var ret is null'! caught by the firebug extension. I have also noticed that another error occurs on a xmlhttp.open("POST", var, var.length) call that is made in order to generate one select html object into a table cell. Again the error shows that some var is null but in this case the function that dropping the program is out of the scope! Both functions are working fine in IE9.
For the first issue I think that it could be something related to the onload event. For the second I really don't know what's happening.
Below is the code that load an html form with method Ajax into the div for the initial input of the XML file.
<form id='file_upload_form' method='post'
enctype='multipart/form-data' target='upload_targetf'
action='include/php/util/handle/handlexml.php'>
<input name="file" id="file" type="file" />
IMPORT
<iframe id='upload_target' name='upload_targetf' onload='lerxml()' ></iframe>
</form>
The javascript for the event onclick of the button that submits the form.
function dosubf(){
if (document.getElementById('file').value==''){
alert ("Por favor seleccione um arquivo");
return
}
document.getElementById('file_upload_form').submit();
}
And the function for the event onload that is firing well when it's the first load into the div of the HTML shown before, but fails when I refresh with Ajax that content on the div and try fire the onload. It fails in the second time on the fire empty onload iFrame and of course on button action submit onload.
function lerxml(){
var ret = window.frames['upload_targetf'].document;
//Here the code breaks with a ret is null error on firebug!
var novostring='';
var d=ret.body.innerHTML;
var mess='';
if (d!=''){
d=eval("("+d+")");
//This for getting the JSON response to evaluate the file
if (d.tipo){
mess+=(d.tipo);
}
if (d.tamanho){
mess+=(d.tamanho);
}
var ok='';
if (d.sucesso){
//The filepath of the uploaded file to use Ajax for parse it later
novostring="arquivo/xml/"+d.sucesso;
}else{
novostring="";
alert (mess);
return
}
}
The PHP that evaluate the file upload to the iFrame
<?
$erro = $config = array();
$arquivo = isset($_FILES["file"]) ? $_FILES["file"] : FALSE;
$config["tamanho"] = 500000;
if($arquivo){
if(!preg_match("/^text\/xml$/",$arquivo["type"])) {
$erro['tipo'] = "Não é um arquivo XML! Por favor seleccione outro arquivo";
} else {
if($arquivo["size"] > $config["tamanho"]) {
$erro['tamanho'] = "Arquivo em tamanho muito grande!";
}
}
if(sizeof($erro)) {
foreach($erro as $err) {
$err=htmlentities($err);
}
echo json_encode($erro);
die;
}else {
$imagem_nome = md5(uniqid(time())) . ".xml";
$imagem_dir ['sucesso'] = "arquivo/xml/" . $imagem_nome;
move_uploaded_file($arquivo["tmp_name"],"../../../../".$imagem_dir ['sucesso']);
echo json_encode(htmlentities($imagem_dir));
}
}
?>
Well I hope 'twas clearly enough to reach some help from you.
Thank you in advance for any comments.
I bet you're running into https://bugzilla.mozilla.org/show_bug.cgi?id=170799
Try replacing window.frames['upload_targetf'].document with document.getElementById("upload_target").contentDocument, which won't have the same issue.

how to create an function using jquery live?

I am writing a function that well keep the user in lightbox images while he adds to cart.
When you click any image it well enlarge using lightbox v2, so when the user clicks the Add image, it will refresh the page. When I asked about it at jcart support they told me to use jquery live, but I dont know how to do that. T tried this code but still nothing is happening:
jQuery(function($) {
$('#button')
.livequery(eventType, function(event) {
alert('clicked'); // to check if it works or not
return false;
});
});
I also used
jQuery(function($) {
$('input=[name=addto')
.livequery(eventType, function(event) {
alert('clicked'); // to check if it works or not
return false;
});
});
yet nothing worked.
for code to create those images http://pasite.org/code/572
I also tried:
function adding(form){
$( "form.jcart" ).livequery('submit', function() {var b=$(this).find('input[name=<?php echo $jcart['item_id']?>]').val();var c=$(this).find('input[name=<?php echo $jcart['item_price']?>]').val();var d=$(this).find('input[name=<?php echo $jcart['item_name']?>]').val();var e=$(this).find('input[name=<?php echo $jcart['item_qty']?>]').val();var f=$(this).find('input[name=<?php echo $jcart['item_add']?>]').val();$.post('<?php echo $jcart['path'];?>jcart-relay.php',{"<?php echo $jcart['item_id']?>":b,"<?php echo $jcart['item_price']?>":c,"<?php echo $jcart['item_name']?>":d,"<?php echo $jcart['item_qty']?>":e,"<?php echo $jcart['item_add']?>":f}
});
return false;
}
and it seems to add to jcart but yet it still refreshes
.live() is to assign handlers to future creating elements. On your site, however, you are re-loading the page so .live would have no bearing. (you are submitting a form)
It sounds like you want to make an ajax request to add the item to the cart and update that display on the site? That would be in the submit of the form and if jcart is dynamically created then yes, live is the answer.
$('.jcart').live('submit', function() {
// aggregate form elements into object and send via ajax
// update the cart on the page, since we haven't reloaded the page the light box is still displayed
});
Regarding comment:
When you send an ajax request, jquery takes an object as an argument. Such as $.post('urlToPostTo.php', { title: 'title of whatever', id: 5 } );
The server sees this the same as:
<form id="myForm" action="uroToPostTo.php" method="POST" >
<input type="text" name="title" value="title of whatever" />
<input type="hidden" name="id" value="5" />
<input type="submit" name="submit" value="submit" />
</form>
So if you were to aggregate the form inputs into an object, there's a few ways (even some jquery plugins to help you out). The primitive way would be:
var $form = $('#myForm'); // instead of finding myForm over and over, cache it as a variable to use
var objToSend = {};
objToSend.title = $form.find('input[name=title]').val();
objTosend.id = $form.find('input[name=id]').val();
$.post( 'urlToPostTo.php', objToSend );
A more Elegant solution is to have something loop through all form elements and put them into an object for you. Plugins like http://docs.jquery.com/Plugins:Forms make that a bit easier.
The end result is the form elements are stuffed into an object to send to your script.

Resources