Add Redirect URL link to JS Function - php

How can I add redirect URL link to JS function (example form action to : session.php) in below code.
I've tried with another way code, but it still can't function.
$(document).ready(function() {
$("#submit_butt").click(function() {
var conf = {
frequency: 5000,
spread: 5,
duration: 600
};
/* do your AJAX call and processing here...
....
....
*/
// this is the call we make when the AJAX callback function indicates a login failure
$("#login").vibrate(conf);
// let's also display a notification
if($("#errormsg").text() == "")
$("#loginform").append('<p id="errormsg">Invalid username or password!</p>');
// clear the fields to discourage brute forcing :)
$("#password").val("");
document.forms['login_form'].elements['username'].focus();
});
});

You can try this
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
https://developer.mozilla.org/en-US/docs/DOM/window.location
Ref: How to redirect to another webpage in JavaScript/jQuery?

you can use this..
window.location.href = "http://www.google.com";

you can try
<script>
function name(){
window.location ='abc.php';
}
</script>

you can by breaking into php code inside your javascript
$(document).ready(function()
{
<?php
someFunction();
?>
});
but only if your javascript is in a php file so it can be processed by php. So if your linking to a .js file that needs to be changed to .php

Related

Post form and redirect to PHP

I'm using this jQuery code to submit a dynamic form :
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('inc/siteform.php', $(this).serialize());
});
but this method only sends the data to the PHP file. I want also that it redirects me to there, as an ordinary PHP POST submission.
How can I do it?
Here is the full testing site: http://edge-americas.com/control/main.html
UPDATE:
Using the method JQuery redirects me but it doesn't send the formdata at the same time so I can't use $_POST[] variables:
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('inc/siteform.php', $(this).serialize(),function(response){
window.location = "inc/siteform.php";
});
});
Is there any other way to keep using jquery and solve it?
You can also use window.location.replace() and pass in the URL of where you want to be redirected as a paramter.
Location.replace() for more information on the method.
Javascript works perfectly for this:
window.location.href = "URL";
Or as Andy pointed out if you want users to go back without issues simply drop the .
window.location = "URL";
You can redirect or refresh page after succcess or server answer. For example:
$.ajax({
url:"?show=ajax_request&action=add_offer",
type:"POST",
data: {var_to_send : somevar},
dataType: "json",
success: function(answer){
if ( answer.result == 'success' )
{
location.reload(); // refresh the page
}
else if ( answer.result == 'error' )
{
window.location.href = "http://google.com"; // redirect to another page
}
}
});

Ajax/ Jquery in Zend framework

