Jquery form data not sending through ajax POST method - javascript

I have a form which sends data to php via ajax , very simple. But when I submit the form the data is not being sent across.
Javascript:
$(document).ready(function(e) {
$('#update').submit(function(event) {
event.preventDefault();
var fd = new FormData($('#update')[0]);
alert(fd);
$.ajax({
url:'func/update.php?id=<?php echo md5($result['id']);?>',
processData: false,
contentType: false,
data: fd,
type:'POST',
dataType:"JSON",
success:function(json){
}
});
});
});
PHP:
if(empty($_POST)){
echo 'No post data';
}else{
echo 'data sent';
}
print_r($_POST);
The php is left very basic to see what is going on. I would normally attach my data fom the individual field.
data:{a:a,b:b,c:c}... and so on.
HTML:
<form id="updateStaff">
Profile Picture<br /><img id="pp_img_display" src="../images/<?php echo $result['pp'];?>" width="100px" /><br /><small>Upload a new image</small><br/><input onchange="uploadImage()" type="file" id="file" /><input type="hidden" id="pp_img" value="<?php echo $result['pp']; ?>" /><br/><small>upload .jpg .png .jpeg only</small><br /><div class="form_err" id="image_err"></div>
Name: <select id="prefix" required="required">
<option><?php echo $result['prefix']; ?></option>
<?php $pre = array('Mr','Mrs','Miss','Ms');
for($x = 0; $x < count($pre); $x++){
if($pre[$x] != $result['prefix']){
echo '<option>'.$pre[$x].'</option>';
}
}?>
</select>
<input type="text" id="f_name" placeholder="First Name" value="<?php echo $result['f_name'];?>" required="required" />
<input type="text" id="l_name" placeholder="Last Name" value="<?php echo $result['l_name'];?>" required="required" /><br/>
Job Title: <input type="text" id="job" required="required" placeholder="Job Tilte" value="<?php echo $result['job_title']; ?>" />
<br/>
Years of Experience: <input type="number" id="xp" required="required" placeholder="1" value="<?php echo (int)$result['xp'];?>" />
<p><input type="submit" value="Update" /> <input type="button" value="Cancel" onclick="history.go(-1);"/></p>
</form>
I would have thought that formData would be a shorter way of doing this.

To be send, element requires name attribute:
<input name="myInputSend" type="text" id="f_name" placeholder="First Name" value="<?php echo $result['f_name'];?>" required="required" />

Once you have added something like this first answer into your project to apply name prefixes to your partial views, you can post them back as is.
On a side note
If you get into variable length lists within those partial views, its no longer that easy.
You would want to send prefix to the controller to properly add new htmlNamePrefixes to the new partial view.
To make posting easy in those situations I've created this helper $.fn()
The helper function will re-base missing / added name indexes back in order for each of the partial views within a parenting form (even if the partial views , had partial views) for the post back to go through as it should. (apologize for the early stage and messed up commenting).

Related

php jquery ajax work with multiple forms and files

