strange javascript form behaviour - php

I am generating the following html form with this php:
echo "<form name=\"userForm\">
Username:
<input type=\"text\" name=\"username\" />
<br />
First name:
<input type=\"text\" name=\"firstname\" />
<br />
Last name:
<input type=\"text\" name=\"lastname\" />
<br />
<input name=\"Submit\" type=\"submit\" value=\"Update\" onclick=\"submitUserInfo();return false\"/>
</form>";
Which is handled by submitUserInfo, which is here:
function submitUserInfo() {
url = "edit_user.php?cmd=submitinfo&username="+document.userForm.username.value+"&firstname="+document.userForm.firstname.value+"&lastname="+document.userForm.lastname.value;
var xmlHttp=GetXmlHttpObject();
if(xmlHttp.responseText == 'true') {
alert(url);
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
//updateByUser(username);
}
}
I clearly have url defined as beginning with
edit_user.php?cmd=submitinfo&username
however when pressing the submit button, it tries to send the url as
edit_user.php?username=
and I cannot figure out why. I have used the above technique succusfully with other forms on my site, and can not find any reason that cmd=submitinfo& is being excluded.

Use a tool like Firebug to determine if the browser is sending it without cmd=submitinfo& or if it's being lost on the server side.

Change:
url = "edit_user.php?cmd=submitinfo&username="+document.userForm.username.value+"&firstname="+document.userForm.firstname.value+"&lastname="+document.userForm.lastname.value;
to:
var url = "edit_user.php?cmd=submitinfo&username="+document.userForm.username.value+"&firstname="+document.userForm.firstname.value+"&lastname="+document.userForm.lastname.value;
You must declare your url variable before you try to use it.
Also, avoid echoing straight HTML to the page. The way you've done it is going to be an absolute pain to debug, update, and stylize.

Frameworks like jQuery is not really needed for such simple tasks, although I would suggest you taking a look if you plan to implement more JavaScript on your site.
Your code, using jQuery, would look like this:
$("#<id of form goes here>").submit(function ()
{
$.ajax({
data: {
"username": $("#<id of username-input goes here>").val(),
"firstname": $("#<id of firstname-input goes here>").val(),
"lastname": $("#<id of lastname-input goes here>").val()
},
url: "edit_user.php"
});
return false;
});
Looks a bit nicer, I think :)
Also; using frameworks - not jQuery in particular - takes care of browser work-arounds.. so you won't have to.. take care of 'em, that is :)

I think you need to change the type of the button from "submit" to "button":
<input name=\"Submit\" type=\"button\" value=\"Update\" onclick=\"submitUserInfo();return false\"/>

Related

Input div id into text box and delete it from a text file when submit is pressed

I have been racking my brain trying to get a very particular function to work. It seems simple but I just cant figure it out. I am looking to basically get a txt file and allow someone to type in a certain id into an input box that upon the user clicking "delete" will remove only the targeted DIV id.
I have tried wrapping a PHP file around a form with no success, as well as putting the PHP directly into the submit button but nothing has worked, can anyone point me in the correct direction?
I have looked for other post here but nothing seems to be exactly what im looking for or I am wording it incorrectly. This is essentially how I want it to look:
<form action='delete.php' method='post'>
<input name='idinput' type='text' value='Enter The Certain ID Value You Want To Remove'>
<input type='submit' name='submit' value='Remove'>
</form>
Not sure about the text file bit but to remove an element from the DOM, well, you can't do this in PHP without reloading the page and apssing in some extra data na dusing some logic to not display that element...
You need to use JavaScript... or with JS with jQuery
$(function(){
$('input[name="submit"]').on('click', function() {
var val = $('input[name="idinput"]').val();
$('#or.IDorCLASSNAME_' + val).remove(); //If Id Input val is 3 this gives #or.IDorCLASSNAME_3
});
});
jQuery: https://api.jquery.com
jQuery Remove: https://api.jquery.com/remove/
jQuery DOM Removal: https://api.jquery.com/category/manipulation/dom-removal/
Tutorial: https://www.w3schools.com/jquery/jquery_dom_remove.asp
I was able to do this by placing a form that is inserted within the txt info im submitting:
<form action='delete.php' method='post'>
<input type='hidden' name='random' id='random' value='".$random."'>
<button type='submit' value='report'></button>
</form>
And also by adding this to the delete.php page:
<?php
$random = $_POST['random'];
$original = "<div id='".$random."'>";
$replacement = "<div id='".$random."' class='hidden'>";
$str = file_get_contents('submissions.txt');
$str = str_replace("$original", "$replacement",$str);
file_put_contents('submissions.txt', $str);
header('Location: index.php');
?>