I’m using Zend framework (php) and I’m trying to submit a from using ajax/jquery.
Here’s the .phtml:
<form id="find">
<input type="text" name="name">
<input type="submit" id="submit" value="Submit">
</form>
Here’s the ajax/jquery part:
$(document).ready(function() {
$("#submit").click(function(){
$.ajax({
type:'POST',
url: "<?php echo SITE_URL;?>Training/test",
data:$('#find').val(),
success: function(response) {
alert (response);
}
});
});
});
Here, “Training” is the controller and “test” is the action inside the controller. The action has just 1 line of code which is echo “hello”. After the user types a number in the box and clicks on “submit”, the control has to go to the controller thus displaying “hello” on success. However, nothing happens when I click on it. Please help me. Thanks in advance.
You didn't name parametr in Ajax call
data:$('#find').val(),
change it to
data:{'param': $('#find').val()},
About Zend it doesn't matter if it's zend or not. You can handle request just providing proper URL. You can access param value in Zend via $this->getParam('param') method.
Also you don't prevent default submit action. Change your function to:
$("#submit").click(function(ev){
ev.preventDefault();
or use in the end of function return false;
I did not test your jQuery. But note you need the instruction event.preventDefault to ensure you haven't the normal form submit action.
The main problem is at your zend Controller because you need a
special response. I suppose you have a controller to perform the request logics. I'll name it AjaxController and I'll name the action ajaxrecuestAction to illustrate how to send a proper response.
<?php
// Filename: yourProject/module/ModuleName/src/Controller/AjaxController.php
namespace ModuleName\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AjaxController extends AbstractActionController {
public function ajaxrecuestAction(){
// This function is called by zend to procces your ayax request
// you must test if it's an xmlHttpRequest
$request = $this->getRequest();
$is_xmlHttpRequest = ($request->isXmlHttpRequest()) ? 1 : 0;
if(!$is_xmlHttpRequest){
// If not you must return a normal page, a message page
// perhaps a forgiven message page, etc. It depends on your site
// logics
}else{
// The solution's KEY
// You must disable the zend's normal output
$viewmodel = new ViewModel();
$viewmodel->setTerminal($is_xmlhttprequest);
// Proccess the input and prepare your output
$output = CallTheLogicsToPrepareIt($request->getContent());
// send your response
$response = $this->getResponse();
$response->setContent($output);
return $response;
}
}
**EDIT: Just noted that, in your HTML, you didn't give an ID attribute to the "find" field. Therefore $('#find').val() will give you an error, something like "cannot find method val() of undefined. Add the id=find tag to your and it should work.
** Other Edit: Sorry about the confusion. Your form has id=find but what you want to send to the server (I believe), is the value of the fields. So give an ID=name to your input then use:
var data = {find: $('#name').val()};
You should start by using your console to see if the event is triggered. Something like:
<script>
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log('Hello');
});
});
</script>
(You do use Fire bug or the Chrome dev tools, right) ? If not, look at the end of this post.
If you can see the Hello in your console, you're on the right path. Then try to set your url in a variable and try to check it in your console:
<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log(url);
});
});
</script>
Then you should see the url in the console, meaning you're still doing good.
If that works, try to set the data and check the output in the same way:
<script>
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
find: $('#find').val()
};
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log(data);
});
});
</script>
Hoping everything still works (you saw the data), then try the actual full code and see if you have an error or something. Also, be sure to include an error function to your ajax call so you will have a response if something went wrong on the server.
<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
find: $('#find').val()
};
$.ajax({
type:'POST',
url: url,
data: data,
success: function(response) {
alert (response);
},
error: function(resp) {
alert(resp.responseText);
}
});
});
});
</script>
Some tools to help you out:
If you are using FireFox, use FireBug for your debugging: https://addons.mozilla.org/fr/firefox/addon/firebug/
If you are using Chrome (my personal favorite), learn a bit more about Chrome Developer Tools: https://developers.google.com/chrome-developer-tools/?hl=fr
If you are using IE, please switch to something else for development purposes, then try it in IE to make sure you code is compatible (most likely won't be but it will be easier to find out why it doesn't work afterwards).
As for the line e.preventDefault......, look into this SO post for more details: https://stackoverflow.com/a/15913969/1483513
Hope this helps !

how to run java script file after invoke with ajax and append to the output

