Event.prevent() default ajax not sending data from form to php - php

I already checked around for this answer but all are different problems just same title (to prevent random duplicate marks).
Here is an ajax call to the click of the filter button that should send the data inserted in the form formmatcat to the php file formfilt.php and should load the result in a div with id resultins
<script>
$(function () {
$('#filter').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize(),
success: function () {
$("#resultins").load('formfilt.php');
}
});
});
});
</script>
I set the preventdefault to load only in the div without redirecting to the php file and this works but if I put the preventDefault it echoes the string I build by concatenating values sent from the form with those empty values. The strange thing is that if I remove preventDefault of course it redirects and loads the php file but with the correct values:
Moral of the story, data in the form with the ajax call goes correctly to the php file but looks like preventDefault don't let this. Thanks in advance
Here's the structure of the html part with the form
<form id="formmatcat" method="post" action="formfilt.php">
.
.
various textboxes
.
.
</form>

What you're doing is sending an AJAX request toformfilt.php, when this call happens and it returns a response it will be stored as a parameter within the success or $.done function as I'll mention later, that is where your echo'd content will be.
What you're doing here is when the call is successful, you simple send a GET request to the same page. Since that GET request differs from the AJAX POST request and has no POST parameters you'll not get the correct output.
By simply submitting the form and letting it go to the page rather than cancelling the request you're getting the right values as you're directly posting to the page with the correct values, when you call the load function you're doing a seperate AJAX get request.
What load actually is, is a rough equivelant to $.get which is shorthand for $.ajax.
Looking at jQuery AJAX docs
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
Basically, a $.ajax() call returns a promise object that you can chain callbacks on when it is finished. Also note that data here will be the actual content within your PHP file, thus if you rewrite your AJAX call like so:
<script type="text/javascript">
$(function() {
$('#filter').on('click', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize()
}).done(function(data) {
$('#resultins').html(data);
});
});
});
</script>
It will then continue to load the output of formfilt.php into the div with ID resultins.