I'm not sure about the right title for this question.
I have two inputs with two buttons for them in index.php
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<input type="text" class="form-control" id="input1" name="input1" value="">
<button type="submit" id="button1" name="button1" class="btn">Get Data</button>
</form>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<input type="text" class="form-control" id="input2" name="input2" value="">
<button type="submit" id="button2" name="button2" class="btn">Get Data</button>
</form>
// display and insert them into database with third button
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
// the results goes inside these input
<input type="text" class="form-control" class="results-container" name="input3" value="">
<input type="text" class="form-control" class="results-container" name="input3" value="">
<input type="text" class="form-control" class="results-container" name="input3" value="">
<input type="text" class="form-control" class="results-container" name="input3" value="">
...
<button type="submit" id="button3" name="button3" class="btn">Sace The Data</button>
</form>
I want to get the input data separately and pass the values(ajax or $_POST) into two other files and do something with them in those two other files namely( doing_somthing1.php , doing_somthing2.php ) and get the results of these files and show them in index.php inside inputs(results-container).
here is a preview:
index.php / AJAX Script
<script>
$(document).ready(function() {
$('#button1').click(function() {
$input = $('#input1').val();
$.ajax({
type: 'POST',
url: '.php',
data: {
'doing_somthing1.php': $input
},
dataType: 'json',
success: function(result) {
$('.results-container').html(result[0]);
},
});
});
});
</script>
doing_somthing1.php
if (isset($_POST['button1'])) {
$input_data = $_POST['input1'];
// do other stuffs like foreach, if and etc..
// and return new data in array
$results = array();
echo json_encode($results);
}
I'm new to ajax and I don't know if I did this right, but if you understand what I mean and what I'm trying to do, please can you help me out here.
I'm not sure that I've understood everything. But you do not need to use two files to handle the form. You can do something like this:
if (isset($_POST['button1'])) {
$input_data = $_POST['input1'];
// do other stuffs like foreach, if and etc..
// and return new data in array
$results = array();
echo json_encode($results);
} else if (isset($_POST['button2'])) {
$input_data = $_POST['input2'];
// do other stuffs like foreach, if and etc..
// and return new data in array
$results = array();
echo json_encode($results);
}
How many inputs you want to submit to the form at the bottom ? You might need again a little bit of jquery 'on click' to handle the third form, because the inputs "results-container" are outside of it. By the way, you do not need the property name any more.

Hiding php code from URL

Is there I can hide the PHP information in the URL without reloading the page?
I have the current HTML code:
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="get">
<label>
<input pattern=".{3,}" required title="3 characters minimum" name="url" class="urlinput" type="text">
</label>
<input name="submit" class="urlsub" type="submit">
</form>
And when I click submit this happens
http://example.com/?url=example&submit=Submit
Is there any way I can keep it as example.com while the information still passes to php?
Full code:
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label>
<input pattern=".{3,}" required title="3 characters minimum" name="url" class="urlinput" type="text">
</label>
<input name="submit" class="urlsub" type="submit">
</form>
<?php
IF($_POST['submit']) {
include('include/functions.php');
// IP OF THE USER
$ip = $_SERVER['REMOTE_ADDR'];
// URL TO PUT IN Database
$url = $_POST['url'];
// MAKE SIMPLE URL EG: HTTPS://WWW.GOOGLE.COM -> GOOGLE.COM
$surl = surl($url);
// RUN SCRIPT
CIURLE($surl, $ip);
}
?>
Change from using GET method to using POST method
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label>
<input pattern=".{3,}" required title="3 characters minimum" name="url" class="urlinput" type="text">
</label>
<input name="submit" class="urlsub" type="submit">
</form>
<?php
if($_POST['submit']) {
echo 'Posted url: '.$_POST['url'] . '<br>';
echo 'Remote IP:'.$_SERVER['REMOTE_ADDR'] . '<br>';
}
?>
Use "POST" instead of "GET". It's explained in the link.
http://www.w3schools.com/Php/php_forms.asp

Automatically add a certain class, whenever <Form> code contains a certain value?