My problem with the javascript file run through the AJAX call is
for example :
index.php
$(function(){
$(".btn-ajax").click(function(){
$.getJSON('ajax.php',function(data){
jsInc(data['js'][0]['src']);
$("#response").html(data['html']);
});
});
function jsInc($src){
var head = document.getElementsByTagName("head")[0];
var script=document.createElement("script");
script.type='text/javascript';
script.src = $src;
head.appendChild(script);
}
ajax.php
$arr['js'][] = array('src'=>'js.js');
$arr['html'] = '<input type="button" class="btn" value="show message"/>';
echo json_encode($arr);
js.js
$(function(){
$(".btn").on('click',function(){
alert("test !");
});
});
but when execute ajax request and append input button to the index.php file this button click event not worked!
please help me
Thanks
You want to get script via AJAX right? You can use $.getScript:
$.getScript("script.js");
Load a JavaScript file from the server using a GET HTTP request, then execute it.
I think what's happeneing is your first loading the JS which binds the click listener and then loading the Button. SO the listener doesnt get bound
Try reversing the order like:
$("#response").html(data['html']);
jsInc(data['js'][0]['src']);
Try rebinding the click function after the Ajax call (success):
$.ajax({...
success: function(data) {
$(".btn").click(clickFunction);
}
});
$(".btn").on('click', clickFunction);
function clickFunction() {
alert("test !");
}
You need to change your function in js.js to be a delegate function.
$(function(){
$('body').on('click','.btn',function(){
alert("test !");
});
});
When you do it this way. The .btn element doesn't even need to be present before the script is run. It attaches the event to the body tag prior to checking if the .btn element exists.

php, how to call a javascript function?

i am trying to use gigya auth properties to login users on my website. They have a function that needs to be called after i authenticate the credentials as seen in this illustration
I have a form and when i submit the form i send it to login.php where i authenticate my users. My question is how do i call socialize.notifyLogin?.
this is the javascript:
<script type="text/javascript"> var conf = { APIKey:'2_9E9r_ojXEqzZJqKk7mRqvs81LtiSvUmBcm' }; </script>
<script type="text/javascript">
var secret = 'eIqtclW2CxC6qvmT55MvOxZ5Rm7V5JhBV/gioJLKIxM=';
var yourSiteUid= '<?php echo $talentnum;?>'; // siteUID should be retrieved from your user management system
function your_b64_hmac_sha1(secret, datePlusSite) {
var b64Sig = ''; // Place your implementation here ...
return b64Sig;
}
function printResponse(response) {
if ( response.errorCode == 0 ) {
alert('After notifyLogin');
}
}
var dateStr = getCurrentTime();
var datePlusSite = dateStr + "_" + yourSiteUid;
var yourSig = your_b64_hmac_sha1(secret, datePlusSite);
var params={
siteUID:yourSiteUid,
timestamp:dateStr,
signature:yourSig,
callback:printResponse
};
gigya.services.socialize.notifyLogin(conf,params);
</script>
to be more clear i set the $talentnum; inside my login.php. so i have the form i send it ti the login.php and a redirect page... Where the call to socialize.notifyLogin will be?
thanks,
any idea helps
You have two options:
If you call login.php as the target of an HTML form, you should redirect the user to a new HTML page upon successful login. This new HTML page should contain the socialize.notifyLogin call.
If you call login.php via an AJAX request, you should call socialize.notifyLogin in the "success" callback of the AJAX request.
In no case, however, will you be able to execute the Javascript function directly from your PHP script. PHP executes on the server before the Javascript is sent to the user as output with your HTML document, and therefore cannot execute Javascript functions directly.
PHP is executed before the page loads, therefore you cannot call a JavaScript function from PHP.

JQuery AJAX post not working if more than 1 function is defined

I have a JQUERY AJAX post function that will work if there is one function, but if I try and include another function in addition, the second function does not post through to the .PHP script. I am a beginner in JQUERY but have tried every variation, but it will process the first function, but if I add any other functions, will not process those.
<script language="javascript" type="text/javascript">
function toggle[My CSS code](x) {
if ($('#'+x).is(":hidden")) {
$('#'+x).slideDown(400);
} else {
$('#'+x).hide();
}
$('.[My CSS Code]').hide();
}
function add(a,b){
var URL="process.php";
$("#add").text("Processing").show();
$.post(URL,{request:"request",mem1:a,mem2:b,},function(data){
$("#add").html(data).show().fadeOut(12000);
});
}
/////This is where the code stops working and the .php script doesnt work//////////
function accept (x) {
var URL="process.php";
$.post(URL,{ request: "accept", reqID: x, } ,function(data) {
$("#req"+requestID).html('<font color="#000">Accepted</font>').show();
});
}
function deny (x) {
var URL="process.php";
$.post(URL,{ request: "deny", reqID: x, } ,function(data) {
$("#req"+x).html('denied').show();
});
}
</script>
So it will process the add function but not the accept nor deny function via the URL posted in the add. Any ideas would be greatly appreciated. Thanks!
You are only defining the URL in the first function, and it's var'ed so the other functions don't have access and have an undefined url
Depending on which browser you are using the trailing comma in your ajax options object may be causing a problem:
// this little guy
// |
// v
$.post(URL,{request:"request",mem1:a,mem2:b,},function(data){
I have known IE to choke on trailing commas in object or array definitions, though FF and Chrome usually seem to be able to handle it

Categories