Wordpress search results in modal - php

I am complete php/js newbie and i got stuck on something that i cant figure out.
I have page at www.test.com/page with a search form that calls www.test.com/results like this:
<form method="post" action="https://www.test.com/results">
<input type="text" placeholder="Enter URL:" required="">
<button>Search</button>
</form>
Form gets URL that the user typed in, passes it to /results, the line ($url = $_POST['url'];) is where it is analyzed and results are displayed.
But, i would want the search results to open in (bootstrap) modal instead of new page. I know this can be done with AJAX but i am complete newbie and am looking for most dirty simple solution that would make it work.
Again, sorry if this is too "newbie" type of question, i am still learning.

Yes, you can use jQuery and AJAX to control the form submit. So something akin to the code example below should do the trick:
$('#myForm').on('submit', function(event) {
$.post('https://www.test.com/results', { URL: "some_url.com" }, function(data) {
// Render the results onto your modal anyway you want with data
// retrieved from server here
$("#my-modal-object").html(data);
}).error(function() {
// Handle the event when the call to "/results" fails
alert("Yikes! Call to /results failed!");
});
// Prevents default browser behaviour which submits the form
// then routes to another page, if specified
event.preventDefault();
});
Short explanation:
We attached a "submit" event listener to your form object and performed a POST AJAX request to your server endpoint /results. Server passes back the processed search results into the callback function of $.post and renders it onto your modal object. You may also change the 2nd argument of $.post, i.e. { URL: "some_url.com" } to whatever data object you want to pass to your server.
This should help you get started with rendering your search results onto your modal element instead of navigating to a new page.

Related

Jquery Mobile: Show new data without refresh after adding it to DB

I'm displaying data from DB like this:
<?php foreach ($r as $k => $v):?>
<div data-role="collapsible" data-mini="true" class="collapsible">
Name: <?=$v['name']?>
</div>
<?php endforeach; ?>
Now when I add new data to DB and the form is submitted, my script redirects back to this page. How do I show the new data immediately without manually refreshing the browser? I usually don't have this issue if I'm not using Jquery Mobile.
You could send the form with jquery ajax
$('form[name="myform"]').submit(function(evt){
evt.preventDefault();
$.post('/my_form_handler.php', $(this).serialize())
.done(function(data){
//Populate dom elements here with new data
}).fail(function(data){
//Handle failed ajax post.
});
});
And then on successful post change the content of the dom-elements.
Not 100% sure i got the right syntax for it but i think it should give you a general idea on how to do it.
The problem here is that the data is hard coded into the page's HTML. After your form submission it's jQueryMobile that's changing the page/view, and no refresh of the page takes place so you're still seeing the same data.
You should refactor to create the loop with JSON data (loaded via AJAX). If the data is cached in a local variable, you can either add to it with the form's data, or make a fresh AJAX call to the server (recommended if you need sorting or filtering).
After reloading the data, the rendering code can be called, showing the new list.
it is easy.
you can send the request to the server using ajax.
and on the server side, you have to make the function to return the data added.
the ajax function will get the success or fail function.
the success function will run if it works.
on the success function , you have to add the content using javascript jquery with the returned data.
Thanks

Button that runs a php script without changing current page

I have a webpage that generates a table from mysql. I have a button at the beginning of each row. I would like it so if the user decides to press on the button, the contents of that individual row are written to a new table in MySQL.
Currently I am thinking of just having the button be an href to another php script that connects to mysql and inserts the row into a table; however, I think that will redirect my current page.
I would like the button to run the script, without redirecting my current page. That way, the user can continue analyzing the table without having the page have to reload every time.
This is what my current table looks like. This is just a snippet, and the table can be very large (hundreds of rows)
In order to do this client side, there are a couple of ways I can think of off hand to do this:
Javascript
You can include a Javascript library (like the ever popular JQuery library), or code it yourself, but you could implement this as an XMLHTTPRequest, issued from a click handler on the button. Using a library is going to be the easiest way.
An iframe
Create a hidden iframe:
<iframe style="display:none;" name="target"></iframe>
Then just set the target of your tag to be the iframe:
...
Whenever someone clicks on the link, the page will be loaded in the hidden iframe. The user won't see a thing change, but your PHP script will be processed.
Of the two options, I'd recommend the Javascript library unless you can't do that for some reason.
You need to insert a record into mysql table upon click of button without reloading the page.
For accomplishing the above task you need to use AJAX which will send http request to server in background using xmlhttprequest object and thereby updating web page without reloading the web page.
So you will have to create a function in javascript which will send http request to server using xmlhttprequest object and also you need to define server side handler for processing http request sent using ajax.
For implementation details of ajax with php ,please refer the example mentioned in below link
http://www.w3schools.com/php/php_ajax_php.asp
It's easy to do using jQuery:
<script>
$(function(){
$('#your_button_dom_id').click(function(){
$.ajax({
url: 'your_php_script_url',
type: 'POST', // GET or POST
data: 'param1=value1&param2=value2', // will be in $_POST on PHP side
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert("Response is: " + data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error!");
}
});
});
});
</script>
You can read more about AJAX in jQuery here: http://api.jquery.com/jQuery.ajax/
You can use another input tag after your submit button with hidden type.
<input class="ButtonSubmit" type="Submit" name="Submit" id="Submit" value="Submit"/>
</p>
<input type="hidden" name="submitted" id="submitted" value="true" />
after that use in top of your code this
if (isset($_POST['submitted'])) {
// your code is here
}
it's work for me. you can use it in wordpress template as well

