Reference to dynamically loaded element - javascript

There are folowing code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="Block"></div>
<script type="text/javascript">
function Request(Mode)
{
jQuery.ajax
({
url: "Script.php",
type: "POST",
dataType: "html",
data: "Mode=" + Mode,
success: function(responce)
{
if (responce == '1')
{
document.getElementById("MessageField").innerHTML = "Message text";
}
else
{
document.getElementById("Block").innerHTML = responce;
}
},
error: document.getElementById("Block").innerHTML = "Request error."
});
}
Request("load form");
</script>
</body>
</html>
And php-script returning html-form or value '1':
<?php
if ($_POST['Mode'] == 'load form')
echo
"
<form id = 'AuthForm' method = 'post' action = ''>
<table border = 1>
<tr>
<td id = 'MessageField'>
&nbsp
</td>
</tr>
<tr>
<td>
<input type = 'submit' name='B1' id='B1' value='Show message' onclick = 'Request()'>
</td>
</tr>
</table>
</form>
";
else echo "1";
?>
Javascript function outputs html-form or changes innerHTML of it's table cell with id="MessageField".
The form appears as supposed, but pressing button I get error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
Script can not execute string:
document.getElementById("MessageField").innerHTML = "Message text";
Why? MessageField already exists when script tries to change it. o_O

There is no element in your given snippet that has the id "Block"

Related

Loading data from a server using jquery $.post

What im about to do is to send data to the server through a form and to a php-script. Then I want to get it back and place it in the right spot using Jquery. I don't know why, but this solution doesnt seem to work as im just getting the "No text in the textbox!". Does someone have any tips?
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#send").click(function(event) {
$.post("target.php", {
melding: $("#input").val().
}, function(data){
$("#meldinger").after("<div>" + data + "</div>");
});
event.preventDefault();
});
});
document.getElementById('demo').innerHTML = date();
</script>
<title>Meldingssystem</title>
</head>
<body>
<h1>Meldingsutveksling</h1>
<form action="target.php" method="post">
<textarea id="input" name="input" cols="40" rows="2"></textarea>
<br/><input type="submit" name="submit" value="Send">
</form>
<h2>Meldinger</h2>
<div id="meldinger">
</div>
</body>
</html>
PHP
<?php
if (!empty($_POST['input'])) {
$melding = $_POST['input'];
echo $melding;
}
else {
echo "No text in the textbox!";
}
?>
This
if (!empty($_POST['input'])) {
$melding = $_POST['input'];
echo $melding;
}
else {
echo "No text in the textbox!";
}
Should be
if (!empty($_POST['melding'])) {
$melding = $_POST['melding'];
echo $melding;
}
else {
echo "No text in the textbox!";
}
because there is no input POST parameter sent
first, please read https://api.jquery.com/jquery.post/
your php script expects data in the input field. but your jquery POST doesn't put anything in an input field.
instead try something like:
$.ajax({
data: {
input: $("#input").val()
},
datatype: "text",
method: "POST",
success: function(data, status, xhr) {
$("#meldinger").after("<div>" + data + "</div>");
},
error: function(xhr, status, error) {
alert("zog zog");
}
};
Notice that input is present in the data parameter.

How to pass on a form through Ajax, and PHP

I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.
here is my form
<form >
<input type="text" id="name" >
<input type="submit" value="s" onclick="return chl()" >
</form>
here is my js
<script>
function chl(){
var name= document.getElementByID('name').value;
var dataString='name' + name;
$.ajax({
type:"post",
url:"hi.php",
data:dataString,
cache:false,
success: function(html){
alert ("success");
}
});
return false;
}
</script>
and here is my php
<?php
$name=$_POST ['name'];
echo "response".$name;
?>
The datastring should be formed like a querystring; you've missed the = between the key and the value:
var dataString = 'name=' + name;
That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:
<form method="hi.php">
<input type="text" id="name" />
<input type="submit" value="s" />
</form>
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
cache: false,
success: function(html){
alert(html); // = 'response: name = [VALUE]'
}
});
});
$name = $_POST['name'];
echo "response: name = ".$name;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!--form method="hi.php"--> <!-- Remove this from your code and method is post or get you can't use hi.php as method -->
<input type="text" id="name" />
<input type="submit" id="click" value="s" /> <!-- Give id to your button -->
<!--/form-->
<script type="text/javascript" src="js/jquery.js"></script> <!-- You need to use jquery -->
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#click').on('click', function(event) {
event.preventDefault();
/* Act on the event */
var name=$('#name').val();
$.ajax({
url: 'hi.php',
type: 'POST',
data: {name: name}
})
.done(function(data) {
alert(data); // You can alert that data
console.log(data); //or you view this data on console Ctrl+shift+I
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
</script>
</body>
</html>
<!-- Your php page hi.php -->
<?php
echo $_POST['nmae'];
// or just say hi
echo 'hi';
?>
Form
<form name="test" id="test">
<input type="text" id="name" >
<input type="submit" value="s" >
</form>
Script
<script>
$("#test").submit(function(e){
e.preventDefault();
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{"name":name},
cache:false,
success: function(html){
alert (html);
}
});
return false;
}
</script>
You can also try with -
var dataString = $('form').serialize();
By this you can get rid of generating the datastring if you have a number of input fields.
change ajax function like and send data as shown below and your php and js function must be in different pages
function chl(){
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{name:name},
success: function(html){
alert ("success");
}
});
return false;
}
<form method="POST" action="server.php">
<input type="text" name="name" id="myName" >
<input type="submit" value="s" onclick="chl(); return false;" >
</form>
<script>
function chl()
{
var nameElement = document.getElementById("myName");
//Creates formData object and sends it to PHP script
var formData = new FormData();
//name equals to input element name attribute value
formData.append(nameElement.name, nameElement.value);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "server.php");
xmlHttp.send(formData);
}
</script>
<?php
$name = $_POST['name'];
echo $name;
?>

