How to continuously update a part of the page - php

http://pastebin.com/dttyN3L6
The file that processes the form is called upload.php
I have never really used jquery/js so I am unsure how I would do this or where I would put the code.
It has something to do with this setInterval (loadLog, 2500);
Also, how can I make it so the user can submit a form without the page refreshing?
$.ajax({
type: "POST",
url: "upload.php",
data: dataString,
success: function() {
}
});
return false; `
and
<?php
$conn1 = mysqli_connect('xxx') or die('Error connecting to MySQL server.');
$sql = "SELECT * from text ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn1, $sql) or die('Error querying database.');
while ($row = mysqli_fetch_array($result)) {
echo '<p>' . $row['words'] . '</p>';
}
mysqli_close($conn1);
?>
</div>
<?php
if (!isset($_SESSION["user_id"])) {
} else {
require_once('form.php');
}
?>

You can submit a form without refreshing a page something like this:
form.php:
<form action='profile.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='result'>Result comes here..</div>
profile.php:
<?php
// All form data is in $_POST
// Now perform actions on form data here and
// create an result array something like this
$arr = array( 'result' => 'This is my result' );
echo json_encode( $arr );
?>
jQuery:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
// loop to set the result(value)
// in required div(key)
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
And If you want to call an ajax request without refreshing page after a particular time, you can try something like this:
var timer, delay = 300000;
timer = setInterval(function(){
$.ajax({
type : 'POST',
url : 'profile.php',
dataType: 'json',
data : $('.ajaxform').serialize(),
success : function(data){
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
}, delay);
And you can stop the timer at any time like this:
clearInterval( timer );
Hope this will give you a direction to complete your task.

This is pretty simple.
To access elements using Jquery you use css selectors, for example, to get value of an input field with name "foo" you do the following:
var fooVal = $("input[name=foo]").val();
To send it over to the server you are to append an event listener (for example, click) to the submit button/any other element
var data = { varName : fooVal };
var url = "http://example.com";
var responseDataType = "json";
function parseResponse(JSON)
{
// your code handling server response here, it's called asynchronously, so you might want to add some indicator for the user, that your request is being processed
}
$("input[type=submit]").on('click', function(e){
e.preventDefault();
$(this).val("query processing");
$.post(url,data, parseResponse, responseDataType);
return false;
});
If you want to do constant updates, you can, of course, add timers or some other logic. But I hope you get the idea of how to proceed to such cases;

To answer part of your question, you can use ajax.
<html><head></head><body>
<div id="feed"></div>
<script type="text/javascript">
var refreshtime=10;
function tc()
{
asyncAjax("GET","upload.php",Math.random(),display,{});
setTimeout(tc,refreshtime);
}
function display(xhr,cdat)
{
if(xhr.readyState==4 && xhr.status==200)
{
document.getElementById("feed").innerHTML=xhr.responseText;
}
}
function asyncAjax(method,url,qs,callback,callbackData)
{
var xmlhttp=new XMLHttpRequest();
//xmlhttp.cdat=callbackData;
if(method=="GET")
{
url+="?"+qs;
}
var cb=callback;
callback=function()
{
var xhr=xmlhttp;
//xhr.cdat=callbackData;
var cdat2=callbackData;
cb(xhr,cdat2);
return;
}
xmlhttp.open(method,url,true);
xmlhttp.onreadystatechange=callback;
if(method=="POST"){
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send(qs);
}
else
{
xmlhttp.send(null);
}
}
tc();
</script>
</body></html>

Related

Ajax request shows complete but data not submitted

I have a simple modal window containing an input field. I am using jquery ajax to validate as well as submit data to database using php. The ajax request shows status code 200 ok but data doesnt get inserted and no success function executes. Does anyone notice any error? Need help
<script type="text/javascript">
$(document).ready(function() {
$("#add_location").click(function() {
var inputDiv = $('#inputDiv').val();
var dataString = 'location=' + inputDiv;
if (inputDiv == '') {
$('#error_message').html("Please enter a location");
} else {
$.ajax
({
type: "POST",
url: "add_location.php",
data: dataString,
success: function(data)
{
$("#error_message").empty();
$("#error_message").html(data);
}
});
}
return false;
});
});
</script>
add_location.php
<?php
$location = new dbhandler();
$ran_id = mt_rand(45287,98758);
if(isset($_POST)) {
$locationData = $_POST['location'];
try{
$location->create('shop_locations', array(
'r_id' => $ran_id,
'location' => $locationData,
));
echo "Location successfully added";
}catch(Exception $e){
die($e->getMessage());
}
}
create() is a method for inserting data
create($tableName, $fields = array());
You can try something
//js file
$.ajax({
url: "You_url",
type: "POST",
data: $("#form_name").serialize(),
headers: {
'Authorization' : 'JWT ' + token
}
})
.done(function (data) {
console.log(data);
})
.fail(function (data) {
console.log(data);
});
And echo post data in php file if you get anything. I was using JWT so I have used JWT here and token is the variable where I am storing my token
I think you're referring the wrong the DOM id. You probably have this formation.
<div id="inputDiv">
Location <input type="text" id="myInput"><br>
</div>
In this case inputDiv = $('#inputDiv').val() will be different with inputDiv = $('#myInput').val()

Ajax POST to Cakephp Controller always give array() result

i really struggle to get the POST value in the controller .i am really new to this..Please someone share me some light..being in the dark for long hours now.
i had a checkboxes and need to pass all the ids that had been checked to the controller and use that ids to update my database.i don't know what did i did wrong, tried everything and some examples too like here:
sending data via ajax in Cakephp
found some question about same problem too , but not much helping me( or maybe too dumb to understand) . i keep getting array();
please help me..with my codes or any link i can refer to .here my codes:
my view script :
<script type="text/javascript">
$(document).ready(function(){
$('.checkall:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$('#button').click( function (event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
var value = memoData.join(", ")
//alert("value are: " + value);
//start
$.ajax({
type:"POST",
traditional:true;
data:{value_to_send:data_to_send},
url:"../My/deleteAll/",
success : function(data) {
alert(value);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});
//end
} ); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
my controller :
public function deleteAll(){
if( $this->request->is('POST') ) {
// echo $_POST['value_to_send'];
//echo $value = $this->request->data('value_to_send');
//or
debug($this->request->data);exit;
}
}
and result of this debug is:
\app\Controller\MyController.php (line 73)
array()
Please help me.Thank you so much
How about this:
Jquery:
$(document).ready(function() {
$('.checkall:button').toggle(function() {
$('input:checkbox').attr('checked','checked');
$('#button').click(function(event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
//start
$.ajax({
type: 'POST',
url: '../My/deleteAll/',
data: {value_to_send: memoData},
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});//end ajax
}); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
In controller:
public function deleteAll()
{
$this->autoRender = false;
if($this->request->is('Ajax')) { //<!-- Ajax Detection
$elements = explode(",", $_POST['value_to_send']);
foreach($elements as $element)
{
//find and delete
}
}
}
You need to set the data type as json in ajax call
JQUERY CODE:
$.ajax({
url: "../My/deleteAll/",
type: "POST",
dataType:'json',
data:{value_to_send:data_to_send},
success: function(data){
}
});

Pass data from ajax to php [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Ajax:
function check_user_country_prod(userId , countryCode , testType )
{ //using alert to check that all data are correct
$.ajax({
type: "POST",
url: "http://localhost/test/testForm.php",
data: { userId: userId ,
countryCode : countryCode ,
productCode: testType
},
success:function(res) {
if(res == "OK")
return true;
else
return false;
}
});
}
PHP:
<?php
require_once("Connections/cid.php");
$userId= $_POST['userId'];
$productCode= $_POST['productCode'];
$countryCode= $_POST['countryCode'];
$sql_check = "SELECT * FROM utc WHERE userId = '$userId' AND productCode = '$productCode' AND countryCode = '$countryCode'";
$list = mysqli_query( $conn, $sql_check);
$num = mysqli_fetch_assoc($list);
if($num >0)
echo "OK";
else
echo "NOK";
?>
I am very sure that the data i had pass in to the php file are correct. However i cant seem to get my data to the php file and it keep return false value back to me. Anything i can do to make it works?
**Note: Somehow even if i change both result to return true in ajax, it will still return false.
and i tried to change the link to another file with only echo "OK"; but it also doesn't work. So i think it is not the file problem. It just never run the ajax no matter what. Do i need to do any link for ajax to run? **
function check_user_country_prod(userId , countryCode , testType )
{ //using alert to check that all data are correct
$.ajax({
url: "test/testForm.php"
type: "POST",
url: "http://localhost/test/testForm.php", // This needs to be "test/testForm.php"
data: { userId: userId ,
countryCode : countryCode ,
productCode: testType
},
success:function(res) {
if(res == "OK")
return true;
else
return false;
}
});
}
Adjust this code according your input type. I hope this will help you:
$(document).ready(function() {
$("#submit_btn").click(function() {
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_phone = $('input[name=phone]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if(user_name==""){
$('input[name=name]').css('border-color','red');
proceed = false;
}
if(user_email==""){
$('input[name=email]').css('border-color','red');
proceed = false;
}
if(user_phone=="") {
$('input[name=phone]').css('border-color','red');
proceed = false;
}
if(user_message=="") {
$('textarea[name=message]').css('border-color','red');
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userMessage':user_message};
//Ajax post data to server
$.post('contact_me.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$('#contact_form input').val('');
$('#contact_form textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function() {
$("#contact_form input, #contact_form textarea").css('border-color','');
$("#result").slideUp();
}); });
Try this also both are running on my localhost:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function (d) {
alert(d);
}
});
});
});
</script>
<form method="post" id="myform">
<input type="text" name="time" /><br>
<input type="text" name="date" /><br>
<input name="submit" type="submit" value="Submit">
</form>
make new file of post.php and pest this code. This code will alert your input field value:
<?php print_R($_POST); ?>
"my current folder is localhost/abc/bsd.php while the one that i am going is localhost/test/testForm.php".
From the above comment, you have to change the ajax url to
url: "/test/testForm.php",
Apart from this , your php code shows
$num = mysqli_fetch_assoc($list);
if($num >0)
echo "OK";
This is incorrect as mysqli_fetch_assoc returns an associative array of strings. So, the comparison $num >0 is illogical.

window open does not work after form submit

I have the following function to commit the values to a mysql database. The php ajax call works fine. But after the insert function, it does not execute the code related to window.open where it should go to index.html page.
function sendval(){
var tosubmit = validateForm();
if(tosubmit){
showprog();
// now create the json string to insert in the database
var myData = {};
myData.EmpName=localStorage.getItem("username");
myData.LeaveType = $( "#leavetype option:selected" ).text();
myData.LeaveStart = $('#txtFromDate').val();
myData.LeaveEnd = $('#txtToDate').val();
myData.ContactNum = $('#contactnum').val();
myData.Comments = $('#Comments').val();
myData.UsrMail = localStorage.getItem("usermail");
myData.SupMail = localStorage.getItem("supmail");
myData.Status = 'Submit';
var myjson = JSON.stringify(myData);
$.ajaxSetup( { "async": false } );
$.ajax({
method: "POST",
url: "submitleave.php",
data: {"points": myjson}
})
.done(function( msg ) {
if(msg == 'Success') {
alert("Submission successful");
} else {
alert("Could not sumbit - try again");
}
$.ajaxSetup( { "async": true } );
window.open("index.html","_self");
});
} else {
alert("Please enter valid values before submitting the form");
}
}
I tried a few iterations but do not seem to get the error.
Some of the other functions do not work as well.
<header>XXXXX<br>
<br><input type="button" value="Logoff" id="logoff">
</header>
$('#logoff').click(function(){
localStorage.clear();
window.open("index.html","_self");
});
Regards,

Using jquery blur with input having brackets[] with this.val and ajax together

This maybe easy for some of you, I'm have inputs with names with brackets, when the one gets a value I want to query the database using ajax to get the part number and put the value in the first empty pn[] field.
My HTML is:
<td>Record ID<span class="switchRed">*</span><br>
<input type="text" name="ri[]" id="ri" size="8" style="font-size:0.9em;" class="do_stuff"></td>
<td>Part Number<br>
<input type="text" name="pn[]" id="pn" style="font-size:0.9em;" class="readlock" readonly></td>
My Jquery / Ajax is
<script>
$(document).ready(function() {
$("[name='ri[]']").on("blur", "[name='ri[]']", function() {
var rival = $(this).val($(this).val());
$.ajax({
url: "/inventory/get-part-number.php",
type: "post",
data: "record=" + rival,
// callback for success
success: function(data, textStatus) {
$("[name='pn[]']").each(function() {
if(!$(this).val() ) {
$(this).val(data); //put value in empty pn[]
}//end if
})//End each
}, //end success else...
//if failsauce throw error
error: function() {
alert('Learn To Code');
} //end error failsauce
}); //ends .ajax function
}); //end blur
}); // ends ready function
</script>
The get-part-number.php is a simple mysql_query..
$message='';
if(isset($_POST['record'])){ $record_id = $_POST['record']; }else{$record_id='';}
//Get Part Number
$sql="SELECT p.part_number FROM parts p JOIN received r ON r.part_id=p.part_id WHERE r.received_id='$record_id'";
$query=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($query)) {
$message.=$row['part_number'];
}
echo $message;
I have been un-succesfull in many variations to get the pn[] field to populate with results for the ajax request.
Can anybody see something wrong in my code and offer some advice.
Thank you
SOLUTION via smclark89 and Musa
Changed Jquery/Ajax from Above to:
<script>
$(document).ready(function() {
$("[name='ri[]']").on("blur", function() {
var rival = $(this).val();
$.ajax({
url: "/inventory/get-part-number.php",
type: "post",
data: "record=" + rival,
// callback for success
success: function(data, textStatus) {
$("[name='pn[]']").each(function() {
if(!$(this).val() ) {
$(this).val(data); //put value in empty pn[]
}//end if
})//End each
}, //end success else...
//if failsauce throw error
error: function() {
alert('Learn To Code');
} //end error failsauce
}); //ends .ajax function
}); //end blur
}); // ends ready function
</script>
When you're using .on for delegation, the element you bind to must be a container of the element you delegate to. So it should be:
$(document).on("blur", "input name='ri[]'", function() { ... });
You can substitute a more specific element for $(document) -- the only requirement is that this must be a static element that's an ancestor of the dynamic ri[] elements.

Categories