$.ajax won't access url - javascript

I'm trying to send some data via jquery and $.ajax to a php file. When the page loads, a list of names is retrieved from "bewohner_func.php". This works.
At the end of the list is a form, which is used to add a new Name onto the list. It uses $.ajax to send the data, also to "bewohner_func.php", using a switch to differntiate from displaying or adding the data-. Problem is, when I try to send the form, the script does not include the php file. I can safely say that it's not the php file's fault, as I reduced it to an alert.
$(document).ready(function()
{
$("#bew_new").submit(function()
{
var frmData = $("#bew_new").serialize();
$.ajax({
url: "bewohner_func.php",
data: frmData,
success: function(msg)
{
$('#bewohnerliste').fadeOut(400);
$.get("bewohner_func.php", {'bew_new': '0'}, function(data){
$("#bewohnerliste").html(data);
});
$('#bewohnerliste').fadeIn(400);
}
});
return false;
});
});
This is the code for displaying, which does it's job fine:
$(document).ready(function()
{
$.get("bewohner_func.php", {'bew_new': '0'}, function(data){
$("#bewohnerliste").html(data);
});
});
The form:
<form id="bew_new" class="bew_form" action="bewohner_func.php" method="get">
<input name="anrede" size="6" value="Anrede" onFocus="if(this.value=='Anrede')this.value=''">
<input name="name" value="Name" onFocus="if(this.value=='Name')this.value=''">
<input name="wohnbereich" size="2" value="WB" onFocus="if(this.value=='WB')this.value=''">
<input type="submit" value="Neu anlegen">
</form>

It sounds like you are running your submit handler code on page load before form is loaded. If so, submit handler won't be bound to form if it doesn't exist.
You can delegate the handler to an eleemnt, or the document itself, that will be permanent asset in page
TRY:
$("#bewohnerliste").on('submit',"#bew_new",function(){
var frmData = $(this).serialize();
$.ajax......
})

Related

ajax [file 1] -> php [file 2] -> $_POST [file 1]

I am building a budget application with HTML, Javascript, and PHP. My goal is to have the user be able to add data into a database from a form provided. I already have a ton of php at the top of my 'dashboard.php' (which contains the form) so I didn't want to run dashboard.php on submit, so instead I created a button that preforms an AJAX call to a different php file 'addIncome.php'.
I have two different files...
dashboard.php &
addincome.php
dashboard.php contains my form, as well as my javascript to run an AJAX call.
addincome.php is using $_POST to grab the values from the form in dashboard.php and make a mysqli_query. However, at first nothing was happening so I decided to echo the value of one of the return values from my $_POST. And ended up getting this error...
undefined index iName in addIncome.php
undefined index iAmount in addIncome.php
So from there I though that maybe I didn't have access to the dashboard.php by default so I included...
include('dashboard.php');
Still no difference...
I'm really at a stand still here. Any thoughts?
Thanks
The form...
<form>
<input type="text" name="iName" placeholder="income name">
<input type="number" step="0.01" min="0" name="iAmount" placeholder="amount">
<input type="date" name="iDate">
</form>
The javascript...
<script>
$('.in-btn').click(function() {
$.ajax({
url: "addIncome.php",
type: "POST",
data: 'show=content',
success: function(data) {
$('.in-btn').html(data);
}
});
setTimeout(() => {
// location.reload();
}, 2000);
});
</script>
The php...
<?php
echo "adding...";
require_once('connection.php');
include('dashboard.php');
$iUser = $_SESSION["username"];
$iName = $_POST["iName"];
$iAmount = $_POST["iAmount"];
echo $iName;
$sql = "INSERT INTO income (user, name, amount, date) VALUE ('pmanke', '$iName', '$iAmount','1/16/19')";
mysqli_query($dbCon, $sql);
?>
You are not sending any post data with your AJAX call except for:
show=content. You want to send your form data. You can retrieve your form data with:
$("#id-of-form").serialize()
That way your PHP code is able to retrieve the correct values from your POST data.
An even more general way to do this is to just create a normal form with a submit button and an action and use javascript to catch the submit event and make an AJAX call instead:
HTML:
<form id="idForm" action="addIncome.php">
<input type="text" name="iName" placeholder="income name">
<input type="number" step="0.01" min="0" name="iAmount" placeholder="amount">
<input type="date" name="iDate">
<input type="submit" />
</form>
Javascript:
$("#idForm").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});

Get input field value in same page without refreshing page php

I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}

[jQuery]Page refreshes after appending html with .html()

So I'm trying to get some data from the server with php but as soon as it's loaded onto the page it seems to reload the page and make it disappear again.
My html:
<form id="searchForm">
<input name="searchValue" type="text" id="search">
<input type="submit" name="Submit" value="Zoek op klant" onclick="getKlanten()">
</form>
<div id="klanten">
</div>
My js:
function getKlanten(){
var value = $("#search").val();
$.ajax({
url:'includes/getKlanten.php',
async: false,
type: 'POST',
data: {'searchValue':value},
success: function(data, textStatus, jqXHR)
{
$('#klanten').html(data);
},
error: function () {
$('#klanten').html('Bummer: there was an error!');
}
});
}
Can anyone help? It gets put into the div but then instantly disappears again.
Firstly, avoid inline click handlers. The page reloads because by default a form submits the form content to the url specified in action attribute.
Instead attach an event to the form and use preventDefault to avoid the page from refreshing. Do something like this
$('#searchForm').on('submit', function(e){
e.preventDefault();
// your ajax request.
});
Or attach an event to input button like this
$('input[type="submit"]').on('click', function(e){
e.preventDefault();
// your ajax request
});
Read more about preventDefault here