Can we use onclientclick in PHP?

<script type="text/javascript">
function changeText2(){
var userInput = document.getElementById('userInput').value;
document.getElementById('boldStuff2').innerHTML = userInput;
return confirm('Hello!');
//return true;
}
</script>
<form method="get">
<p>Welcome to the site <b id='boldStuff2'>dude</b> </p>
<input type='text' id='userInput' value='Enter Text Here' />
<input type='button' OnClientClick="return changeText2()" value='Change Text'/>
</form>
Is this possible in PHP? I tried it but I get an error. Please suggest a solution.
Not exactly.
PHP doesn't have as complicated a template engine as ASP.NET.
You can simply use the HTML onclick attribute directly. There is no need to use a differently named one on the client because there isn't a server side attribute with the same name getting in the way.
Best practise, however, is to write unobtrusive JS and bind your event handlers programatically.

Update table record using PHP AJAX when multiple instances

On my page I have multiple forms all the same as this...
<form class='bill-upd'>
<input type='hidden' value='".$info['rand']."' name='rand2' id='rand2'>
<input type='hidden' value='".$info['id']."' name='billid' id='billid'>
Total <input type='text' id='total' name='total' /><br />
Bill name<input type='text' id='bill-name' name='bill-name' /><br />
bill descriptiion <input type='text' id='bill-description' name='bill-description' /><br />
bill colour<input type='text' id='bill-colour' name='bill-colour' />
<input type='button' value='submit' onClick='updateBill();' />
</form>
I then have my AJAX as so
function updateBill()
{
$.post('update_bill.php', $('.bill-upd').serialize(),
function(data) {
$(this).append(data);
});
};
If I have one form on my page, this works fine, but when there are multiple instances, my same record is being overwritten, can anybody tell me where im going wrong?
Thanks
With the help of #Armatus and #Bricriu I got it sorted, the answer as marked worked, stupidly forgot to wrap it within document.ready
You need a way to specify which bill you're updating, otherwise it just takes all of them. This should work, since we can determine which one it is by which button was clicked.
Edit: I personally would bind the even using jQuery rather than onClick on the element itself:
$(".bill-upd input:submit").click(function(){
var elem = $(this);
$.post('update_bill.php', elem.parent('.bill-upd').serialize(),
function(data) {
elem.append(data);
});
});
If the other forms have the same class .bill-upd the javascript .serlialize() will take values from them also. Make sure the other forms have an alternate class.
What would be better would be if you gave the form a unique id such as id="billform" and then replace $('.bill-upd').serialize() with $('#billform').serialize().
Hope this helps.
EDIT:
Use this:
$(this).parent('.bill-upd').serialize()
to serialize the parent of that which was clicked.

Get variable from Ajax to Php

