Link to a page and trigger ajax via the same button - javascript

I'm trying to make a div button which triggers ajax and links to a page which the ajax is posting data to. I have the ajax working on click, but can't seem to get the link to work at all with it, all the ways I've tried to get the link working do nothing.
I have a div button:
<div class="cman shadow1" id="search_button" value="carSearch"/>
Start Search
</div>
Which triggers:
function carSearch()
{
$.ajax({
type: "POST",
url: 'searchpost.php',
data:
{
mpg : $('.mpg').val()
},
success: function(data)
{
alert("success! "+$('.mpg').val());
}
});
}
Edit:
Feel I should mention that the page I wish to link to is atm:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('cdb', $conn);
if(isset($_POST['mpg']))
{
$mpg = (int)($_POST["mpg"]);
header("Location: home.php");
exit;
}
?>
I wish to use this to gather all of the search fields the user enters to then load the search results page. The above code for it is just for testing right now.
I mention this as user #Doge suggested doing document.location.href = "searchpost.php" in the success handler of the ajax, this did cause the page to change but the page didn't run the isset and the redirect, so the js variable wasn't posted, or it was but this instance of the page didn't get it.
The isset and redirect do work as using the XHR Network tab on my page the page it is to redirect to appears.

If you must do this via js then create a hidden form, populate it and submit it:
html:
<form method="post" id="hiddenform" action="searchpost.php">
<input type="hidden" name="mpg" id="mpg"/>
</form>
js:
function carSearch()
{
$('#mpg').val(yourjsvariable);
$('#hiddenform').submit();
}

Related

I want to show data which got from a php file to all tab pages by using ‘storage event’

I want that when I click on logout, ck() function will be fired and there is an ajax method. By ajax method I have send some data to object.php file. After success all process I will get I got It string. Now I want that when this data I will get, 'storage' event will execute and I got It will show all index.php tab pages at a times without any refresh or click again logout. I am very very sorry for my poor English. It is my first question.
index.php:
<script>
function ck(){
var ok="thx";
$.ajax({
type:"GET",
data:{mt:ok},
url:"object.php",
success:function(html){
if(html!=""){
localStorage.setItem('store-it', html);
window.addEventListener('storage', function (event){
if(event.key=='store-it'){
$(".show").text(event.newValue);
}
})
}
},
});
}
</script>
<p onclick="ck()">logout</p>
<p class="show"></p>
object.php
<?php
if(isset($_GET['mt']) && $_GET['mt']=="thx"){
echo "I got It";
}
?>

Displaying the data (retrieved from an API call) after user submit the form without refreshing the page

I am creating a form that will get a search query request from the user on submit and will display the results after making an API call I would like to show the results without refreshing the page using AJAX. I am using PHP to connect to the API.
This is what I have so far but I can't get the results displayed. Regardless of the success of the API connection, I cant even get the entry of the form displayed in the same page without refreshing the page so I am not sure if I am doing it right. what am I missing? What else do I have to consider in order to make this work? Could someone please guide me to the right direction?
$(document).ready(function() {
$('#search-form').on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
console.log(data);
$('#results').html(data);
}
});
});
});
<form action='result.php' method='post' id='search-form'>
<input type='search' name='search'>
<input type='submit' value='submit'>
</form>
<div id='results'>Result comes here..</div>
// result.php
if(isset($_POST['search'])) {
$query = urlencode( $_POST[ "search"]);
$request = 'http://some.api/?query=' . $query;
$response=file_get_contents($request);
$result=json_decode($response);
echo ($result);
} else {
echo ("No search query has received");
}
.serialize() does not serialize submit buttons. Submit buttons are only sent in requests when they are pressed/trigger the submit action on the form they are in, .serialize() has no way of knowing any of that.
You'll just have to add that information manually or not check for it at all.
...
data: $(this).serialize()='&submit=ajax',
...
or
if(!empty($_POST['search'])) {
...
I suggest in this case, you just create a hidden field with the value like this:
<input type="hidden" name="search" value="submitted" />
And that's going to be there on a submit.

Can I set the response of a form submission to the content of a dialog?

I had a question about JavaScript Popup here JavaScript popup result from a form
Now I was wondering, since no one could really help me out here, not even the internet!
is it possible to use JavaScript Dialog to show the result of a form with action "..php"
I could not find it.
situation:
imagine, we got 2 php files, index.php and test.php
is it possible to make a form with a submit button on index.php, with action="test.php"
but that the file test.php will get loaded in a JavaScript Dialog.
something like this: http://jqueryui.com/dialog/#animated
echo "<form action='getlist.php' method='post'>
<input type='text' name='exte' class='exte' value=".$value['ext'].">
<input type='submit' name='aanvragen' id='aanvragen' value='aanvragen'></form>";
echo "</td>";
This is what I have, now I want the getlist.php get loaded in a popup or Dialog.
I hope that I've been clear about my question, I am trying to get this working for hours now and quite lost my mind.
Sure it is, shouldn't even be very hard, just submit the form with ajax and show the result in a dialog
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize()
}).done(function(data) {
$('#dialog').html(data).dialog(settings);
});
});

Temporarily changing HTML structure on the same page in PHP when submit button is clicked?