Javascript/JQuery: On form submit, don't reload full page (only a div), and still submit form data

I've got the following code that I use on my links. This prevents the page from reloading and loads the content from the href tag in a div.
$("a[rel='right']").click(function(e){
e.preventDefault();
pageurl = $(this).attr('href');
$.ajax({url:pageurl.replace('index.php', 'rightcolumn.php')+'&rel=right',success: function(data){
$('#WMS_NEW_right').fadeOut(500, function(){ $('#WMS_NEW_right').html(data).fadeIn(1000); });
}
});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
My Question:
I need the use the same concept behind this, except on form submit, it needs to not reload the page, but submit the form only inside a div #WMS_NEW_right. How can I do this? I don't need push state or anything, just need to be able to control that form with class="formrelright" to only reload a div and get the url from the form action. I will also need all data from the form method="POST" on the new page (inside div)
From my understanding, you want to use ajax to post a form without reloading the page during the form submission. So I would consider the following:
$('.formrelright').submit(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: 'POST',
data: $(this).serialize(),
success: function(data) {
// Whatever you want
}
});
});
Either use target and an IFrame, or JQuery to submit the form in the background. The latter is preferable if you want to use the contents of the response.
JQuery post()
Maybe try it like this:
HTML:
<!-- Notice there is no 'form' element -->
<div id="myform">
<input type="text" name="firstName"><br>
<input type="text" name="lastName"><br>
<button type="button" id="submit_myform">Submit</button>
</div>
<div id="resultArea"></div>
<!-- the biggest critique about this method might be that
yes, it is not very semantic. If you want to use a form,
just throw in an 'e.preventDefault()' in your jQuery -->
jQuery:
$('#submit_myform').on('click',function() {
var firstName = $('input[name="firstName"]').val(),
lastName = $('input[name="lastName"]').val();
$.ajax({
type: "POST",
url: 'form.php',
data: {
firstname: firstName,
lastname: lastName
},
//the success function is automatically passed the XHR response
success: function(data) {
$('#resultArea').html(data);
},
});
});

How to put a jQuery code into one file which will be referenced by all pages?

I have a login popup that will pop up on every page of my site. What I want to do is once the user clicks submit, to have a single JS file where the jQuery code for handling that request lives, and makes an AJAX call to validate the parameters in the DB.
I am able to get the pop up box to pop up. And the form loads. I am thinking my jQuery code will live in a separate imported file and look like this:
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var some_params= $("#param").val();
var dataString = 'Some url to send to ajax';
if( params validated ok )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
So my question is how do I make this get invoked only when the right form is submitted? The form would have some id="some_name" but I don't really understand how to make this jQuery code get executed only when that form element is called.
And here is the form I am calling to display in the popup:
<?php
echo '<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
</p>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
<p>
Create Account | Reset Pass
</p>
';
?>
and here is the problemio.js contents with the jQuery to handle the login form submit:
// javascript library
// login_form
$(function()
{
$("#login_form input[type=submit]").click(function()
{
console.log("test");
alert("1");
// var name = $("#problem_name").val();
// var problem_blurb = $("#problem_blurb").val();
// var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
// if(name=='' || problem_blurb == '')
// {
// $('.success').fadeOut(200).hide();
// $('.error').fadeOut(200).show();
/// }
// else
// {
// $.ajax({
// type: "POST",
// url: "/problems/add_problem.php",
// dataType: "json",
// data: dataString,
// success: function(json)
// {
// $('.success').fadeIn(200).show();
// $('.error').fadeOut(200).hide();
//
/// // Here can update the right side of the screen with the newly entered information
// //alert (json);
//
// new_string = "<h2>Most Recently Added Problems</h2>";
// Have to figure out how to make this work with the DOM.
// }
// });
// }
return false;
});
});
Two things. First, when you place the code above into a separate javascript file, be sure to remove the <script ..> and </script> HTML tags.
Next, alter the following line:
$("input[type=submit]").click(function()
To instead say:
$("#loginform input[type=submit]").click(function()
And then set id="loginform" on your <form> tag.
You can use .submit() to attach a handler to the form submit event. First you'll need to select your form via the id:
$("#some_form_id").submit(function() {
// the code you have in the click event above goes here.
});
You can specific the form you want to trigger the jquery. http://api.jquery.com/submit/
If you are not sure, just right-click this webpage and read its html code.
<script type="text/javascript" src="some.js"></script>
And also, binding the the function to form.submit is much better than to the submit button.
$('formid').submit(function(){blablabla;return false;})
If you would like to handle the click event for every submit on the page without using ids, you can always use the this keyword in the click event to find the sender and then find the parent form.

Categories

Resources