I want to add a special class to each form that contains the word special as part of its action URL.
But I have many forms, and I can't think of an automated way to do this.
The only way I came up with was to create the following code, but I will have to create such code for each and every form, using a different index number:
<?php
$case1 = "special";
$case2 = "none";
if($case1 == "none") {
$class1 = ""; // don't add any class
}
else {
$class1 = "effect"; // add `effect` class
}
if($case2 == "none") {
$class2 = ""; // same goes here
}
else {
$class2 = "effect"; // and here
}
?>
HTML:
<form action="/go/<?= $case1 ?>" method="POST" target="_blank">
<input type="submit" class="<?= $class1 ?> general-class" value="submit">
</form>
<form action="/go/<?= $case2 ?>" method="POST" target="_blank">
<input type="submit" class="<?= $class2 ?> general-class" value="submit">
</form>
OUTPUT:
<form action="/go/special" method="POST" target="_blank">
<input type="submit" class="effect general-class" value="submit">
</form>
<form action="/go/none" method="POST" target="_blank">
<input type="submit" class="general-class" value="submit">
</form>
Is there any automated way to do this?
Basically I have two types of forms, one should be opened using a jquery plugin (henace the special class), and the other should open in a normal way.
My way to differentiate between them is to insert the $case[i] variable into the action url, as this is something that I have to do either way.
Perhaps there's a complete different way to achieve this, I don't know.
EDIT:
Real Form is generated mostly manually, with this code:
<form action="/go/<?= $item ?>/<?php echo $case1 ; ?>" method="POST" target="_blank">
<input name="a" type="hidden" value="<?php echo $a; ?>"/>
<input name="b" type="hidden" value="<?php echo $b; ?>"/>
<input name="c" type="hidden" value="<?php echo $c; ?>"/>
<input name="d" type="hidden" value="<?php echo $d; ?>"/>
<input type="submit" class="<?= $class1 ?> general-class" value="Click Me"></form>
(all variables are being given values at the start of the PHP block you see above)
There's two ways - PHP and jQuery. Based on your code, we don't have enough info to know if we can use the PHP way or not, so here's the jQuery way:
// wait until the document is ready
jQuery(function($) {
// find all forms that have "special" in the action
$('form[action*="special"]').each(
function() {
// within the form, find the submit button, and add the "effect" class
$(this).find('input[type="submit"]').addClass('effect');
}
);
});
And, the shorter / less verbose way:
jQuery(function($) {
// find all forms that have "special" in the action, find their input, and add the class
$('form[action*="special"] input[type="submit"]').addClass('effect');
});
The PHP Way
So, to do this in PHP, I would recommend writing a simple function, then calling it.
function get_class( $slug ) {
$class_map = array(
'special' => 'effect',
'none' => '',
// .. you could add others here if appropriate
return ( isset( $class_map[ $slug ] ) ) ? $class_map[ $slug ] : '';
);
Then you could use it in your php like so:
<form action="/go/<?= $item ?>/<?php echo $case1 ; ?>" method="POST" target="_blank">
<input name="a" type="hidden" value="<?php echo $a; ?>"/>
<input name="b" type="hidden" value="<?php echo $b; ?>"/>
<input name="c" type="hidden" value="<?php echo $c; ?>"/>
<input name="d" type="hidden" value="<?php echo $d; ?>"/>
<input type="submit" class="<?= get_class( $case1 ); ?> general-class" value="Click Me"></form>
While that may not seem like a big value, if you started applying those concepts to your code, you would quickly see the value start adding up.

Multiple Forms on Same page AJAX

I'm having troubles on making this work.
I need to have multiple forms on the same page... I've tried countless things, but nothing seem to work.
What I'm trying to do here is identify every form (in some way) in order to submit that one instead of the FIRST form on the page. Code below, works but submits always the same form, the first one!
Here's my current code
JS:
$(document).ready(function(){
$('.submit').on("click", function() {
var artworkId = $("#inquirebox").data("artworkid");
$.post("send.php";, $("#artinquire"+artworkId).serialize(), function(response) {
$('#success').html(response);
});
return false;
});
});
HTML:
<div id="inquirebox" data-artworkid="<?php echo 456;?>">
<form action="" method="post" id="artinquire<?php echo 456;?>" data-artworkid="<?php echo 456;?>">
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" /><br />
<label for="message">Message:</label><br />
<textarea name="message" id="message"></textarea><br />
<input type="hidden" name="id" value="<?php echo 456;?>">
<input type="hidden" name="artist" value="<?php echo $title1; ?>">
<input type="hidden" name="url" value="<?php echo $uri1; ?>">
<input type="hidden" name="artwork" value="<?php echo $artwork1; ?>">
<input type="button" value="send" class="submit" id="submit" data-artworkid="<?php echo 456;?>">
<div id="success"></div>
</form>
</div>
You're using the same ID on all the DIV wrappers around the forms.
ID's must be unique, so you could use a class instead, but you really don't need any identifiers at all, nor do you need data attributes, the .submit button is inside the form, so all you need is this.form, or more jQuery'ish $(this).closest('form') to get the parent form
$(document).ready(function(){
$('.submit').on("click", function() {
var form = $(this).closest('form');
$.post("send.php", form.serialize(), function(response) {
form.find('.success').html(response);
});
return false;
});
});
You should however use a class on the #success element to find it based on the form.

Javascript function call on wrong pages

Heyo,
Having a few issues with JavaScript function calls. Basically I am using php to create a table, and then on page init JavaScript is called to click a button which is labelled correct answer.
Now this all works fine, however when I return to the main page and try to do the same thing again it fails due to an "Uncaught TypeError: Cannot call method 'click' of null". This is happening because for some reason the script is being incorrectly called again and is then trying to click on something which isn't there, hence the 'null' error.
If I reload the page it works fine again as the JavaScript function is then not loaded until called.
The main issue seems to be that the JavaScript is remaining loaded (probably because jquerymobile uses ajax calls to load the page, and thus the data is never properly refreshed. Other than forcing the page to load without ajax, any suggestions?
JavaScript function:
function showCorrectAnswer(correctAnswer) {
$(document).on("pageinit", function() {
document.getElementById(correctAnswer).click()
})
}
PHP function:
function populatedQuestionUI ($topicID, $questionID, $actionSought) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM questions WHERE Topic = ? and QNo = ?");
$query->bindValue(1, $topicID);
$query->bindValue(2, $questionID);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
?>
<form name="questionUI" action="/MCExamSystemV2/Admin/manageQuestion.php" method="post">
<input type="hidden" name="TopicID" value="<?php echo $_POST['topic']; ?>"/>
<input type="hidden" name="QuestionNo" value="<?php echo $_POST['question']; ?>"/>
<label for="QText">Question Text</label>
<input type="text" name="QText" value="<?php echo $results[0]['QText']; ?>"/>
<label for="AnswerText-1">First Answer</label>
<input type="Text" name="AnswerText-1" value="<?php echo $results[0]['AText1']; ?>"/>
<label for="AnswerText-2">Second Answer</label>
<input type="Text" name="AnswerText-2" value="<?php echo $results[0]['AText2']; ?>"/>
<label for="AnswerText-3">Third Answer</label>
<input type="Text" name="AnswerText-3" value="<?php echo $results[0]['AText3']; ?>"/>
<label for="AnswerText-4">Fourth Answer</label>
<input type="Text" name="AnswerText-4" value="<?php echo $results[0]['AText4']; ?>"/>
<label for="CorrectAnswer">Correct answer:</label>
<div data-role="controlgroup" data-type="horizontal">
<input type="button" name="Answer-1" id="Answer-1" value=1 onClick="document.getElementById('CorrectAnswer').value='1'"/>
<input type="button" name="Answer-2" id="Answer-2" value=2 onClick="document.getElementById('CorrectAnswer').value='2'"/>
<input type="button" name="Answer-3" id="Answer-3" value=3 onClick="document.getElementById('CorrectAnswer').value='3'"/>
<input type="button" name="Answer-4" id="Answer-4" value=4 onClick="document.getElementById('CorrectAnswer').value='4'"/>
</div>
<input type="hidden" name="CorrectAnswer" id="CorrectAnswer" value='0'/>
<input type="submit" value="Confirm <?php echo $actionSought; ?>">
<input type="button" value="Cancel" onClick="location.href='/MCExamSystemV2/Admin'"/>
</form>
<script src="/MCExamSystemV2/includes/scripts.js"></script>>
<script>showCorrectAnswer('Answer-<?php echo $results[0]['CorrectA']; ?>')</script>
<?php
}
The main problem is because you're doing this:
document.getElementById(correctAnswer).click();
You're not checking if the element is on the page. Change it to:
var el = document.getElementById(correctAnswer);
if (el) {
el.click();
}

Categories

Resources