Using AJAX to POST data to PHP database, then refresh

Currently I have a button:
<ul>
<li><button onclick="display('1')">1</button></li>
<li><button onclick="display('2')">2</button></li>
<li><button onclick="display('3')">3</button></li>
</ul>
That when pressed, calls a javascript function, and displays PHP based on which button is pressed using AJAX. I figured this out all on my own. The AJAX gets a PHP file with a postgres query that outputs a table of data to a div.
Now I want to be able to add, via form, new data and have it refresh (without reloading the page, yannknow?). I've tried a couple of things, and have hit roadblocks every time.
My initial idea was to have the form submit the data using a javascript function and AJAX, then call my "display()" function after the query to reload the content. I just can't figure it out using GoogleFu.
Based on my current idea, I'd like help with the following:
How do I pass the form data to a javascript function.
How do I use POST to pass that data to PHP using AJAX?
I'm super new to javascript and AJAX. I've looked into jquery as it seems like that's the way to go, but I can't figure it out. If there's a better way to do this, I'm open to suggestions. Please forgive any misuse of nomenclature.
EDIT: Once I solve this problem..., I'll have all the tools needed to finish the project preliminarily.
This example is copied directly from the jQuery API docs for $.post. When in doubt, first place to look is in the API
http://api.jquery.com/jQuery.post/
Example: send form data using ajax requests
$.post("test.php", $("#testform").serialize(), function(data){
/* success- do something with returned data*/
});
Now extend the concept further and wrap the post in a submit handler for the form
$("#testform").submit(function(){
/* code from above, changing form selector to "this" */
$.post("test.php", $(this).serialize(), function(data){
/* success- do something with returned data*/
});
/* prevent browser default submit*/
return false;
})
Refer to jQuery.post method. It does what you want (sends AJAX request with POST data).
To grab values from inputs, use val() method for nodes that have value (textarea, input, .. )

Adding AJAX to a working PHP form

I have a working PHP registration form that goes through $_POST[] requests to check user inputs.
Username length (3-20)
Username availability
Username /^[A-Za-z0-9_]+$/
etc.
Rather than have it take you to a whole new page to display errors, I want a live request to call for the errors from register.php so they will appear in a div on the registration.
<div id="errors">" . $usernameErrors . "</div>
I've been trying to read up on AJAX but have noticed most codes involve utilizing $_GET[].
What will I have to do to get my current forms integrated with AJAX?
My Current Basic Registration Form Logic:
<form method="post" action="register.php">
<input type="text" name="username" id="username" required />
$usernameErrors
</form>
And register.php contains all of the checks already.
If you're using jQuery, it's pretty simple.
<script type='text/javascript'>
$.post('/register.php',
{username: $('#username').val()
// insert values of other fields here
},
function(response) {
// update your div with errors
$('#errors').html(response);
})
</script>
You should invoke this code, for example, when user changes username in registration form. It will happen in background and update page asynchronously.
Your register.php script should, in this case, emit only errors, not the whole page, or you will see unexpected results. :-)
In order to simplify ajax, you can use jQuery (a very powerful JS lib).
Add jquery***.js to your project and refer it on your page:
<< script type="text/javascript" src="#js/jquery-ui-1.8.16.custom.min.js" />
Then, you create the javascript function that will make the ajax call.
On the ajax call, you specify the php file to call and the function to handle the return of php(callback). On this callback function, you add the error message to body.
function verifyForm(){
$.ajax({
type: "POST",
url: "register.php",
data: "username=NAME_GOT_FROM_FORM_&location=Boston"
}).done(function( returned ) { //the callback
$('#errors').html(returned); // add the string returned to div id=errors
});
}
So, the crux of the problem as you're asking it seems to be that you're (correctly) using a POST request on your register form, but your tutorials all want to use GET. Here's a discussion about the difference between the two methods:
http://thinkvitamin.com/code/the-definitive-guide-to-get-vs-post/
If you're actually registering the user with AJAX (rather than just validating) you should be submitting the AJAX request as a POST. If you're using jQuery, the answer has already been given. If you're not using jQuery, then look for the XMLHttpRequest object in your tutorial, and where its "open" method is called (reference here: http://www.w3.org/TR/XMLHttpRequest/). The first parameter of that function is a request method--change it to "post" rather than "get", and the request will be treated like a POST, which register.php expects.
That being said, it sounds like you just want AJAX to validate the form. In that case, GET is the correct verb to use--all you want to do with AJAX is check data against the database, not actually make a change to data. I would suggest that you actually write a new PHP script like validate_registration.php that will perform only the validation logic in register.php, and then return a JSON array of errors (which would be empty if no errors occurred). You can activate/deactivate your form submit button based on that return value, and let the user submit the form just like your old workflow if everything is okay.
The tl;dr here is that you should read up on what makes $_GET and $_POST different, and then write an AJAX-specific validation script so that you're separating the data-retrieval part of your process from the data-insertion part. Once you understand the difference, the rest should follow.

