Use jQuery to post data to php file - php

I am making a search engine.I want to post the data from jquery to php.
Here is my code of jQuery
<script>
$(document).keypress(function(e) {
if(e.which == 13 && $('#textfield').val()) {
$.post("search_result.php",
{
wording: $('#textfield').val()
}, function() {
window.location = "search_result.php";
}
);
}
});
</script>
Here is my code of php to get the wording:
<?php include('../include/common_top.php');
$key_word = $_POST["wording"];
var_dump($key_word);
?>
But what I get is a null value.Please help.

You shouldn't redirect to the PHP script. That runs it a second time, but this time with no POST parameters.
The output of the PHP script from the AJAX request will be the argument to the callback function, you can display it from there.
$(document).keypress(function(e) {
if(e.which == 13 && $('#textfield').val()) {
$.post("search_result.php",
{
wording: $('#textfield').val()
}, function(result) {
$("#somediv").text(result);
}
);
}
})

Related

Redirect to another page if DropzoneJS image upload is success with php variable

I am using dropzoneJS in my form. The form also record user input. Below code shows what I am doing in simple. Everything is working fine but php variable is not getting its value. It is somewhat like this
if (!empty($_FILES)) {
$imgID = submitData()//This functions upload image and write image url in database and then return ID of the affected row
}
When submit button in form is clicked, redirection is happening but $imgID is not getting its value
Here is the Javascript
Dropzone.options.myAwesomeDropzone = {
autoProcessQueue: false,
etc.. etc ..
init: function() {
var myDropzone = this;
$("#submit-all").click(function (e) {
e.preventDefault();
e.stopPropagation();
if (myDropzone.files.length) {
myDropzone.processQueue(); // upload files and submit the form
} else {
$('#my-awesome-dropzone').submit(); // submit the form
}
});
// Refresh page when all images are uploaded
myDropzone.on("complete", function (file) {
if (myDropzone.getUploadingFiles().length === 0 && myDropzone.getQueuedFiles().length === 0) {
var idvar = '<?php $imgID; ?>';
window.location.replace("/preview.php?id="+ idvar);
}
});
}
}
Suggest me where I am doing wrong. Is there any alternative available.
You can send the id back to the browser as response and take it with dropzone on success event like this.
php: (If this file is used to handle other requests a possible structure can be like this)
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && !empty($_FILES))
{
$imgID = submitData();
echo $imgID;
}
else
{
// The rest of your php file shoul go in here.
}
js:
Dropzone.options.myAwesomeDropzone = {
// .........
init: function() {
// ........
// On success refresh
this.on("success", function (file) {
var idvar = $.trim(file.xhr.response);
window.location.replace("/preview.php?id=" + idvar);
}
}
}

Two functions (Javascript and AJAX) dont work together

Im trying to send some data to the server through AJAX with the value i get from a JS variable.
Code:
<script type="text/javascript">
var url;
function aplicarFoto(_src) {
url = _src;
var fotosel = document.getElementById("fotosel");
fotosel.src = 'fotos/'+_src;
}
function guardarCambios() {
$.post("guardarCambios.php",
{url: url},
function(response) {
alert(response);
if (response == "NoUsuario") {
window.location = "../login.php";
} else {
alert("correcto");
}
}
alert(url);
}
</script>
The idea is update the user picture with the url i get from aplicarFoto(_src) with the variable url .
The first function (aplicarFoto(_src)) alone works correctly, but when i put the another function (guardarCambios()), the first function doesnt work, therefore the second neither! I dont know why, but it just happens when using ajax functions because i did a test with an alert(url) (sunrrounding the rest of code with comments) in the second function and both work correctly!
Some guess? Thank you!
Your script alone has syntax errors.
<script type="text/javascript">
var url;
function aplicarFoto(_src) {
url = _src;
var fotosel = document.getElementById("fotosel");
fotosel.src = 'fotos/' + _src;
}
function guardarCambios() {
$.post("guardarCambios.php", {
url: url
}, function (response) {
alert(response);
if (response == "NoUsuario") {
window.location = "../login.php";
} else {
alert("correcto");
}
alert(url);
}
);
}
</script>

Jquery POST fetching data on keyup

What I want to do
When writing in the text field, I want the <div class="result"> to be filled with what PHP is echoing.
But it doesn't work!
Jquery
$(document).ready(function() {
var search = $("#search");
if (search.val() !== '') {
search.keyup(function() {
$.post("index.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
});
}
});
php
if (isset($_POST['search'])) {
echo 'hello';
}
html
<input type="text" name="search" id="search"/>
<br />
<div class="result"></div>
Problem
When filling the input, nothing happens, and it meant to POST the entered data on keyup (When entering a new character/or deleting.
What is stopping it from working? I am new to jQuery .
Thanks.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
This is wrong.
if (search.val() !== '') {
The above line should be,
if (search.val() != '') {
EDIT:
Then wrap the if condition inside the keyup function.
$(document).ready(function() {
var search = $("#search");
search.keyup(function() {
if (search.val() != '') {
$.post("getInputs.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
}
});
});
When I run into situations like this, I just start breaking the problem in half to see where its failing. Here are a couple things I would try.
First, in your jQuery, add some output to the console:
if (search.val() !== '') {
console.log("I am not empty so I should go to index.php");
search.keyup(function() {
$.post("index.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
});
}
else
{
console.log("search val was empty");
}
Of course you could always check the browsers network profiler to see if it made a POST to that resource. This will tell you if the problem is in your search.val test.
Then, if you want to debug the PHP side, you could remove the isset test and just always return "hello". That will tell you if its an issue with your POST variables or checks.
Finally, you could output the data result to be sure something is coming back at all. This will remove any issues with $(".result").html() being the problem:
$.post("index.php", { search : search.val()}, function(data) {
console.log(data);
$(".result").html(data);
});
If none of these work, maybe you could just switch around the way you bind to keyup in the first place:
$(document).ready(function() {
$("#search").keyup(function() {
if ($(this).val() !== '') {
$.post("index.php", { search : $(this).val()}, function(data) {
$(".result").html(data);
});
});
}
});
$(document).ready(function() {
var search = $("#search");
});
This fire only at document ready but not on keyup, means in var $("#search").val() will be blank.
Change your code to capture inpute value on every key-up stroke.
$(document).ready(function() {
search.keyup(function() {
var value = $("#search").val();
if(value!="")
{
$.post("index.php", { search : value}, function(data) {
$(".result").html(data);
});
}
});
});
Your logic is incorrect. You are only setting the keyup event handler if your #search has text in it. Unfortunately when that script runs on document ready, there is NO value in #search so your keyup handler never gets set, which is why it never fires.
I rewrote some of your logic and was able to get it to work. One being the way your checking to ensure you have a value. Instead of string comparing I am checking the length. Also, instead of binding the event to the field, I bind the event on the document and target the field. Try it:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<input type="text" name="search" id="search"/>
<br />
<div class="result"></div>
<script>
$(document).ready(function() {
$(document).on('keyup', 'input#search', function() {
if($(this).val().length > 0) {
$.post('index.php', {"search":$(this).val()}, function(data) {
$('div.result').html(data);
});
}
});
});
</script>
// when the html is loaded
$(document).ready(function() {
// find an element with the id 'search'
var search = $("#search");
// if this element's value is NOT an empty string -- oh look, it is!
if (search.val() !== '') {
// well, going to skip all this here then
search.keyup(function() { // don't care
$.post("index.php", { search : search.val()}, function(data) { // don't care
$(".result").html(data); // don't care
});
});
}
// YAAAAY! All done!
});
Actually nothing is wrong in your code. I have tried your code itself. Only issue was that you have called keyup function conditionally. Your Javascript code should be like below:
$(document).ready(function() {
var search = $("#search");
search.keyup(function() {
if (search.val() != '') {
$.post("index.php", { search : search.val()}, function(data) {
$(".result").html(data);
});
}
});
});
Here, condition should be inside the keyup function.

jquery dynamic content on ie

I have problem with the site I'm developing. The dynamically loaded div (ajax) is empty in IE9 and works poorly on firefox (php doesn't compile) and I can read the source of my php file in the div.
I've tried a lot of solutions like changing from GET to POST or adding a unique id to the url or making an async request but the content is absolutely empty. Any ideas? thanks
function pageload(hash) {
if(hash == '' || hash == null)
{
document.location.hash = "#php"; // home page
}
if(hash)
{
getPage();
}
}
function getUniqueTime() {
var time = new Date().getTime();
while (time == new Date().getTime());
return new Date().getTime();
}
function getPage() {
var str = getUniqueTime();
console.log(str);
var data = 'page=' + encodeURIComponent(document.location.hash);
$('#content').fadeOut(200);
$.ajax({
url: "loader.php?_=" + str,
type: "POST",
data: data,
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
}
});
}
EDIT:
//loader.php
<?
require_once('session.class.php');
require_once('user.class.php');
$se = new session();
$lo = new user();
$se->regenerate();
if(isset($_POST))
{
$alpha = (string) $_POST['page'];
if($alpha == '#php')
{
include 'homeloader.php';
}
else if($alpha == '#cplus')
{
include 'cplusloader.php';
}
else if($alpha == '#web')
{
include 'underloader.php';
}
else if($alpha == '#about')
{
include 'underloader.php';
}
else if($alpha == '#social')
{
include 'socialloader.php';
}
}
else
$page = 'error';
echo $page;
?>
try this:
//on click of a button:
$("#button").live("click", function(){
//get you string data
var str = "test";
//do new version of ajax
$.post("loader.php", {str:str}, function(html){
$('#content').html(html);
});
});
and you dont need to do AJAX method anymore $.post works amazing
php doesn't compile? async request? actually not specifying ascync: true the request is executed asyncroniously and in version jQuery 1.8 there is no sync AJAX requests at all. Attach an error handler and you will see that your request probably results an error:
...
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
},
error: function (a,b) {
alert('Error!');
}
...
Normally AJAX consists of 2 parts - client side and server side. I don't see serverside posted in your question. You have to check both of them. Make a simple loader.php returning the string success and get rid of all extra get params. First test your php file in browser to be sure that it works. Check FireBug for javascript errors ...

jQuery get() php button submit

I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});

Categories