I have ajax code which take textfiled variable. it alert the value, but when I want to get in php, it gives me an error of Undefined index
JavaScript Code
<SCRIPT>
function go(UserID) {
var name= encodeURI(document.getElementById('name').value);
var design= encodeURI(document.getElementById('design').value);
http.open('get', 'testAjax.php?design='+design+'&name = '+name);
http.send(null);
}
</SCRIPT>
HTML Code
<INPUT ID='name' type='text'>
<INPUT ID='design' type='hidden' value="<?php echo $UserID; ?>">
Link
Php Code
if(isset($_GET['process'])) {
echo $_GET['design'];
echo $_GET['name'];
}
please let me know how to solve it.
You have an anchor tag on which you have an onclick event. Onclick event when fired will send an ajax request to testAjax.php? url.
However since you haven't prevented default behaviour of clicking an anchor tag, as soon as this ajax request is sent, page will redirect to ?process and where ofcourse you will have nothing to receive as $_GET parameters.
Assuming you have your ajax going right, add return false; at the end of your go() function. Also since on server side you have a clause like if(isset($_GET['process'])) { , you should also update your ajax url to something like: testAjax.php?process
Ok, a couple of things I spotted that maybe causing this issue.
Try:
<script>
function go(UserID) {
var name= encodeURI(document.getElementById('name').value);
var design= encodeURI(document.getElementById('design').value);
http.open('get', 'testAjax.php?process&design='+design+'&name='+name);
http.send(null);
}
</script>
<input id='name' type='text' />
<input id='design' type='hidden' value="<?=$UserID; ?>" />
Link
As you can see, we remove the html variable "process" and make it a part of the ajax call.

Get value of input box, without a form?

Does anyone know how I can get the value of an input box, without having a form? I want a submit button, but instead of submitting a form, I want it to change data in a MySQL database. Something like this maybe?
$img1="WHAT DO I PUT HERE?"
$idx=1
$sql="INSERT INTO games SET img1='$img1' WHERE id=$idx";
$result=mysql_query($sql);
Could I use that code on a "onclick" event? The input box's name and id is "img1".
If you don't want to submit a form, the only two other ways of accomplishing this are to click a link with the data as query parameters in the url, or use AJAX to send the data to the server in the background.
update:
Javascript, as usual. You'd put a link or button somewhere on the page with "Send to Server" or whatever for the text. The script would pull your information from the input fields, and then send it on to the server via an AJAX call. Something along these lines (note that I'm using Mootools for all this, as it makes life much easier than having to do the remote calls yourself):
function clickHandler() {
var img1 = $$("input[name='img1']")[0].value;
var r = new Request.JSON({
'url: 'http://yourserver.example.com/script.php',
'method': 'post',
'onComplete': function(success) { alert('AJAX call status: ' + (success ? 'succeeded': 'failed!'); },
'onFailure': function() { alert('Could not contact server'); },
'data': 'img1=' + img1
}).send();
}
and on the server you'd have something like:
<?php
$img1 = mysql_real_escape_string($_POST['img1']);
$idx=1;
$sql="INSERT INTO games SET img1='$img1' WHERE id=$idx";
$result=mysql_query($sql);
echo (($result !== FALSE) ? 1 : 0);
You'd probably want something more complicated than this, but this is the basis of an AJAX application. Some client-side javascript that makes requests, and a script on the server that handles them and returns any data/errors as needed.
Don't know if your completely against using a form or just might not know how to keep it hidden.
You can create a hidden form that submits the info with the click of a button.
<form name="hidden-form" action="youraction.php" method="post">
<input type="hidden" name="submitme" value="I get submitted">
<input type="hidden" name="submitmetoo" value="I get submitted">
<input type="hidden" name="submitmeaswell" value="I get submitted">
<input type="hidden" name="dontleavemeout" value="I get submitted">
<input name="submit" type="submit" value="SUBMIT" />
</form>
However anyone that looks at your html will be able to see this
I guess this is what you looking for.
this will only work if your html and php are on the same file...
<html>
<head>
</head>
<body>
<input type='text' id='user' placeholder='user'>
</body>
</html>
<?php
$val = "
<script>
document.write(document.querySelector('#user').value);
</script>
";
echo $val;
?>

Categories