Website design prevents data being posted to server

I have a big problem with my website.
I have made it in a way that seems to stop be from doing anything.
I have a number of containers, the main part of the page has three small containers all on top of each other and then a bigger container next to them that has the main content. The content that is shown in this main container is pulled from other pages so I don't have to refresh the whole page ever time a link is pressed. So I have one main page (the index) and a bunch of other content filled pages.
Now, if a page were to need to post data to the server to process it and then confirm with the user, this can't be done with normal PHP like I'm used to because the whole page is refreshed and it goes back to the default.
So I thought, I know Ajax can do this. I can post data to the server, process it and then change something on that page without loading anything.....
But I was wrong, it seems that it still wants to refresh the whole page meaning I lose my data. Also with the Ajax I am using "post" not "get" but for some reason it's putting the data into the address bar.
Is there a way I can keep my current structure and be able to do this, or am I doomed?
Any help, tips, code or advice would be MORE than welcome and thank you for the time and help.
Oh yeah, if I view the content outside of the index page the script runs just fine, it's only when the index pulls it from another page.
Ajax:
unction pass()
{
// Real Browsers (chrome)
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var oldPass = document.getElementById('oldPass').value;
var newPass = document.getElementById('newPass').value;
var newPassCheck = document.getElementById('newPassCheck').value;
xhr.open("POST","changeSettings.php");
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
var obj = {oldPass: oldPass, newPass: newPass, newPassCheck: newPassCheck};
xhr.send("data=" + JSON.stringify(obj));
xhr.onreadystatechange=function()
{
if (xhr.readyState==4)
{
//grade = xhr.responseText;
document.getElementById("myDiv").innerHTML = xhr.responseText;
//document.write.grade;
//alert ("Nice essay. Your grade is " + grade);
}
}
return false;
}
Here is the original page:
<div id="content">
<form>
<h1>This page is still under construction please do not attempt to use it!</h1>
<p>
Old Password: <input type="password" name="oldPass" id="oldPass"><br />
new Password: <input type="password" name="newPass" id="newPass"><br />
Retype Password: <input type="password" name="newPassCheck" id="newPassCheck"><br />
<input type="submit" name="submit" value="Submit" onClick="return pass();">
</p>
</form>
<div id="myDiv" name="myDiv"> </div>
</div>
Just because you're supplying "POST not GET" in the form doesn't mean ajax will handle it this way.
What needs to be actually done is attach to the submit event of the form, then let AJAX handle it the rest of the way. On a confirmed submission (or even a failure) you can update content (or show errors).
To keep it simple with jQuery...
<div id="content-container">
<form method="post" action="/some/submission/page.php">
<!-- flag to let the landing page know it's an ajax request
this is optional, but IMHO it makes for a more seamless
experience -->
<input type="hidden" name="ajax" value="true" />
<!-- controls go here -->
</form>
</div>
So there's your form. Now, you need to attach to the submit event. Again, I use jQuery for simplicity, but feel free to use any method. I also am creating a very generic controller here so you could presumably use it for every form found on the page, but that's up to you. (And, because we still decorate the <form> an absence of javascript will still proceed, but when it IS there, it will use the nice ajax look and feel)
// use .live to catch current and future <form>s
$('form').live('submit',function(){
var target = $(this).prop('action'),
method = $(this).prop('method'),
data = $(this).serialize();
// send the ajax request
$.ajax({
url: target,
type: method,
data: data,
success: function(data){
//proceed with how you want to handle the returned data
}
});
});
The above will take a normal form found on the page and make it submit via AJAX. You may also want to bind to $.ajaxError so you can handle any failures.
Also, depending on the content you return from the AJAX call, you can either pass the entire response back to the container ($('#content-container').html(data); in the success call), or if it's JSON or plain text, display other data.
Oh, and using my example, you may want to have something like the following in your posted page:
<?php
$ajax_call = isset($_POST['ajax']);
if (!$ajax_call){
// not an ajax call, go ahead with your theme and display headers
}
// output content as usual
if (!$ajax_call){
// again, not ajax, so dump footers too
}
(That way when it's AJAX, only the info in your container is returned, otherwise display the page as usual because they probably don't support AJAX/JavaScript).
You need to put up the page or post a code example in order to get answers to this question.
If I were to take a guess, it would be that you are not preventing submission of the form, so it's firing off the ajax request like you asked, but also submitting the form. In order to prevent it, you need to select the submit button and have it return false. Here's a quick example with jquery of how you would do this
$('input[type=submit]').click(function(){
$.ajax({ ... request here ... });
return false
});
or you can also catch the click event and prevent default, as such
$('input[type=submit]').click(function(event){
event.preventDefault();
});
Since I can't see any of your code, this is not guaranteed to be right. If you post the code, I can revise this. In the meantime, hopefully I guessed it!

Categories