dont use form, use input without form, and use button tag use onclick to run function, if you use form, it will submit and redirect,
i'm not good with ajax on jQuery
but if i were to use javascript/XHR
var CB=document.getElementById("filter").value; //get input/filter value
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200)
document.getElementById('contain').innerHTML=xhttp.responseText;
};
var url="formfilt.php?filter="+CB;
xhttp.open("GET", url, true);
xhttp.send();
if you want to use post :
xhttp.open("POST", "formfilt.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('filter='+CB);
sorry, i'm also learning, and new to this, just learning a week ago,

Related

Form submits 1st via jQuery, 2nd via PHP

I have a form which when submitted is processed via jQuery ajax call to a PHP script.
The 1st time the form is submitted, jQuery catches the event, runs the ajax call and PHP script and returns the data from the PHP script putting it in the required HTML elements.
However, if the submit button is pressed a 2nd time, the form is submitted normally and jQuery is unable to "preventDefault" so to speak. So the whole page is reloaded.
the jQuery code
$(document).ready(function() {
// catch form submittion
$('#user_account_form').submit(function(ev) {
// prevent default action and propagation
ev.preventDefault();
ev.stopPropagation();
// pull data from the form attributes
var href = $(this).attr('action');
var postData = $(this).serializeArray();
// run the ajax call
var request = $.ajax({
url: "view/jquery/" + href,
type: "post",
data: postData,
dataType: "json"
});
// ajax call completed?
// -- echo returned data to elements
request.done(function(data) {
// put the refreshed form (provided by PHP script) in the #user_account element
$('#user_account').html(data.form);
// put the system message (provided by PHP script) in the #sysmsg element
$('#sysmsg').html(data.sysmsg).delay(2000).fadeOut(100);
});
// on fail, log to console
request.fail(function(jqXHR, textStatus, errorThrown) {
console.log('error processing form data: ' + textStatus + " [" + errorThrown + "]");
});
});
});
the PHP code
this is basically a simple script that checks the entered data from the form
against the data in the database. If the entered password equals the database
password the database is updated, otherwise it will only return a system message
to the user that the password was incorrect.
I believe the fault is that I'm missing something in my jQuery code that makes jQuery catch the 2nd, 3rd, 4th, etc. submission.
Try:
$('#user_account_form').on('submit', function(ev) {});
Instead of:
$('#user_account_form').submit(function(ev) {});
This is because as I understood, your submit button is in the data that is refresh from the back end, which means that the button is not bound to any events as it's a completely new button. jQuery on will bind the event to all instances of that element, even if they are created in the future.
Important: If you use jQuery < 1.7, instead of on() use live().
Maybe try to use a counter so you'll know how many time you've clicked on your submit btn
$(document).ready(function() {
var counter = 0;
// catch form submittion
$('#user_account_form').submit(function(ev) {
// If first click
if(counter === 0){
// Do the preventDefault and ajax thing
}
else{
// Do nothing or what you expect for a >2nd click
}
// Increment counter
counter++;
})
});
After reading your posts about the PHP script building a completely new form and therefore not binding the submit button preventing jQuery from catching subsequent submissions, I figured "Why build a whole new form if I only need to refresh 1 or 2 fields?".
So I changed my PHP script to return only the data from the database of the changed fields and send that in a json format to my jQuery script. Then adjusted my jQuery script to read the json object, and put the new values into the corresponding fields.
Now it works as intended.
changed jQuery code
....
request.done(function(data) {
$('#email').val(data.email);
$('#sysmsg').html(data.sysmsg).delay(2000).fadeOut(100);
});
changed PHP code
....
$email = $main->getUserDetails('email');
$array = array("sysmsg" => $msg, "email" => $email);
$data = json_encode($array);
echo $data;
Thanks for your input all, it helped me figuring out what to change to improve my code.

Auto reload a `DIV` after checkbox form change

I am trying to get a div to reload once a checkbox has been selected or unselected and the form has been submitted. I have used AJAX and can get the form to submit on change, which works no problem. However the page has to reload to display new data.
I have built the php in such a way that it doesn't need to refresh the page or fetch a new page. If the div and it's content refreshes that should be sufficient to display the new filtered data.
Below is what I have written so far
$(document).ready(function() {
$("input:checkbox").change( function() {
$.ajax({
type: "POST",
url: "index.php?action=resortFilter",
data: $("#locationFilter").serialize(),
success: function(data) {
$('.resorts').html(data);
}
});
})
});
What do I need to do to get the div to reload after the request has been made?
I use class methods to handle the processing which return only the array of data. The requests are made to the class from a php function.
What I'm trying to do isn't actually possible to because PHP is a server side language. The best bet is to create a new intermediate file that can handle the display of the data so that it can be brought in through a normal AJAX request and get the new display from it
Where is the Ajax request? You are submitting your form through HTML/Browser. You need to use the following code:
$(document).ready(function() {
$("input:checkbox").change( function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#locationFilter").serialize(), // serializes the form's elements.
success: function(data)
{
$('.resorts').html(data);
}
});
})
});
Source: jQuery AJAX submit form
this sample loading code maybe help you
<div id="loadhere"></div>
$('div#loadhere').load('ajaxdata.php',{datatosend:whatyouwantforexamplehelloworld});

Simple jquery ajax php request

