Ajax request inside ajax request fails - reloads the whole page again - php

So, basicly what I'm trying to achieve:
In index.php
I would enter products code to search for products information and it's images (that query is run in open_first.php, called via ajax post request).
It works just perfect..
When open_first.php is loaded, it displays me some images I can select from (when I click on the image, it's relevant checkbox get's checked containing the image id).
This works too, just fine.
BUT,
If I enter a code in the field: "productCodeCopy" and click on "confirmCodeCopy" -button it reloads the whole page, I mean index.php and everything I've entered is lost and I'm back in the starting point again. I don't understand why it does so. I suppose it has something to do with the fact, that the second ajax request is made from a dynamically created page (open_first.php)?? Do I miss something I should POST too?? Or what's the problem, this is really frustrating me since I've tried to fix this for hours now.
Note:
Jquery is loaded in index.php, open_first.php and open_second.php, I've just ignored that to keep the code simpler.
FILE: index.php (the "starting point")
<!-- head -->
<script type="text/javascript">
$(document).ready(function() {
$("#confirmCode").on('click', function(){
var productCode = $("#productCode").val();
$.ajax({
url: 'open_first.php',
type: "POST",
data: ({code: productCode}),
success: function(data){
$("#found").html(data);
},
error: _alertError
});
function _alertError() {
alert('error on request');
}
});
});
</script>
<!-- body -->
<input type="text" class="textfields" id="productCode" name="productCode" value="YT-6212">
<input type="button" class="admin-buttons green" name="confirmCode" id="confirmCode" value="Search">
<div id="found"></div>
FILE open_first.php
<script type="text/javascript">
$(function() {
$("#foundImage").on('click', function(){
$('#foundImage').toggleClass("foundImage-selected foundImage");
var myID = $('#foundImage').data('image-id');
var checkBox = $('input[id=selectedImages-'+myID+']');
checkBox.prop("checked", !checkBox.prop("checked"));
});
$("#confirmCodeCopy").on('click', function(){
var checkedItems = $('input:checkbox[name="selectedImages[]"]:checked');
// this code here reloads the whole page / view (as in "index.php")
$.ajax({
url: 'open_second.php',
type: "POST",
data: ({checked: checkedItems, copyTo: productCodeCopy, code: "<?php echo $_POST['code']; ?>"}),
success: function(data){
$("#copyToProducts").append(data);
},
error: _alertError
});
/*
// the code below runs just fine when I hit the button "confirmCodeCopy"
alert('Fuu');
return false;
*/
});
function _alertError() {
alert('error');
}
});
</script>
<!--BODY-->
<!-- these are dynamically generated from php, just to simplify we have checkbox that contains value "1" to be posted in ajax -->
<div class="foundImage" id="foundImage" data-image-id="1"><img src="image.jpg"><input type="checkbox" id="selectedImages-1" name="selectedImages[]" value="1" style="display: none;"></div>
<label for="productCodeCopy">Products code</label>
<input type="text" class="textfields" id="productCodeCopy" name="productCodeCopy">
<br /><br />
<label for="confirmCodeCopy"> </label>
<input type="button" class="admin-buttons green" name="confirmCodeCopy" id="confirmCodeCopy" value="Search">
<div id="copyToProducts"></div>
open_second.php only prints out POST variables for now, so nothing special yet.
SOLVED
So ok, I solved it. With dumdum's help.
I removed the line:
$('input:checkbox[name="selectedImages[]"]:checked');
And added this:
var checkedItems = new Array();
var productToCopy = $('#productCodeCopy').val();
$("input:checkbox[name=selectedImages[]]:checked").each(function() {
checkedItems.push($(this).val());
});
Since there was no form element present, it didn't get the field values unless "manually retrieved" via .val() -function.. Stupid me..
I don't know how much this affected but I changed also:
data: ({checked: checkedItems, copyTo: productCodeCopy"})
To
data: {"checked": checkedItems, "copyTo": productToCopy}
So now it's working just fine :) Cool!

WHen you apply event hander to a button or a link to do ajax...always prevent the browser default processing of the click on that element
There are 2 ways. Using either preventDefault() or returning false from handler
$("#confirmCodeCopy").on('click', function(event){
/* method one*/
event.preventDefault();
/* handler code here*/
/* method 2*/
return false;
})
The same is true for adding a submit handler to a form to do ajax with form data rather than having the form redirect to it's action url

your code $('input:checkbox[name="selectedImages[]"]:checked'); is returning undefined making the json data in the ajax call invalid. Check you selector there.

Related

using ajax for change website language

I Have very simple PHP html code for change my website language and I need to use Ajax to not-reload after select language but honestly I never used ajax before and I don't have any idea how to use that.
I google it and found some code but I fail.
HTML:
<form action="" method="get">
<input type="submit" value="per" id="per" name="per">
<input type="submit" value="eng" id="eng" name="eng">
</form>
PHP :
function lang()
{
$lang = 'per';
if (isset($_GET['per']))
return $lang = 'per';
else
return $lang = 'eng';
}
Ajax:
$.ajax({
type: "GET",
url: 'index.blade.php',
data: {name: 'per'},
success: function(data){
alert(data);
window.location.reload();
}
});
All Code's are at one page named
index.blade.php
php code working fine just need for ajax to not-reload page when I click buttons
Try this:
html:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<form action="" >
<button type="submit" id="button1">Click
</button>
</form>
<script type="text/javascript" src="1.js"></script>
<!--<script type="text/javascript" src="2.js"></script>-->
</html>
js:
document.getElementById("button1").addEventListener("click",function(e){
//alert("hello");
e.preventDefault(); //a button's default behavior is to submit the form which this function prevents
$.ajax({
url:"example.php",
success:function(result){
alert(result);
location.href=location.href; //here you can specify where you want to get your ajax call to redirect to.
}
})
return false;
})
php file:
<?php
echo "Hello world";
?>
Hope this is what you are looking for!
I suggest studying a few tutorials on Ajax, I will try to briefly touch the subject here.
First of all, when doing Ajax, you basically call a web page or script (an actual url, not a function written in PHP). The result that you get (HTML, XML, CSS, JSON, JPG), you can use in your code, insert ii in the DOM, change the document, etc.
In my opinion, changing the language is a site-wide action that should probably be implemented as a normal call. Genearaly, if you change the language, then the whole page should be translated, from the top (title) to the last bit of text down before the closing body.
If you just need to change a small portion of the web page, please see the URL
jQuery get
The page uses an example
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
that performs what you want, just change the url. Hope I helped a bit.

$_GET PHP form variable AJAX check 404 then submit form

I have a form on a page that accepts an 'ID', user inputs ID eg; 1026
The form submits to the same page ajax grabs the ID checks it against another site. I need to be able to let the form post if the response is NOT a 404 error and $_GET is true.
Heres what I have
<script>
$(document).ready(function(){
$('form#getid').submit(function(){
var theid = $('input#id').val();
var dataString = "id=" + theid;
$.ajax({
type: "POST",
data: dataString,
success: function(response, status, xhr){
if(status=="success") {
$("#err-404").html(response);
}
else { alert(status+ ' - '+ xhr.status); }
}
}
});
});
return false;
});
</script>
My form
<form id="getid" action="">
<input type="text" name="id" />
<input type="submit" class="button" value="Go">
<div class="error" id="err-404"></div>
I think im on the right track, just not sure how to put it all together.
Firstly, if you don't have to use a string for your data, don't. You can use an array like so:
$.ajax({
type: "POST",
data: {'id': theid },
Which is cleaner and more maintainable.
As for your question, your code is a little unclear, but what you probably should do is return false at the end of the submit() event to prevent the form from submitting, and then in the AJAX event, if it's cleared for submission, do a $('#getid').submit(). You may have to set some kind of flag (a hidden input or a data attribute) that you check on to avoid the AJAX-triggered submit from checking again, resulting in an infinite loop.
A note here: 404s should cause the error() callback in the AJAX handler to fire, so a 404 won't trigger the success callback you have set up.

jQuery json loop with ajax call for php function

I'm new to Javascript. The code for a jQuery-ajax-php-cooperation does strange things. It works - sometimes.
This is what I want to do:
make some settings in a form (works)
read JSON-file after pressing submit-button (works)
loop the JSON-items, extract the values of each item and form a parameter-string (problem is here: loop is not (always) executed in the button-pressed-function)
send parameter-string built from each items values to PHP-file (works if loop is entered)
receive the response from the PHP-file (html-tag) (works)
update a form element with the response value (not yet implemented, actually show an alert with the PHP-response for debugging purposes)
The JSON file is valid (tested).
The HTML-Page is valid HTML5 (tested).
The PHP-script works and returns a valid HTML-Image-Tag (tested).
When I press the button, no responses from the PHP-file are displayed in the alert I implemented for debugging purposes. But this works:
reload page
open Firebug
set breakpoint at loop-begin
skip one statement forward
reload page
the loop is entered, all works fine
I can close Firebug and the loop is performed properly.
The javascript code
<script type="text/javascript">
$(document).ready(function () {
//click event of submit button
$('#generator').click(function(){
// GET variables
var datafile = "my.json";
var logo = false;
// if checkbox is checked
if( $('#logo').attr('checked')){
logo = true;
};
// read data from json file
$.getJSON(datafile,function(data){
//iterate through the data-sets
for(var i=0; i < data.length; i++) {
// get the response from server for each data-set
$.ajax({
type: 'POST',
async: false,
cache:false,
url: 'myfile.php',
data: 'param1='+data[i].field1+'&param2='+data[i].field2+'&logo='+logo,
success: function(response){
//$('#imgdisplay').html(response);
// alert only for debugging purposes
alert(response);}
}); // end of ajax-call
}; // end of for-loop
} ); // end of getJSON
}); // end of button.click
}); // end of document.ready
</script>
(sorry for bad intented formatting)
I use a for-loop, could not get an each()-loop to work properly.
And this is the form:
<form name="settings">
<label>Source file</label>
<select id="datasource" name="datasource">
<option value="extract">Extract</option>
<option value="filter">Filter</option>
</select><br />
<label>Logo</label>
<input type="checkbox" id="logo" name="logo" value="ON"/><br />
<p> </p>
<input type="submit" value="Start Generator" id="generator" name="generator" />
</form>
<div id="imgdisplay" class="imgdisplay"></div>
What causes this strange behavior? How can I solve it?
Try to return false from the anonymous click method
$('#generator').click(function(){
....
return false;
}
This will ensure that the click will not post your form

Cascading select

Sorry in advance everyone for this question as I know the cascading select boxes has been done to death but I can't seem to find any good help. I've tried various things but it all seems to fail and I'm not understanding why.
Here's the jquery I have currently:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
var vid = $("select#cat option:selected").attr('value');
var request = $.ajax({
url: "show_type.php",
type: "POST",
data: {id : vid}
});
request.done(function(msg) {
$("#result").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
}
Don't mind the first section of the code with the select#type and select#cat as these are for what I was trying to get the code to populate at first, however the .change is my trigger for the .ajax request. The rest of the code I'm merely trying to dump a simple return message into an empty div#result upon a successful ajax request.
I ran a test, and the var vid populates correctly.
Here's the simple PHP file I'm trying to call with the ajax:
<?php
$requ;
if (isset($_POST['id'])) {
$requ = 'Worked';
} else {
$requ = "didn't work";
}
echo $requ;
?>
I thought perhaps the problem was the id wasn't being passed properly so I altered the PHP script to give me any valid output regardless of whether the $_POST was set or not.
I won't post the HTML as I'm just trying to dump this all into a div while I test it. When I run the script I get the 'Request Failed' error message with a message of "error".
Here is the other jquery & PHP I have also tried, using the .post instead of the .ajax:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
$("select#type").html("<option>wait...</option>");
var vid = $("select#cat option:selected").attr('value');
$.post("show_type.php", {id:vid}, function(data){
$("#result").empty().append(data);
}, "json");
});
}
And the PHP to accompany this particular jquery:
$requ = $_POST['id'];
$ret = 'You selected: ' . $requ;
echo json_encode($ret);
Again, it all failed. I also tried the above code without using the json encoding/parameters. All I want to do is a simple (so I would think) cascading select dropboxes. The second box to be dependent of the first boxes selection. I'm beginning to think that this all just may not be worth it and just sticking strictly to PHP with links to resubmit the page with a GET and populate a new section or div with the results of the first click. Any help or suggestions you might have would be greatly appreciated, I've spent 2 solid days trying to figure this all out. Thanks in advance
Alright, I got it fixed. Thanks to Mian_Khurram_ljaz for making me take a different look at the hierarchical structure of the file. I was assuming that since the js was calling the php file, by placing the php file in the same folder as the js, I could call the php by using the url: show_type.php but that was actually wrong. The structure is considered from the actual page invoking the js and php, and therefore the url should have been js/show_type.php since I had the show_type.php file in my js folder.
It's always the little mistakes that take you days to figure. For those in the future looking to find decent code for cascading select drop boxes, here is my functioning and fully expanded code (which also includes a tri-level cascade)
jQuery:
function project() {
$("select#model2").attr('disabled', 'disabled');
$("select#brand2").attr('disabled', 'disabled');
$("select#project").change(function(){
$("select#model2").attr('disabled', 'disabled'); // if changed after last element has been selected, will reset last boxes choice to default
$("select#model2").html('<option selected="selected">Choose...</option>');
$("select#brand2").html("<option>Please wait...</option>");
var pid = $("select#project option:selected").attr('value');
$.post("handler/project.php", {id:pid}, function(data){
$("select#brand2").removeAttr("disabled");
$("select#brand2").html(data);
});
});
$("select#brand2").change(function(){
$("select#model2").html("<option>Please wait...</option>");
var bid = $("select#brand2 option:selected").attr('value');
var pid = $("select#project option:selected").attr('value');
$.post("handler/projBrand.php", {proj: pid, bran: bid}, function(data){
$("select#model2").removeAttr("disabled");
$("select#model2").html(data);
});
});
}
Just call the function in the $(document).ready of your js.
Notice the comment, having this 'redundant' call to disable and force the last box to select the default is just in case the user makes a selection in all 3 boxes but goes back to the first box and changes the selection.
Here is the php handler file:
<?php
include_once('../includes/file.inc');
$request = $opt -> getModelvBrand();
echo $request;
?>
The other handler file for the jQuery is nearly exactly the same, only invoking a different method in the class file.
And lastly, the HTML:
<form action="" method="post">
<select id="project">
<option value="0">Choose...</option>
<?php echo $opt -> getProject();?> //populates first box on page load
</select>
<select id="brand2">
<option value="0">Choose...</option>
</select>
<select id="model2">
<option value="0">Choose...</option>
</select>
<br /><br />
<input class="like-button" type="submit" title="Submit" value="" />
</form>
Thanks again Mian for making me take a different look at my file(s).
Hope this code helps someone else in the near future.

jQuery, Ajax & PHP submit multiple forms dilemma

This is a very simple form that I have found on the web (as I am a jQuery beginner).
<!-- this is my jquery -->
<script>
$(document).ready(function(){
$("form#submit_wall").submit(function() {
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
</script>
<!-- this is my HTML+PHP -->
some PHP ...
while($row_pilt = mysql_fetch_assoc($select_pilt)){
print
<form id="submit_wall">
<label for="message_wall">Share your message on the Wall</label>
<input type="text" id="message_wall" />
<input type="hidden" id="id" value="'.(int)$row_pilt['id'].'">
<button type="submit">Post to wall</button>
</form>
and down below is my PHP script that
writes to mySQL.
It is a pretty straight forward script. However, it is getting little complicated when I submit it. Since I have more than one form on my page (per WHILE PHP LOOP), thus when I submit - only the FIRST form gets submitted. Furthermore, any other subsequent forms that I submit - data is being copied from the first form.
Is there any jQuery functions that clear the data? - or is there a better solution.
Thanks,
Nick
It's because you're giving each form the same id, and thus it is submitting the first element it finds with that id, i.e. the first form. What you should do is assign a unique id to each form, and then give each form an AJAX submit function that submits the form-specific data. You can use jQuery's $.each() function to loop through all the forms and $(this).attr('id') within the submit function to retrieve the form-specific id.
UPDATE: As revealed by the comment on this answer, you actually don't need the each() function because jQuery applies it to every form element anyway.
Here would be an example script:
$(document).ready(function(){
$("form").submit(function() {
var message_wall = $(this).children('input[type="text"]').attr('value');
var id = $(this).children('input[type="hidden"]').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
Because we can't see all of your forms, I'm not entirely sure, but given your question I'm going to assume that the other forms all share the same id (form#submit_wall), which is invalid an id must be unique within the document.
Given that you're going to change the id of the other forms (I'd suggest using a class name of, probably, 'submit_wall', but the specifics are up to you), the jQuery needs to be changed, too. From:
$("form#submit_wall").submit(function() {
To:
$("form.submit_wall").submit(function() { // using the class-name instead of the id.
Now, of course, you run into the same problems of duplicate ids.
So I'd suggest, again, changing the id to a class and changing:
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
to:
var message_wall = $(this).find('.#message_wall').attr('value');
var id = $(this).find('.id').attr('value');
Given the mess that you've posted, above, I find it hard to believe that this is all you need. It would definitely be worth posting the full page (or a demo at JS Fiddle or JS Bin) that fully reproduces your code.

Categories