I have a html with some javascript in in, now I want to run another php-file (test.php) without showing or opening this file. It's part of a loop and I tried:
for(i = 1; i < length; i++){
var bname = table.rows[i].cells.item(0).innerHTML;
var bvalue = table.rows[i].cells.item(1).innerHTML;
location.href = "test.php?account="+account+"&key="+key+"&memo="+memo+"&bname="+bname+"&bvalue="+bvalue;
}
But this will redirect the current location and runs only once...
I also tried to use:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","test.php?account="+account+"&key="+key+"&memo="+memo+"&bname="+bname+"&bvalue="+bvalue);
xmlhttp.send();
But that seems not to work.
I also found the hint to use ajax, but I never used it and don't know how to pass my variables to test.php.
Thanks for your help!
You can do using ajax,
$.post("test.php",
{
account: account,
key: key,
memo:memo,
bname:bname,
bvalue:bvalue
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
use ajax to send data from javascript to a php file
vars="account="+account+"&key="+key+"&memo="+memo+"&bname="+bname+"&bvalue="+bvalue;
var ajaxhr = new XMLHttpRequest();
var url = "test.php";
ajaxhr.open("POST", url, true);
ajaxhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxhr.onreadystatechange = function() {
if(ajaxhr.readyState == 4 && ajaxhr.status == 200) {
var return_data = ajaxhr.responseText;
}
}
ajaxhr.send(vars);
I am posting this for a detailed answer to help PHP and Javascript side.
I would use jQuery + AJAX. Reference: http://api.jquery.com/jquery.ajax/
Ajax is great for sending data to php, reading data from php etc..
Please take time to look at my reference to read up on how it all works for future knowledge!
Lets get into the code!
Ajax (Javascript - Client Side):
var memoData = "Today is beautiful"; //Varible passed for ajax data
$.ajax({
url : '/LocationToTestPHP/test.php', //Location to PHP File
cache: false,
type: 'POST', //Type of method - Remove this line for GET if required
data: {account: "Welcome", key: "ValueHere", memo: memoData, bname: "ValueHere", bvalue: "ValueHere"} //Data to send to PHP
}).done(function(data)
{
//We check if PHP sent us back the correct data required here.
if(data == "Success")
{
alert("Success! Data returned is: " + data);
}
else
{
alert("Error! We didnt get correct data back. Data: " + data);
}
});
Please note, i provided a variable into ajax data for memo, this is
also possible.
PHP (Server Side) - test.php:
<?PHP
//Check for our value and return data
if($_POST['account'] == "Welcome") //Check if account has Welcome passed in..
{
echo "Success";
}
else //Welcome is not provided
{
echo "Account did not equal to Welcome :(";
}
?>
I quickly typed this up so hopefully you get the correct idea! Any help required, comment below :)
Related
I'm a new developer. I've read a lot of question all around about my topic, and I've seen a lot of interesting answers, but unfortunately, I cannot find a way to resolve mine.
I have a simple form in HTML and <div id="comment"></div> in it (empty if there is nothing to pass to the user). This DIV is supposed to give updates to the user, like Wrong Username or Password! when it's the case. The form is treated via PHP and MySQL.
...
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
header("Location: ../main.html");
} else {
//Please update the DIV tag here!!
}
...
I tried to "read" PHP from jQuery (with AJAX), but whether I didn't have the solution, or it cannot be done that way... I used this in jQuery (#login is the name of the form):
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
$("#comment").replaceWith(data); // You can use .replaceWith or .html depending on the markup you return
},
error: function(errorThrown) {
$("#comment").html(errorThrown);
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
But I'd like to update the DIV tag #comment with some message if the credentials are wrong. But I have no clue how to update that DIV, considering PHP is treating the form...
Can you help please ?
Thanks in advance ! :)
In order for AJAX to work, the PHP must echo something to be returned from the AJAX call:
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'good';
} else {
//Please update the DIV tag here!!
echo 'There is a problem with your username or password.';
}
But this will not show up in error: function because that function is used when AJAX itself is having a problem. This text will be returned in the success callback and so you must update the div there:
success:function(data) {
if('good' == data) {
// perform redirect
window.location = "main.html";
} else {
// update div
$("#comment").html(data);
}
},
In addition, since you're calling the PHP with AJAX, the header("Location: ../main.html"); will not work. You will need to add window.location to your success callback dependent upon the status.
To begin, your pretend is using Ajax to send form data to PHP. So your client (HTML) have to communicate completely via Ajax. After you do authenticate, you need send an "Ajax sign" to the client.
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'true';//it's better for using json format here
// Your http header to redirect won't work in this situatition
// because the process is control by javascript code. Not PHP.
} else {
echo "false";//it's better for using json format here
}
//the result is either true or false, you can use json to send more details for client used. Example: "{result:'false', message:'wrong username'}";
// use PHP json_encode(Array(key=>value)) to convert data into JSON format
Finally, you have to check the "Ajax sign" in your js code:
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
// You can use `data = JSON.parse(data)` if the data format is JSON
// Now, data.result is available for your checked.
if (data == 'true')
window.location.href = "main.html";
else
$("#comment").html('some message if the credentials are wrong');
},
error: function(errorThrown) {
$("#comment").html('Other error you get from XHTTP_REQUEST obj');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
I want to fetch data when onclick is invoked. I have four div in my form and I want only a particular div to be reloaded and fetch data. while loading it should not discard the form data. Anyone help. Thanks in advance for people who are going to help me in this.
my code looks something like this
<div id="fetch">
<?php
//query to fetch data
?>
</div>
<div id="data4">
//dynamic data
//Want to retain this data even after fetch
</div>
In this case you should use AJAX.
Onclick you can send a xmlhttprequest (JS) to a separate php file, which returns the data you need (for example as string / JSON), and insert it into your website with JS.
Example:
function test()
{
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if(xhr.readyState==4 && xhr.status==200)
{
result = xhr.responseText;
document.getElementById("test_field").innerHTML = result;
}
}
xhr.open("GET","your_ajax_file.php",true);
xhr.send();
}
your_ajax_file.php returns the data you want to insert.
You mentioned you have a problem with function call, but you did not give more information. so i will give you an example how to write an ajax request, then you can maybe give me more detailed info on where your problem is.
$.ajax({
url: 'ajax_file.php',
type: 'post',
data: {var1: 'value1', var2: 'value2'},
success: function( data ){
console.log('ajax request successful! data: '+data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
And in your ajax_file.php do something like this:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
echo $var1.', '$var2;
edit: typo, changed val2 to var2 in ajax request
I have web page that submits a form via AJAX in codeigniter, submission works great, and the php script works as well, but when php is done it return an HTML view as a response to Ajax so it repopulates a div but instead of repopulating it try's to download the file. Chrome console shows
Resource interpreted as Document but transferred with MIME type application/text/HTML
has me confused because I use the same code in another page and it works fine.
This is my Jquery script
$("#addpaymentform").submit(function (event) {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
data: formdata,
url: baseurl + 'sales/add_payment',
success: function (data, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
$('#paymets').html();
$('#payments').html(data);
$('#addpaymentform').each(function() { this.reset() });
}
if (ct.indexOf('json') > -1) {
$("#Mynavbar").notify(
data,
{position: "bottom center"}
);
$('#addpaymentform').each(function() { this.reset() });
}
}
});
event.preventDefault(); // this will prevent from submitting the form.
});
and this is my controller
function add_payment()
{
$this->form_validation->set_rules('fpay', 'Type of payment', 'trim|required|alpha');
$this->form_validation->set_rules('payment', 'Payment', 'trim|numeric');
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
header('Content-type: application/json');
echo json_encode(validation_errors());
} else {
$fpay = filter_var($this->input->post('fpay'), FILTER_SANITIZE_STRING);
$payment = filter_var($this->input->post('payment'), FILTER_SANITIZE_STRING);
if(isset($_SESSION['payments'][$fpay]))
{
$temp = $_SESSION['payments'][$fpay] + $payment;
$_SESSION['payments'][$fpay] = $temp;
header('Content-type: application/html');
echo $this->_loadpaymentcontent();
}
}
}
function _loadpaymentcontent() {
$this->load->view('payment_content');
}
Hope someone can point me in the right direction I've been stuck on this for 2 days.
Thanks everyone.
I had the same problem and i successfully solved it by putting an exit; after the value which is returned to the ajax call in the controller method.
In your case it will be:
echo $this->_loadpaymentcontent();
exit;
What exit does here is it limits the returned value to the value which should be returned to the ajax call and exits before the html is appended to the returned value.
This is what is obvious per the effect it produces.
Yo need to set up your AJAX.
$.ajax({
type : 'POST',
url : baseurl + 'sales/add_payment',
dataType : 'html', // Will set the return type of the response as AJAX.
... Keep rest of the code same.
I have a function connected with onclick button.
It sends some data through ajax to another php file.
Actually everything was working fine, but I tried to add now to 'success' a simple IF statement, that would get true or false from external file.
I guess some of the syntax may be wrong here because the error message says that my main fuction is not defined.
Could someone find some mistakes here please?
main file (here in success: i have added if else statement only):
$.ajax({
type: 'get',
url: '/editcomment',
data: {newComment: newComment,
id: id,
userId: userId},
success:function(data){
if(data.success){
$(".newCommentForm" +id).replaceWith("<span id='" + id + "' class='limitedText'>" + newComment + "</span>");
$(thisId).data("PinComment", newComment);
}
else { alert('error');},
error:function(){
alert('error');
}
});
}
external file (i have added the return arrays here):
public function editComment(){
$userId = Input::get('userId');
if ( $userId == Auth::id() or Auth::user()->hasRole("admin")){
$id = Input::get('id');
$newComment = Input::get('newComment');
DB::update('UPDATE `comments` SET f_text = ? WHERE h_id = ?', array($newComment, $id));
return array('success' => true);
} else {
return array('success' => false);
}
}
You have a typo here else { alert('error');},, you need another closing brace to close the success function.
You are trying to access PHP array in JS that not possible. What you need to do is, either you need to return response as an string or JSON from PHP file
see: Get data from php array - AJAX - jQuery
Get rid of commas. Try this in else block
jAlert('No Success', 'alert box');
I amc creating A Login script with php and javascript.
What I want to do is log the user in without the page refresh which I have archived so far, With some help from Stack Flow users, I am fairly good with PHP but new to the Javascript client side.
Anyway, When the user enters the correct data and the session gets started how do I get it to call the fade out function?
Heres the PHP Side
<?php
require "../core/database.php";
//lets create some veriables to use, This way is shorter
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
if (($user_login) && ($password)) {
//Connect to the database to fetch the users username and password
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
//I HAVE CALLED IT HERE HOPING THERE,S A BETTER WAY OF DOING THIS. IT WILL CAL
echo "
Yes, Now we can start the session right here, when your ready.
<script>
$('#field').fadeOut();
</script>";
} else {
echo "The username or password you entered is incorrect";
}
} else {
echo "<b>Blank Fields</b> <br>
You must enter A Username/Password Combination";
}
?>
Incase yous need it, there is the client side aswill (modified by some users to make the functionality better)
$(document).ready(function() {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
user_login: $('#user_login').val(),
pass_login: $('#pass_login').val()
}
}
function loading(e) {
$('#content').html('Loading Data');
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
$('#content').html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function(e) {
if (e.keyCode == 13) {
var username = $('#user_login').val();
loading(e);
check(e);
}
});
$('#submit').click(function(e) {
if (e.keyCode != 13) {
loading(e);
check(e);
}
});
});
Since PHP is Server Side and Java Script controls the Client side, Probably the best way to do or call it is this way, But its worth A ask anyway.
Besides this everything is working out well.
If you want you can help change the way loading data is coded/works, But the functionality is working perfectly so theres not much need.
The ajax success method needs to check the response from the server to see if login was successful and then take the appropriate action:
// php
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
echo 'correct';
} else {
echo 'The username or password you entered is incorrect';
}
// js
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
if (data === 'correct') {
$('#field').fadeOut();
} else {
$('#content').html(data);
}
}
});
}
Returning JSON instead of raw HTML is much more flexible. Quick example:
PHP Side
<?php
require "../core/database.php";
$json = array('success' => false, 'error' => null);
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
if (($user_login) && ($password)) {
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
$json['success'] = true;
}
else {
$json['error'] = "The username or password you entered is incorrect";
}
} else {
$json['error'] = "<b>Blank Fields</b> <br>You must enter A Username/Password Combination";
}
echo json_encode($json);
Your AJAX function:
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
var loginResult = JSON.parse(data);
if(loginResult.success){
//Login successful - fade out whatever form or fields
//that you want to
$('#field').fadeOut();
} else{
//Add error message to an error div or whatever
$('#error').html(loginResult.error);
}
}
});
}
I'll start by saying that your PHP should be using the newer mysqli_* functions or the PDO object for all of your database queries. Further, you should be using prepared statements which will safeguard you against SQL injection attacks.
Another thing to note is that in a PHP file that is not going to output anything to the browser, or in other words, is just going to run some code, you don't need a closing tag. In fact, you don't want a closing tag. That is because anything after the closing tag will get sent to the browser, which will get included in the response of your AJAX success function. That includes things like spaces and new lines.
Now, on to your PHP. You are going to want to output some JSON so that you can check for success or failure in your AJAX.
PHP
<?php
require "../core/database.php";
//lets create some veriables to use, This way is shorter
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
//Create an array to represent our JSON data.
$json = array(
"successCode" => 0
);
if (($user_login) && ($password)) {
//Connect to the database to fetch the users username and password
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
//echo "Yes, Now we can start the session right here, when your ready."
$json['successCode'] = 0;
} else {
//echo "The username or password you entered is incorrect";
$json['successCode'] = 1;
}
} else {
//echo "<b>Blank Fields</b> <br>
//You must enter A Username/Password Combination";
$json['successCode'] = 2;
}
//Set that our content type is JSON
header("Content-type: application/json");
echo json_encode($json); //Convert the PHP array to JSON and echo it as the response.
In our PHP, we have created a $json array which will story the successCode that we will be responding to the client. This will tell the client if the login was a success or failure, and even what type of failure occurred. It will then be up to the client to decide how to display that success or failure to the user. This allows multiple applications to use the same server side source, but display the errors differently if desired.
At the end of the PHP, we have set the header Content-type to specify that we are sending back application/json to the client. Then, we encode the PHP array as JSON, and output it to the response.
jQuery/Javascript
//Let's define different messages depending on what status code we get on the client.
var errorMessages = [
"Yes, Now we can start the session right here, when your ready.",
"The username or password you entered is incorrect",
"<b>Blank Fields</b><br />You must enter A Username/Password Combination"
];
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
//First, make sure that data and data.successCode are defined.
if (data && data.successCode) {
//Here, you are getting back the JSON data from the login call.
$('#content').html(errorMessages[data.successCode]);
//If the successCode is 0, which means it was successful, then we want to fade out the #field div.
if (data.successCode == 0) {
$('#field').fadeOut();
}
} else {
//There must've been a server error. You'd handle that here.
}
}
});
}
Why put the error messages on the client instead of the server? Because it allows you to easily change how the error messages are displayed, without having to touch the server side code. The server just outputs an error code, and the client decides how to handle that code.
The Javascript array, errorMessages, defines the error messages corresponding to their index in the array. The error message at index 0 would correspond to successCode = 0, and so on. If you weren't going to use sequential successCodes, you could use a javascript object to specify keys corresponding to each error code.