Ajax Javascript function not being called - javascript

First question on StackOverflow so I hope i get this right. I have a AJAX call to a JS function :
function addOptionText(str)
{
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","AddText.php?q="+str,true);
xmlhttp.send();
}
And Here is my HTML code :
<body>
<FORM NAME ="form6" onclick= "addOptionText(this.value)" >
Text Input:
<INPUT TYPE = "TEXT" VALUE placeholder ="Nume Field" NAME ="Text_Field">
<INPUT TYPE = "Submit" Name = "Edit" VALUE = "Add" >
</FORM>
<p id="0"> </p>
</body>
The php file only contains :
<html>
<body>
<?php
$name = ($_GET['q']);
echo "nume";
?>
</body>
</html>
But the function doesn't appear to be used as the paragraph doesn't change. New to php here and trying to understand how it works so I'm thinking something might've slipped me.
EDIT
I had more than one "submit" id's so that's why it didn't work. I changed the "submit" id from to and now all's working as intended.

Unfortunately, your code is all over the place.
<FORM NAME ="form6" onclick= "addOptionText(this.value)" > is wrong for a multitude of reasons.
First, we don't use onclick on the form itself but on the submit button. Secondly the value you put in the parameter doesn't in any way represent the value of the text box.
Since you want just to display the value of your textbox and not to navigate to a different page, modify your <form> tag, so that it doesn't have an action = "some page" attribute, because that way it will automatically redirect you to the page you specify and thus the AJAX request is rendered useless. Instead, modify your tag so that it looks like this:
<form name = "form6" onsubmit = "return false;">Provided that you specify your input/button type to submit: type= "submit", using the onsubmit event and setting it to return false will prevent the form from sending you over to a new page.
When using Vanilla JavaScript and not jQuery, I believe its more efficient to use IDs, so as to identify your HTML elements easier in JavaScript.
Your PHP code doesn't mean anything at all. Before doing anything else, you need to evaluate if, indeed, the q was sent over to the PHP file with the GET method. To do that, use in your php file:if (isset($_GET["q"])): // Your codeendif;
The line: echo "nume" you wrote will output "nume" regardless of what you have actually sent to your php file with the AJAX request.
In my opinion is pretty useless to still provide support for Internet Explorer 5 and 6. Not many people use it, unless for whatever reason they are mentally bound to it.
Analytically, how your files should be:
HTML:
<body>
<form name = "form6" onsubmit = "return false;">
Text Input:
<input type = "TEXT" placeholder ="Nume Field" id = "textfield" name = "Text_Field"/>
<input id = "submit" type= "submit" Name = "Edit" value= "Add"/>
</form>
<p id = "0"> </p>
<script src = "YOUR JAVASCRIPT FILE" type = "text/javascript"></script>
</body>
JavaScript:
var textfield = document.getElementById("textfield");
var submit = document.getElementById("submit");
submit.onclick = function() {
'use strict';
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "AddText.php?q=" + textfield.value, true);
xmlhttp.send();
};
PHP:
<?php
if (isset($_GET["q"])):
echo ($_GET["q"]);
endif;
?>

Related

AJAX call to PHP not returning value

I have 3 files linked together index.php functions.js and compute.php
index.php has a div that calls a function in functions.js: compute() that sends an AJAX request to do something in compute.php
index.php:
<form id = "input_form">
<textarea name = "row" id = "inputform" placeholder="Input row here"></textarea>
<input type = "submit" value = "Enter" onclick="compute(inputform.value);">
</form>
<div id = "output_container">
<p id = "output"></p>
</div>
When the button is pressed, compute() is called passing in whatever was in the textarea as data.
function compute(row){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
output.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET","compute.php?row="+row,true);
xhttp.send(null);
}
This passes the value into a php script which simply is suppose to output what was in the textarea into #output
<?php
$str = $_GET['row'];
echo $str;
?>
When I test my program by clicking the button, nothing happens indicating something went wrong. I tried to pinpoint the problem by adding a window.alert('something'); after the check if(xhttp.readyState == 4) but a popup box never appears, making it seem like the issue is between functions and compute.
I tested out phpinfo(); and it looks like php is working properly on my server as well
Problem: Form is getting submitted without making ajax call, because your code contains type='submit'
Solution: Change type to button:
<input type = "button" value = "Enter" onclick="compute(inputform.value);">
Also update code to fetch the output properly:
if (xhttp.readyState == 4) {
document.getElementById("output").innerHTML = xhttp.responseText;
}