I have PHP page that have submit button to another URL.
I want to reload the current page after the submit button clicked, and add div to the HTML.
My page url is: /foo.php, and in the HTML I have:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
As you can see the form sends request to /bar page.
I want to reload the /foo.php (the current page), and change the HTML to:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
<div>Thank you!</div>
My problem is how can I know that the user click on the button and the refresh was because the click, and not because just navigating.
Another thing, if it possible, I want that the new div will disappear if the user refresh the page again.
Why don't you just append the div in the success callback of the get function? You wouldn't have to reload the page.
<div id="btn_area">
<button onclick="$.get('/bar', function() { $('#btn_area').append($('<div>').html('Thank You');)})">Submit</button>
</div>
By the way, i hardly recommend to separate the javascript from the html and not put it directli in the DOM.
Another Method would be, to fire an additional form with a hidden parameter to the same side. After that, you check on the serverside the hidden parameter and display the div.
A third method is, to set a cookie in the Callback, reload the side, check the cookie, display the div and remove the cookie again.
In my opinion, the first mentioned option (add the div directly in the callback without reloading) would be by far the 'prettiest', but of course i don't know what else is going on on your site
Alternatively, you could simulate a flash session (one time use session) if you opt to do this in PHP. Consider this example:
foo.php
<?php session_start(); ?>
<form method="POST" action="bar.php">
<button type="submit" name="thank_you">Submit</button>
</form>
<?php if(isset($_SESSION['thank_you'])): ?>
<?php unset($_SESSION['thank_you']); ?>
<h1>Thank You!</h1>
<?php endif; ?>
bar.php
<?php
session_start();
if(isset($_POST['thank_you'])) {
$_SESSION['thank_you'] = true;
// processes
header('Location: foo.php');
}
?>
Demo
You can handle that in js side. Just make your request, and in callback, you can manipulate dom. You can see below;
<button>Submit</button>
$("button").on("click", function() {
var $button = $(this);
$.get("/echo/html", function() {
$button.after("<div>Thank you!</div>");
});
});

Delays/inconsistencies in AJAX refresh

I've been working on a web app that allows users to submit content and have that content, and today I've been seeing some unexpected results without making any significant changes.
The basic functionality of the app is that the user submits some POST data from a form on a web page index.php, whereupon a PHP script submit.php is run to add the data to a table in a database. Meanwhile, a Jquery function on index.php is refreshing the contents of a div with rows selected from the table by means of a script load.php, and the function is called once per second.
The problem is that today, suddenly, I'm seeing long (10-20 minute) delays between when the data is added to the table and when it shows up in the Jquery-refreshed div. Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.
I've checked the MySQL database before and after submit.php is called and I've verified that the data is being added instantaneously once it's submitted, so the problem has something to do with how the load.php script is called from Jquery.
This just started today. Strangely, I've been seeing this same behavior with another AJAX app that I built earlier to test the same I/O mechanism, and I haven't touched that app's code in over a week. My system administrator says there haven't been any changes to the server that would account for this.
I've posted all the code to provide all necessary information, but I think the problem is either in load.php or the javascript updateMyContent() in index.php.
index.php
<script language="JavaScript">
setInterval("updateMyContent();",1000);
$(function(){
updateMyContent=function(){
$('#refreshData').load("./module/load.php").fadeIn("slow");
}
});
</script>
<script language="JavaScript">
$(document).ready(function(){
$('#submitForm').on('submit',function(e){
$.ajax({
url:'./module/submit.php',
data:$('#submitForm').serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
$('#textID').val('');
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
</script>
<div style="float: right;
top: 0;
" id="submitDiv">
<form id="submitForm" action="" method="post">
<textarea id="textID" type="text" name="content" rows=5></textarea>
<input type="submit" value="send" name="submit"/>
</form>
<br>
<span id="error" style="display: none; color:#F00">error</span>
<span id="success" style="display:none; color:#0C0">success</span>
</div>
<div style="float: center;" id="refreshData"></div>
submit.php
<?php
if(isset($_POST['content']))
{
$content=$_POST['content'];
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$insertSQL="insert into submission (content) values (?)";
$stmt=$db->prepare($insertSQL);
$stmt->execute(array($content));
}
else
{
echo "FAIL!";
}
?>
load.php
<?php
try
{
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$PDOsql="select * from submission order by id desc";
$stmt=$db->query($PDOsql);
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $resultRow)
{
printf("%s<br>",$resultRow["ID"]);
printf("%s<br>",htmlspecialchars($resultRow["content"]));
$stmt->closeCursor();
}
}
catch(PDOException $ex)
{
echo "an error occurred! ".$ex->getMessage();
}
?>
The issue with it taking so long to return the Ajax response is probably that the table submissions has grown. Rather than each second loading all the submissions, append only new submissions to the div. I.e. keep track of the last id received and use this in the query so the where clause is limited.
Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.
Ajax response can be cached by the browser just like anything else. To prevent that, you can:
Put no-cache headers in the page that processes the request to prevent browser caching of the Ajax responses. IE is particularly stubborn and will require the most forceful headers.
Add a parameter to your Ajax request that is a random number, to make every request unique.
Tell JQuery to prevent caching (it just does #2 for you). Use $.ajaxSetup ({ cache: false }); or add the cache: false, attribute to each call to $.ajax

Categories