php ajax form submit ..nothing happens

I have a PHP Ajax form that I'm trying to submit a Zendesk API call. Whenever I use the ajax part, in order to keep the user on the same page, it doesn't work. When I remove the <script> part, it works fine, but obviously redirects to contact.php from contact.html so I'm thinking the problem is in the Ajax part, not in the PHP part.
Here is my HTML form:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="box_form">
<form id="zFormer" method="POST" action="contact.php" name="former">
<p>
Your Name:<input type="text" value="James Duh" name="z_name">
</p>
<p>
Your Email Address: <input type="text" value="duh#domain.com" name="z_requester">
</p>
<p>
Subject: <input type="text" value="My Subject Here" name="z_subject">
</p>
<p>
Description: <textarea name="z_description">My Description Here</textarea>
</p>
<p>
<input type="submit" value="submit" id="submitter" name="submit">
</p>
</form>
</div>
<div class="success-message-subscribe"></div>
<div class="error-message-subscribe"></div>
<script>
jQuery(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('.box_form form').submit(function() {
var postdata = $('.box_form form').serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>
</body>
</html>
And the PHP Part:
You can probably ignore most of this since it works when I don't use the Ajax. Only the last few lines gives the response $array['valid'] = 1; which should then be catched by if(json.valid == 1) above.
<?php
( REMOVED API CALL CODE FROM ABOVE HERE )
if (isset($_POST['submit'])) {
foreach($_POST as $key => $value){
if(preg_match('/^z_/i',$key)){
$arr[strip_tags($key)] = strip_tags($value);
}
}
$create = json_encode(array('ticket' => array(
'subject' => $arr['z_subject'],
'comment' => array( "body"=> $arr['z_description']),
'requester' => array('name' => $arr['z_name'],
'email' => $arr['z_requester'])
)));
$return = curlWrap("/tickets.json", $create, "POST");
$array = array();
$array['valid'] = 1;
$array['message'] = 'Thank you!';
echo json_encode($array);
?>
Any ideas why this isn't working?
I expect your use of contact.php as a relative URL isn't resolving properly. Check your JavaScript console and you should see an error that shows the post failing. Change contact.php to www.your_domain.com/contact.php and it should work fine
Replace jQuery(document).ready(function() { by
$(document).ready(function() {
Secondly from Jquery documentation:
Note: Only "successful controls" are serialized to the string. No
submit button value is serialized since the form was not submitted
using a button. For a form element's value to be included in the
serialized string, the element must have a name attribute. Values from
checkboxes and radio buttons (inputs of type "radio" or "checkbox")
are included only if they are checked. Data from file select elements
is not serialized.
Therefore submit button won't serialize through jQuery.serialize() function.
A solution below:
<script>
$(document).ready(function() {
$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();
$('#submitter').click(function(e) {
e.preventDefault();
$myform = $(this).parent('form');
$btnid = $(this).attr('name');
$btnval = $(this).attr('value');
var postdata = $myform.serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: { "btnid" : $btnid, "btnval": $btnval, "form-data": $form.serialize() },
dataType: 'json',
success: function(json) {
if(json.valid == 1) {
$('.box_form').hide();
$('.error-message-subscribe').hide();
$('.success-message-subscribe').hide();
$('.subscribe form').hide();
$('.success-message-subscribe').html(json.message);
$('.success-message-subscribe').fadeIn();
}
}
});
return false;
});
});
</script>

Sending php generated form data via Ajax from Dialog box

Hi Guys any help on this? I have a dialog box triggered by a button click that calls my php script to generate a form which needs to be filled and submitted. I want to do the sending and conformation via Ajax. I have been recoding and researching for a few days but nothing on StackExchange or other websites help me with it.
Here's the code:
Dialog box snippet;
$k('#CreateTable').click(function(e){
e.preventDefault();
var Call = $k('#CreateTable').attr('value');//.attr('id');
var util = $k(this).attr('id');//.attr('id');
$k('#dialog').dialog({
autoOpen: false,
title: 'Running Utility for: '+Call,
modal: true,
width: 450,
close: function(event, ui) {
$k("#dialog").dialog('destroy');//event.target
}//END CLOSE
}).dialog('open');
var utility = { 'utility' : util };
$k.ajax({
type: "post",
url: "inc/runUtilities.php",
dataType: "html",
data: utility,
success: function(data) {
$k('#DlgTxt').html(data).fadeIn('slow');
}
});
//return false;
});//END DIALOG
The PHP snippet;
$show .= "<form id='cContact' name='cContact' method='post'>";
// action='".$_SERVER['REQUEST_URI']."'
$show .= '<table align="center" width="425" border="0">
';
$query = "SHOW COLUMNS FROM `".$_SESSION['WorkTable']."`";
if($output = mysqli_query($this->MySQLCxn->MySQLCxn, $query))
{
$columns = array();
while($row = mysqli_fetch_assoc($output))
{
if($row['Field'] == 'id') {}
else
$show .= '
<tr>
<td width="175"><div align="right">'.#$row['Field'].':</div></td>
<td width="155">
<input type="text" name="'.#$row['Field'].'" placeholder="'.#$row['Field'].'" />
</td>
<td width="115"> </td>
</tr>
';
}
}
$show .= '
<tr>
<td>Submit </td><td>
<button type="button" id="cContactSbmt" onclick="doSubmitForm(this); return false;" name="cContactSbmt" value="cContactSbmt">Create contact</button>
<!-- <input type="submit" class="button" value="Save" name="submit"> -->
</td> <td> </td>
</tr>
</table></form>
<div id="thanks">
</div>
';
And the JQuery that i am currently using trying to have it call my php to process the form being sent.
var $j = jQuery.noConflict();
(function($j){
$j(document).ready(function() {
$j("#cContactSbmt").click(function(e){//'click',
e.preventDefault();
alert('cContactSbmt clicked...');
$j.ajax ({
type:"POST",
url:"inc/runUtilities.php",
data: $j(this).serialize(),
success: function(msg){
$j("#thanks").html(msg)
$j(this).modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
})($j);
For some reason its not working nothing showing up in the console as well.
again: i have a dialog box that gets populated via Ajax with a php generated from that needs to get submitted to another php script that is to process it and reply to the dialogs.
Any suggestions?
your php ist not outputting ("echoing") anything. you need to echo whatever you want to return to your ajax-call.
update: plus for debugging try to log the returned data in every success callback, for example:
success: function(data) {
console.log(data);
}
You may need to add an echo to the end of your php snippet..
echo $show;
This echoed html will then be available in your ajax function in the success callback function... as the variable "data"
success: function(data) {
$k('#DlgTxt').html(data).fadeIn('slow');
}
Also you may need to use jQuery .on() in your click function..to submit the form..
http://api.jquery.com/on/
$j("body").on("click", "#cContactSbmt", function(){
});
Hope this helps....
Hi Guys so I got it working with the following changes:
On the form;
<button id="cContactSbmt" onClick="doContactsCreate(\'#cContact\')" type="button" class="form-submit" name="cContactSbmt" value="cContactSbmt">Create contact</button>
I added the onclick method with a callback to a function doContactsCreate(\'#cContact\'), which has the id of the form passed to it.
function doContactsCreate(obj)
{
alert(obj+': cContactSbmt clicked...');
/* */
var frmData = $k(obj).serialize();
$k.ajax ({
type:"POST",
url:"inc/runUtilities.php",
data: frmData,
success: function(data){
$k("#thanks").html(data);
console.log(data);
$k(obj).modal('hide');
},
error: function(){
alert("failure");
}
});
}
I've just enclosed the JQuery code in this function definition and placed it outside the
(function($k){
$k(document).ready(function() {
//rest of JQuery code
})($k);
Don't know why but i think that was the main problem

unable to show success message after submitting a form using ajax

I am sending email using ajax after when ajax form is submitted.
Here is my php controller code:
If i keep the email sending code inside this function then the SUCCESS message is not showing on the html page. But if i remove the Email sending code from that function then SUCCESS message is showing.
public function sendedits()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<li class="errorlist">', '</li>')->set_rules('menu_name', 'Title', 'trim|required|min_length[2]|max_length[255]|xss_clean');
//user is logged in proceed the next work
if (!$this->form_validation->run())
{ //False
$this->_status['status'] = "error";
$this->_status['message'] = $this->load->view('commonfiles/ajax_error_display_1', '', TRUE);
}
else if ($this->form_validation->run() && $this->input->post('myId')=='')//myId=just for checking robot or human
{ //TRUE block
$fname=$this->input->post('menu_name');
$sendersemail=$this->input->post('changes_made');
$intrested_message=$this->input->post('content');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = 'asdsdsd#gmail.com';
$config['smtp_pass'] = 'sdsfsdfsdfsdfsds';
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
//$this->email->from($sendersemail, $fname);
$this->email->to('ssdd#myemil.com');
$this->email->subject('User Edited article of : '.$fname);
$message = '<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<table cellspacing="0" cellpadding="0" style="border-collapse:collapse;width:98%;background-color:whitesmoke" border="1">
<tbody>
<tr>
<td colspan=2><h2> '.$fname.'</h2></td>
</tr>
<tr>
<td width=50%>First Name </td>
<td width=50%>'.$fname.'</td>
</tr>
<tr>
<td width=50%>Email </td>
<td width=50%>'.$sendersemail.'</td>
</tr>
<tr>
<td width=50%>Message </td>
<td width=50%>'.$intrested_message.'</td>
</tr> </tbody> <table> </body></html> ';
$this->email->message($message);
$this->email->send();
$this->_status['message'] = 'Thankyou for your edits. We will review it before publishing.';
$this->_status['status'] = "success";
}
echo json_encode($this->_status);
}
Ajax function for submitting the form
<script type='text/javascript'>
$(document).ready(function() {
var _status = $('#status');
$('#sub2').click(function(e) {
_status.html('');
var postData = $('#form_id').serializeArray();
var formURL = $('#form_id').attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
dataType: "json",
success: function(dat) {
if (dat.status === 'success') {
_status.html('<span class="success">' + dat.message + '</span>');
}
else if (dat.status === 'fail') {
}
else
{
_status.html('<span class="err">' + dat.message + '</span>');
}
},
error: function(e) {
alert("Ooops! Try again later or else sends us message regarding this issue. Thankyou!");
}
});
});
});
</script>
So Im guessing this is using the phpmailer library, do you have that installed (it might come as default depending on your platform)
The first thing that I can see is that $sendersemail is not defined. Try inserting a string instead of the variable. The phpmailer library is terrible for cactching errors, I can never figure out how to tell where the errors are either!
If that doesnt work, try outputting to the console after the line you think is giving you the error. If you use:
echo("email sent");
Then you should see it in the browser console as the code is being processed. Hopefully you can see where the error is coming from then.

Categories

Resources