JavaScript form submit to database using Ajax and Laravel route

I'm making a quiz website using Laravel, Javascript and Ajax and I made an add form function with JavaScript like this:
But I want to send the form data (to create a new quiz question) into my Laravel QuizController route using Ajax, after the focus on the form is lost or after an enter..
But I can't figure out how to do it.
My JavaScript/Ajax:
var limit = 1;
var count = 0;
var myButton = document.getElementById('myButton');
var container = document.getElementById('container');
function createQuestion() {
if(count < limit) {
var input = document.createElement("input");
input.type = 'text';
input.id = '';
input.setAttribute('class', 'form-control')
container.appendChild(input);
count++;
}
else {
alert ('Enter this question first before you can add another question!');
}
}
function storeQuestion() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
My Laravel.blade:
<div class="form-group">
<div id="container"></div>
</div>
{!! Form::button('Add Quiz', array('onclick' => 'createQuiz()', 'class' => 'btn btn-default', 'id' => 'myButton', 'value' => 'Add question')) !!}
My QuestionController:
public function store(Quiz $quiz)
{
$input = Input::all();
$input['quiz_id'] = $quiz->id;
Question::create($input);
return Redirect::route('quizzes.show', $quiz->slug)->with('message', 'Question created.');
}
I hope someone can help me because I'm pretty stuck up with this problem for some time..
To use AJAX instead of standard HTTP POST you should catch enter and blur events.
How to catch enter is explained in first answer to input type text and onKeyDown not working under IE but in test for enter you should run storeQuestion
to add blur add :
<input type="text" name="item_code" onkeydown="test(event)" onblur="storeQuestion()">
Your store function should not return a Redirect::route but some status code or JSON string. If you use laravel 4 http://laravel.com/api/4.1/Illuminate/Http/JsonResponse.html that would just say "OK" or true or error
You should modify storeQuestion to add the new answer/edit/delete buttons to the list also. ( // )
A simpler way would be to not use AJAX but just submit the form with javascript after focus is lost by attaching an onblur event handler to the textbox.
var req = new XMLHttpRequest();
queryString = "access_token=" + access_token + "&data=" + data;
req3.open('GET', '/path/of/laravel/route?' + queryString, true);
req3.send(queryString)

Getting a null value to database when AJAX is used

I got this registration code which was working fine but I decided to add AJAX to make it more dynamic but when I run it, my PHP code was saving null value to database.
This is what I know so far: whenever a user writes information in signup page it goes to AJAX and the ajax pass it along to php and then php saves the info into database and it echo a message and then it goes to ajax and then it displays the message. All of this works the only problem is that my php code is saving null value no matter what i write in signup page.
and i think this is the code thats not working properly but i just dont know the other way
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "signip_parse.php?username="+username+"&password="+password;
the following is rest of my code. this is the page were user puts information and its saved as signup.php
<head>
<script src = "ajax.js"></script>
<div id="content">
</head>
<body>
<form action="signip_parse.php" method="post" id="registration_form">
<p>Name <input type="text" name="username" id = "username"/></p>
<p>Password <input type="password" name="password" id = "password"/></p>
<p><input type = "button" value="sign up" id="submit" onclick = "hello()"/>
<input type="button" value="Back" onclick="return back()"/></p>
</form>
<div id="ack"><p>1</p></div>
</div>
</body>
and this is the ajax code that I got it from w3school ajax example and i saved it as ajax.js
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
var HTTP = loadXMLDoc();
function hello(){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "signip_parse.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState==4 && HTTP.status==200)
{
document.getElementById("ack").innerHTML=HTTP.responseText;
}
}
HTTP.open("POST", url ,true);
HTTP.send();
}
and last this is the signip_parse.php where i managed to spell signup wrong
<?php
include_once("connect.php");
$user = mysql_real_escape_string( $_POST["username"]);
$password = mysql_real_escape_string( md5 ($_POST["password"]));
$sql = "INSERT INTO users (username, password) VALUES ('$user','$password')";
if(mysql_query($sql)){
echo "You have been successfully registered";
}
else{
echo "Something went wrong try again";
}
?>
Any help would be great. thanks guys
and yes i know md5 is broken but this is just a demo and intend to used something else.
Since you're sending a request as post, its important to add this on your XMLHttpRequest object:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
And just combine them inside, no need to separate some parts. It would look something like this:
<script type="text/javascript">
function hello() {
var xmlhttp = new XMLHttpRequest();
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("ack").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", 'signip_parse.php', true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("username="+username+"&password="+password);
}
</script>
Here's what it would look like
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Ref: https://stackoverflow.com/a/12860140/3859027
You should consider also (if you're using PHP 5.5 or greater) to use PHP's native password hashing and replace that md5() instead. If you're below v5.5 then you could use the its compatibility pack

Ajax code is not working

So I have this program in which the user enters a city and a country. The program looks in the database to see if the city doesn't already exists, if it does I show a warning message using ajax, if not i add the city to the database.
This is the form:
<form action="addCity.php" method="get" onsubmit="return validateCityInfoForm();">
onsumbit I call the javascript function validateCityInfoForm() that looks like this:
function validateCityInfoForm() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if (xmlhttp.responseText == "true") {
document.getElementById("checkIfCityExistsWarning").style.display = "block";
document.getElementById("checkIfCityExistsWarning").innerHTML = "This city already exists!";
return false;
}
}
}
xmlhttp.open("GET", "checkIfCityExists.php?city=" + cityInput + "&country=" + countryInput, true);
xmlhttp.send();
}
checkIfCityExists.php echoes "true" if the city already exists in the database and "false" otherwise.
The problem is that it always adds the city in the db even though the city already exists.
checkIfCityExists.php returns "true" but it doesn't seem to matter.
I really don't know what the problem is, any help would be greatly appreciated.
Thanks!
here is checkIfCityExists.php:
<?php
include ('database_connection.php');
$city = mysqli_real_escape_string($dbc, $_GET['city']);
$country = mysqli_real_escape_string($dbc, $_GET['country']);
//check if the city and country already exists in the database
$query_verify = "SELECT * FROM city WHERE name = '$city' AND country = '$country'";
$result_verify = mysqli_query($dbc, $query_verify);
if(mysqli_num_rows($result_verify) == 0) { //if the city does not appear in the database
echo "false";
}
else {
echo "true";
}
?>
You are trying to make an asynchronous call to do validation. By the time the call comes back it is too late because the form already is submitted.
Tha Ajax call does not pause the code execution, it makes the call and the rest of the code happens.
What you would need to do it break it up into two steps, make the Ajax call and when the onreadystatechange comes back, submit the form.
The problem is, your onsubmit has no return.
So validateCityInfoForm() returns undefined which does not prevent the Browser from executing the action. validateCityInfoForm() should return false to prevent the Browser from submitting the form. And then in the onreadystatechange call form.submit() if necessary.