I am doing a basic jquery ajax call on a php file and can't seemsto figure out why it isn't working. Any help is appreciated. Fiebug does not seem to show any ajax or XHR action going on. I want to not to refresh the page and just execute the ajax call. Thanks.
JS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"</script>
<script>
function getData(url_param){
$.ajax({
type: 'get',
url: 'data.php',
data: {url_param:url_param},
success: function(data) {
$('#data').html(data);
}
});
};
$('#clickMe').click(function(e){
e.preventDefault();
getData(2);
});
</script>
HTML:
<div><a id='clickMe' href='data.php?url_param=url_param'>CLICK ME TO RUN PHP</a></div>
<div id="data"></div> <!-- divto show result -->
PHP:
<?php
if($_GET['url_param']){
echo "simple ajax call";
}
?>
You have to bind the event inside an onload function. The most common practice is:
$(document).ready(function(){
$('#clickMe').click(function(e){
...
});
});
You should also add return false; in the last line of your event.
First, you have misspelled your function name (getGata != getData).
Secondly:
data: {url_param:url_param}
Are you setting the javascript variable url_param anywhere? The $.ajax data parameter is formatted as follows:
get/post variable name : get/post variable value
As you have it now, it doesn't seem that you are assigning a value to url_param.
you can simply use jQuery post function.
$.post('data.php',{param1:'your param 1', param2 : 'your param 2'}, function(response){
//do your operation here. response is what you get from data.php. 'json' spicifies that the response is json type
$("#data").html(response);
},'json');
The (amended?) JavaScript prevents your code from working, because you haven't closed the angle brackets on jQuery source, it should be:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
One of the comments states you shouldn't have the href in the anchor, but because you've ignored defaults this isn't triggered (assuming JS is enabled in the user's browser).
Finally, I think that
return false;
should really be inside the function after
getData(2);
but since we're ignoring defaults, the anchor shouldn't make an attempt to go anywhere or reload anyway.

Using ajax for form submission with multiple forms generated by php on page

I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.

Load dynamic content from php on submitting a form

I have created a page "index.php" with a lot of divs and I need to refresh only one of the divs when the form is submitted.
This div loads the content from chat_window.php which is as follows:
<div id="chatbox">
<?php echo $res; ?>
</div>
<!-- Chat user input form-->
<?php echo $formchat; ?>
chat_window.php uses dynamic content - $res and $formchat from chat.php.
Everytime I post the form the content of $res and $formchat is modified and I need to reflect the same in my page which loads chat_window.php.
I used AJAX and jQuery to do the same as follows:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("input#chat").val();
var dataString = "chat="+ name;
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
}
});
$("#chatwrapper").load(chat_window.php);
return false;
});
});
The index.php has a div to show the chat_window as follows:
<!-- Chat window-->
<div id="chatwrapper">
<?php include ("chat_window.php"); ?>
</div>
As per my analysis, when I post the form, $res and $formchat are getting updated in the php. But when I load the chat_window.php, it doesnot loads the modified values. It rather loads the initial static values.
(Please dont suggest setInterval() as I dont want to refresh the page automatically).
Javascript is non-blocking, so it means that the interpreter does not wait for jobs to complete before processing the next one.
In your code, $("#chatwrapper").load('chat_window.php'); is being called pretty much before the ajax request above it completes. You will need to use the ajax success event to call the reload.
Try:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load('chat_window.php');
}
});
Try moving the .load() statement into the ajax success handler:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load("chat_window.php");
}
});
The $.ajax() call is asynchronous, which means that execution does not pause waiting for the response, rather, it moves on directly to the .load() call. (Which is also asynchronous, so really you've no guarantee about the order the response from each call will come in unless you don't make the second call until the first one finishes.)
I got my work done. Though I used another way of doing it.
What I have understood after few days of R&D is that, when we submit the form to a php, the request is sent with input params. When your php file processes this request, it might be updating some global variables. It completes processing the request and returns the control back to the calling index.php page.
The important thing to notice is:
The variable updates made while processing the form submit request do not persist after the control is returned. The global php variables will only get updated when the page gets refreshed.
So, if there is a strict requirement to avoid page refresh, collect the processed data from the php in some output string and pass it back to index.php like this:
$responseString = $res . "|" . $formchat;
echo $responseString;
The success parameter of .ajax will receive this output and accordingly you can update your chat window or any other form.

Categories