XMLHttpRequest to Post HTML Form

Current Setup
I have an HTML form like so.
<form id="demo-form" action="post-handler.php" method="POST">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething">Update</button>
</form>
I may have many of these forms on a page.
My Question
How do I submit this form asynchronously and not get redirected or refresh the page? I know how to use XMLHttpRequest. The issue I have is retrieving the data from the HTML in javascript to then put into a post request string. Here is the method I'm currently using for my zXMLHttpRequest`'s.
function getHttpRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function demoRequest() {
var request = getHttpRequest();
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
console.log("Response Received");
}
}
request.open("POST","post-handler.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("action=dosomething");
}
So for example, say the javascript method demoRequest() was called when the form's submit button was clicked, how do I access the form's values from this method to then add it to the XMLHttpRequest?
EDIT
Trying to implement a solution from an answer below I have modified my form like so.
<form id="demo-form">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething" onClick="demoRequest()">Update</button>
</form>
However, on clicking the button, it's still trying to redirect me (to where I'm unsure) and my method isn't called?
Button Event Listener
document.getElementById('updateBtn').addEventListener('click', function (evt) {
evt.preventDefault();
// Do something
updateProperties();
return false;
});
The POST string format is the following:
name=value&name2=value2&name3=value3
So you have to grab all names, their values and put them into that format.
You can either iterate all input elements or get specific ones by calling document.getElementById().
Warning: You have to use encodeURIComponent() for all names and especially for the values so that possible & contained in the strings do not break the format.
Example:
var input = document.getElementById("my-input-id");
var inputData = encodeURIComponent(input.value);
request.send("action=dosomething&" + input.name + "=" + inputData);
Another far simpler option would be to use FormData objects. Such an object can hold name and value pairs.
Luckily, we can construct a FormData object from an existing form and we can send it it directly to XMLHttpRequest's method send():
var formData = new FormData( document.getElementById("my-form-id") );
xhr.send(formData);
The ComFreek's answer is correct but a complete example is missing.
Therefore I have wrote an extremely simplified working snippet:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
var xhr = new XMLHttpRequest();
xhr.onload = function(){ alert(xhr.responseText); }
xhr.open(oFormElement.method, oFormElement.getAttribute("action"));
xhr.send(new FormData(oFormElement));
return false;
}
</script>
</head>
<body>
<form method="POST"
action="post-handler.php"
onsubmit="return submitForm(this);" >
<input type="text" value="previousValue" name="name"/>
<input type="submit" value="Update"/>
</form>
</body>
</html>
This snippet is basic and cannot use GET. I have been inspired from the excellent Mozilla Documentation. Have a deeper read of this MDN documentation to do more. See also this answer using formAction.
By the way I have used the following code to submit form in ajax request.
$('form[id=demo-form]').submit(function (event) {
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// fire off the request to specific url
var request = $.ajax({
url : "URL TO POST FORM",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
});
// prevent default posting of form
event.preventDefault();
});
With pure Javascript, you just want something like:
var val = document.getElementById("inputFieldID").value;
You want to compose a data object that has key-value pairs, kind of like
name=John&lastName=Smith&age=3
Then send it with request.send("name=John&lastName=Smith&age=3");
I have had this problem too, I think.
I have a input element with a button. The onclick method of the button uses XMLHTTPRequest to POST a request to the server, all coded in the JavaScript.
When I wrapped the input and the button in a form the form's action property was used. The button was not type=submit which form my reading of HTML standard (https://html.spec.whatwg.org/#attributes-for-form-submission) it should be.
But I solved it by overriding the form.onsubmit method like so:
form.onsubmit = function(E){return false;}
I was using FireFox developer edition and chromium 38.0.2125.111 Ubuntu 14.04 (290379) (64-bit).
function postt(){
var http = new XMLHttpRequest();
var y = document.getElementById("user").value;
var z = document.getElementById("pass").value;
var postdata= "username=y&password=z"; //Probably need the escape method for values here, like you did
http.open("POST", "chat.php", true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", postdata.length);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(postdata);
}
how can I post the values of y and z here from the form

Categories