Jump to content

Search the Community

Showing results for tags 'ajax'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I have done this a while back but lost the code. It worked back then. I am trying to recreate it but my memory isn't perfect. It's basically a follow/unfollow button like twitter. This is the main reference. http://jsfiddle.net/jakie8/ZECEN/ The php/mysql action queries do work if I call it through normal a href link; but for some reason, it's not being called through ajax. The jquery/ajax set variables do show up correctly when I test an alert with them inside. So that works too. I could really use fresh pair of eyes to see what I might have done wrong. Here is the index.php page. <html> <head> <script src="js/jquery-1.11.0.min.js"></script> <script> $(function() { $(document).on('click','.followButton',function(e) { e.preventDefault(); $button = $(this); if($button.hasClass('following')){ //$.ajax(); Do Unfollow var unfollow = $(this).attr('rel'); var follower = $("#follower-id").val(); $.ajax({ type: "POST", url: "actions.php", data: "unfollow="+unfollow+"follower="+follower+"&action=unfollow", success:function(data){ $button.removeClass('following'); $button.removeClass('unfollow'); $button.text('+ Follow'); } }); } else { // $.ajax(); Do Follow var following = $(this).attr('rel'); var follower = $("#follower-id").val(); $.ajax({ type: "POST", url: "actions.php", data: "following="+following+"follower="+follower+"&action=follow", success:function(data){ $button.addClass('following'); $button.text('Following'); } }); // return false; } }); $('button.followButton').hover(function(){ $button = $(this); if($button.hasClass('following')){ $button.addClass('unfollow'); $button.text('Unfollow'); } }, function(){ if($button.hasClass('following')){ $button.removeClass('unfollow'); $button.text('Following'); } }); }); </script> </head> <body> <div class="container"> <input type="hidden" id="follower-id" value="<?php echo $follower_userid; ?>"> <button class="btn followButton following" rel="<?php echo $following_userid; ?>">+ Follow</button> </div> </body> </html> And here is actions.php page. require_once 'core/init.php'; if($action == "follow") { $following = $_POST['following']; $follower = $_POST['follower']; $date = date('Y-m-d H:i:s'); $follow = $db->prepare("INSERT INTO followers(following_id, follower_id, date, active) VALUES(:following_id, :follower_id, :date, :active)"); $follow->bindParam(':following_id', $following); $follow->bindParam(':follower_id', $follower); $follow->bindParam(':date', $date); $follow->bindValue(':active', 1); $follow->execute(); } else if($action == "unfollow") { $unfollow = $_POST['unfollow']; $follower = $_POST['follower']; $date = date('Y-m-d H:i:s'); $unfollow = $db->prepare("UPDATE followers SET date = :date, active = :active WHERE following_id = :following_id AND follower_id = :follower_id"); $unfollow->bindParam(':following_id', $unfollow); $unfollow->bindParam(':follower_id', $follower); $unfollow->bindParam(':date', $date); $unfollow->bindValue(':active', 0); $unfollow->execute(); } else { // echo 'no action'; }
  2. I am attempting to create a php AJAX contact form , however the email never seems to arrive in my outlook. /* Jquery Validation using jqBootstrapValidation example is taken from jqBootstrapValidation docs */ $(function() { $("input,textarea").jqBootstrapValidation( { preventSubmit: true, submitError: function($form, event, errors) { // something to have when submit produces an error ? // Not decided if I need it yet }, submitSuccess: function($form, event) { event.preventDefault(); // prevent default submit behaviour // get values from FORM var name = $("input#name").val(); var email = $("input#email").val(); var phone = $("input#phone").val(); var message = $("textarea#message").val(); var firstName = name; // For Success/Failure Message // Check for white space in name for Success/Fail message if (firstName.indexOf(' ') >= 0) { firstName = name.split(' ').slice(0, -1).join(' '); } $.ajax({ url: "./bin/contact_me.php", type: "POST", data: {name: name,phone:phone, email: email, message: message}, cache: false, success: function() { // Success message $('#success').html("<div class='alert alert-success'>"); $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×") .append( "</button>"); $('#success > .alert-success') .append("<strong>Your message has been sent. </strong>"); $('#success > .alert-success') .append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, error: function() { // Fail message $('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×") .append( "</button>"); $('#success > .alert-danger').append("<strong>Sorry "+firstName+" it seems that my mail server is not responding...</strong> Could you please email me directly ? Sorry for the inconvenience!"); $('#success > .alert-danger').append('</div>'); //clear all fields $('#contactForm').trigger("reset"); }, }) }, filter: function() { return $(this).is(":visible"); }, }); $("a[data-toggle=\"tab\"]").click(function(e) { e.preventDefault(); $(this).tab("show"); }); }); /*When clicking on Full hide fail/success boxes */ $('#name').focus(function() { $('#success').html(''); }); <?php require("../lib/phpmailer/PHPMailerAutoload.php"); if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $m = new PHPMailer(); $m->IsSMTP(); $m->SMTPAuth = true; $m->SMTPDebug = 2; $m->Host = "smtp-mail.outlook.com"; $m->Username = ""; $m->Password = ""; $m->SMTPSecure = 'tls'; $m->Port = 587; $m->addAddress('EXAMPLE@outlook.com', $name); $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; $m->Subject = "Contact Form has been submitted"; $m->Body = "You have received a new message. <br><br>". " Here are the details:<br> Name: $name <br> Phone Number: $phone <br>". "Email: $email_address<br> Message <br> $message"; if(!$m->Send()) { echo "Mailer Error: " . $m->ErrorInfo; exit; } ?>
  3. Say I have button 1 and I want to replace it with button2 on click. How would I do that? <button id="button1">butto 1</button> <button id="button2">butto 2</button>
  4. This twitter style button I found. http://jsfiddle.net/jakie8/ZECEN/ I have managed to modify it to my liking. And yes I know the ".live" is depreciated and instead use "on". Anyways, the only thing I noticed is that if I click "Follow" button and it turns green; once I refresh the page, it goes back to default "follow" mode. I was wondering how can I keep it green even if I refresh the page?
  5. I'm creating a social network site using Laravel. I have a page that load all the posts created by users the currentUser follows. I have a comment section on each post. I'm using ajax to post the comments. Here is my code. Here is the view of the comment-box. It contains a section where I loop through each comment and display them. At the end is the type field so a user can post a new comment: <div class="comment-box-container ajax-refresh"> <div class="comment-box"> @if ($type->comments) @foreach ($type->comments as $comment) <div class="user-comment-box"> <div class="user-comment"> <p class="comment"> <!-- starts off with users name in blue followed by their comment--> <span class="tag-user"><a href="{{ route('profile', $comment->owner->id) }}">{{ $comment->owner->first_name }} {{ $comment->owner->last_name }}</a> </span>{{ $comment->body }} </p> <!-- Show when the user posted comments--> <div class="com-details"> <div class="com-time-container"> {{ $comment->created_at->diffForHumans() }} · </div> </div> </div><!--user-comment end--> </div><!--user-comment-box end--> @endforeach @endif <!--type box--> <div class="type-comment"> <div class="type-box"> {{ Form::open(['data-remote', 'route' => ['commentPost', $id], 'class' => 'comments_create-form']) }} {{ Form::hidden('user_id', $currentUser->id) }} {{ Form::hidden($idType, $id) }} {{--{{ Form::hidden('user_id', $currentUser->id) }}--}} {{ Form::textarea('body', null, ['class' =>'type-box d-light-solid-bg', 'placeholder' => 'Write a comment...', 'rows' => '1']) }} {{ Form::close() }} </div><!--type-box end--> </div><!--type-comment--> </div><!--comment-box end--> The user submit the form for the comment type box by pressing the "enter/return" key. Here is the JS for that <script> $(document).on('keydown', '.comments_create-form', function(e) { if (e.keyCode == 13) { e.preventDefault(); $(this).submit(); } }); </script> Here is my Ajax (function(){ $(document).on('submit', 'form[data-remote]', function(e){ e.preventDefault(); var form = $(this) var target = form.closest('div.ajax-refresh'); var method = form.find('input[name="_method"]').val() || 'POST'; var url = form.prop('action'); $.ajax({ type: method, url: url, data: form.serialize(), success: function(data) { var tmp = $('<div>'); tmp.html(data); target.html( tmp.find('.ajax-refresh').html() ); target.find('.type-box').html( tmp.find('.type-box').html() ); tmp.destroy(); } }); }); })(); When I post a comment on the first post it all works fine. However, when I post a comment on the second, third, fourth etc it only displays the comments from the first post. I have to manually refresh the page, then the correct comments will display. I'll try to illustrate this problem with images. Starting fresh, I can easily submit 2 comments on POST 1 http://s27.postimg.org/6ej76hunn/comment1.jpg When I scroll down to Post 2, I see it already has a comment, I will submit a new comment http://s23.postimg.org/x65ui2ryz/comment_2.jpg HERE'S THE PROBLEM: When I submit the comment on POST 2, the comments that were in POST 2 disappears, and are replaced by the comments from POST 1. http://s30.postimg.org/ugl08oz01/comment_3.jpg The back end still worked, because when I reload the page everything is the way it should be http://s9.postimg.org/w51fgyzen/comment_4.jpg I'm completely stuck. Does anyone know why this is happening and how to fix it?
  6. So here's the situation. 1. I retrive records form mysql database. WORKS. 2. Within each record, I load a "form" via on click .button. WORKS. 3. The form is basically a way for a User to send a message to that record specifically. WORKS That process works. What doesn't work is that every time I submit a form to the database, it will not insert the "message" field text(appears empty) and the "record_id" will insert but it'll be same for all records inserted, no matter how many different records forms I submit. Other data like "message-to" and "message-by" insert fine. Here is the full page setup. Also, session_start(); is in the init.php <?php require_once 'core/init.php'; $user = new User(); $mainUserid = escape($user->data()->user_id); ?> <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title><?php echo $title; ?></title> <meta name="description" content="<?php echo $description; ?>"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link rel="stylesheet" href="css/style.css" media="screen"> </head> <body> $getRecord = $db->prepare("SELECT records.*, users.* FROM records LEFT JOIN users ON records.user_id = users.user_id ORDER BY record_id DESC LIMIT 10"); $getRecord->execute(); $resultRecord = $getRecord->fetchAll(PDO::FETCH_ASSOC); if(count($resultRecord) < 1) { $error = '0 records found.'; } else { foreach($resultRecord as $row) { $record_id = escape(intval($row['record_id'])); $user_id = escape(intval($row['user_id'])); $username = escape($row['full_name']); $title = escape($row['title']); $details = escape($row['details']); $_SESSION['record-id'] = $record_id; $_SESSION['message-to'] = $user_id; $_SESSION['message-by'] = $mainUserid; $message = Input::get('message'); // HTTP method POST or GET $_SESSION['message'] = $message; ?> <div class="record"> <h1><?php echo $title; ?></h1> <p><?php echo $details; ?></p> <p><?php echo $user_id; ?></p> <button class="button">send message</button> <!-- this form loads through on click(.button) function and is located in "ajax/form.php" --> <form class="new-form"> <textarea name="message" class="message">Enter message</textarea> <input type="button" name="submit" class="form-submit" value="Send Message"> </form> </div> <?php } } <!-- js scripts below --> <script src="js/jquery-1.11.0.min.js"></script> <script> $(document).ready(function(){ $(".button").click(function(){ $(this).parent().load("ajax/form.php"); }); }); </script> <script> $(document).on('click','.form-submit',function() { if($(".message").val()==='') { alert("Please write a message."); return false; } $(".form-submit").hide(); //hide submit button var myData = 'message='+ $(".message").val(); //build a post data structure jQuery.ajax({ type: "POST", // HTTP method POST or GET url: "process.php", //Where to make Ajax calls dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables success:function(response){ $(".message").val(''); //empty text field on successful $(".form-submit").show(); //show submit button }, error:function (xhr, ajaxOptions, thrownError){ $(".form-submit").show(); //show submit button alert(thrownError); } }); }); </script> </body> </html> here is process.php <?php require_once 'core/init.php'; $session_record_id = $_SESSION['record-id']; $session_message_to = $_SESSION['message-to']; $session_message_by = $_SESSION['message-by']; $session_message = $_SESSION['message']; $insertMssg = $db->prepare("INSERT INTO sub_records(record_id, message_to, message_by, message, bid_posted) VALUES(:record_id, :message_to, :message_by, :message)"); $insertMssg->bindParam(':record_id', $session_record_id); $insertMssg->bindParam(':message_to', $session_message_to); $insertMssg->bindParam(':message_by', $session_message_by); $insertMssg->bindParam(':message', $session_message); $resultInsert = $insertMssg->execute(); if($resultInsert == false) { $error = 'Your message could not be inserted.'; } else { $success = 'Your message has been added.'; } ?> <div class="success"><?php echo $success; ?></div> <div class="error"><?php echo $error; ?></div>
  7. For eg, say I am retreiving 3 records from database and they look like this. <div class="record"> <h1>Record title 1</h1> <p>Record description</p> <button class="button">send message</button> </div> <div class="record"> <h1>Record title 2</h1> <p>Record description</p> <button class="button">send message</button> </div> <div class="record"> <h1>Record title 3</h1> <p>Record description</p> <button class="button">send message</button> </div> and this is my ajax to load the form. <script> $(document).ready(function(){ $(".button").click(function(){ $(".record").load("form.php .new-form"); }); }); </script> the form looks like this. <form class="new-form"> <textarea name="message" class="message"></textarea> <input type="button" name="submit" class="form-submit" value="Send Message"> </form> That all works. The only problem with that is, it loads the form in EACH record. How can I make it so that the form only loads to the div record from which I am calling from?
  8. 1down votefavorite I have been building a bowling score calculator. The calculator itself works but you must enter all scores in the form at once and then it will calculate the total score. I wanted it to loop form the form to enter your score for each frame, submit the form show the current score and reload the form again for the next frame. This is the first time I have used ajax and followed a tutorial on how to submit a form via ajax but it does not seem to be working. This is the first time I have used ajax, the ajax code is form an online tutorial I have followed and have not been able to get it working yet. The two scripts are below. PHP Script: <?php session_start(); //start a new game if (isset($_GET["endGame"]) && $_GET["endGame"] == 'yes') { session_destroy(); //redirect to homepage and remove any get parameters $location="http://localhost/bbc/v8.php"; echo '<META HTTP-EQUIV="refresh" CONTENT="0;URL='.$location.'">'; } //Check if the number of players has been set if (isset($_POST['next'])) { //Determine thye number players foreach ($_POST['numberOfPlayers'] as $player) { $_SESSION['numberOfPlayers'] = $player; $location="http://localhost/bbc/v8.php"; echo '<META HTTP-EQUIV="refresh" CONTENT="0;URL='.$location.'">'; } //check number of players has been set before enter player names } elseif (isset($_SESSION['numberOfPlayers'])) { $numberOfPlayers = $_SESSION['numberOfPlayers']; if (!isset($_POST['playerSubmit']) || (isset($_POST['scores']))) { ?> <!-- Form to enter the playes names --> <form method="post" action=""> <fieldset> <?php $x = 1; echo '<div class="custTitle"><h3>Enter player names below</h3></div>'; while ($x <= $numberOfPlayers) { echo '<input class="form-control" type="text" name="players[]" placeholder="Player ' . $x . '">'; $x++; } ?> </fieldset> <input type="submit" name="playerSubmit" value="Start Game"> </form> <?php }// close if } if (isset($_POST['playerSubmit'])) { $players = array(); foreach ($_POST['players'] as $player) { $players[] = $player; } // save player names array to session for reuse $_SESSION['players'] = $players; } //Check player name have been submitted if(isset($_POST['playerSubmit']) || isset($_SESSION['players'])) { //create global variable of players array $players = $_SESSION['players']; $_SESSION['frameScore'] = array(0); $frameCount = 1; while ($frameCount <=9 ) { ?> <!-- Form to enter players score--> <form method="post" action="" class="ajax"> <?php $i = 0; while($i < $_SESSION['numberOfPlayers']){ echo '<fieldset>'; echo '<h3>' . $players[$i] . '</h3>'; $x=1; // loop the form 21 times for maximum of 21 throws while($x <= 3){ ?> <label>Throw, <?php echo $x; ?></label> <select class="form-control" name="score[<?php echo $i; ?>][<?php echo $x; ?>]"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">X</option> </select> <?php $x++; }// close 21 throws while ?> <input type="hidden" name="player[<?php echo $i; ?>]" value="<?php echo $players[$i] ?>"> </fieldset> <?php $i++; }// close while for looping throuhg players ?> <input type="submit" value="Finish Game" name="scores"/> </form> <?php // close player submit if // check if any scores have been submitted if(isset($_POST['score'])) { $i = 0; $result = []; foreach($_SESSION['players'] as $name) { $result[$name] = $_POST['score'][$i]; $pins = $_POST['score'][$i]; $game = calculateScore($i, $pins); $i++; } } $frameCount++; }// close do while // if number of players is not yet set the show the form to select number of players } else { ?> <!-- Form to select the number players --> <h2>How many players will be bowling?</h2> <form method="post" action=""> <select class="form-control" name="numberOfPlayers[]"> <option name="numberOfPlayers[]" value="1">1</option> <option name="numberOfPlayers[]" value="2">2</option> <option name="numberOfPlayers[]" value="3">3</option> <option name="numberOfPlayers[]" value="4">4</option> <option name="numberOfPlayers[]" value="5">5</option> <option name="numberOfPlayers[]" value="6">6</option> </select> <input type="submit" name="next" value="Next"> </form> <?php }// close else // if the number of players has been set show a 'New Game' button if (isset($_SESSION['numberOfPlayers'])) { echo '<button class="btn_lrg"><span><a href="http://localhost/bbc/v8.php?endGame=yes">New Game</a></span></button>'; } // function to calculate the players scores function calculateScore($player, $pins) { global $players; $frame = 0; // create an array for the frame score //$frameScore = $_SESSION['frameScore']; //$frameScore = array(0); //loop for 10 frames of a game while ($frame <=9) { $_SESSION['frameScore'][$frame] = array_shift($pins); //Check for a strike if($_SESSION['frameScore'][$frame] == 10) { $_SESSION['frameScore'][$frame] = (10 + $pins[0] + $pins[1]); // No strike, so take in two throws } else { $_SESSION['frameScore'][$frame] = $_SESSION['frameScore'][$frame] + array_shift($pins); //Check for a spare if($_SESSION['frameScore'][$frame] == 10) { $_SESSION['frameScore'][$frame] = (10 + $pins[0]); } }// close if //Move to the next frame and loop again $frame++; }// close while //echo out player scoreborad echo '<h3>' .$_SESSION["players"][$player]. '</h3>' . '<h4>' . array_sum($_SESSION['frameScore']) . '</h4>'; }// end calculateScore function ?> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="main.js"></script> <!-- End Bowling Calculator Script --> JavaScript/Ajax: $('form.ajax').on('submit', function() { var that = $(this), url = that.attr('action'), type = that.attr('method'), data = {}; that.find('[name]').each(function(index, value) { var that = $(this), name = that.attr('name'), value = that.val(); data[name] = value; }); $.ajax({ url: url, type: type, data: data, }); return false; });
  9. I would like to know how can I redirect a jquery dialog function to a different page, if another function is true? For eg. 1. User 1 sends a request to User 2. 2. User 2 accepts the request. 3. User 1 still has the request "dialog" window open. Instead, I would like to have that dialog window close and redirect to a specified page. Of course this only happens after User 2 accepts the request and I check against it in the database. Here is the function for when User 1 makes a request. <script> $(function() { $("#new-dialog").dialog({ resizable: true, autoOpen: false, modal: true, width: 600, height: 300, buttons: { "Cancel Trade": function(e) { $(this).dialog("close"); $.ajax({ type:"post", url:"request-trade?by=<?php echo $session_requestById; ?>&to=<?php echo $session_requestToId; ?>", data:"action=cancelTrade", success:function(data){ if(data == true) { alert('success'); } else { alert('not deleted'); } //window.location.href='trade?by=<?php echo $session_requestById; ?>&to=<?php echo $session_requestToId; ?>'; } }); } } }); $(".dialogify").on("click", function(e) { e.preventDefault(); $("#new-dialog").html(""); $("#new-dialog").dialog("option", "title", "Loading...").dialog("open"); $("#new-dialog").load(this.href, function() { $(this).dialog("option", "title", $(this).find("h1").text()); $(this).find("h1").remove(); }); }); }); </script> And here is the new function in which I check the database for match. If it returns true, I would like to redirect the above dialog/page. <script> $('document').ready(function(){ function checkTrade() { $.ajax({ type:"post", url:"request-trade?by=<?php echo $session_requestById; ?>&to=<?php echo $session_requestToId; ?>", data:"action=checkTrade", success:function(data){ window.location.href='trade?by=<?php echo $session_requestById; ?>&to=<?php echo $session_requestToId; ?>'; } }); } }); </script> So what am I missing to do the redirect?
  10. Here's the basic premise of the function I am trying to create. 1. User 1 sends a trade request to User 2. 2. User 2 accepts the request. 3. It redirects both users to new page(trade.php). Below is the code where User 2 accepts the request.I am using jquery dialog box for pop windows. The current issue I am having is that "window.location." is not showing the "by=$session_requestById" variable. It appears as NULL if I var_dump on trade.php page. But it is showing the second variable correctly, which is "by=$session_requestToId". It seems like it only happens on trade.php page. Both variables show up fine on request-php.page and in heading when I var_dump. Perhaps you can tell me what's wrong with this ? window.location.href='trade?by=<?php echo $session_requestById; ?>&to=<?php echo $session_requestToId; ?>'; <script> $(function() { $( "#dialog-confirm" ).dialog({ resizable: true, autoOpen: true, modal: true, width: 600, height: 300, buttons: { "Accept Trade": function() { $( this ).dialog( "close" ); $.ajax({ type:"post", url:"request-trade?by=<?php echo $session_requestById; ?>&to=<?php echo $session_requestToId; ?>", data:"action=acceptTrade", success:function(data){ window.location.href='trade?by=<?php echo $session_requestById; ?>&to=<?php echo $session_requestToId; ?>'; } }); }, Cancel: function() { $( this ).dialog( "close" ); $.ajax({ type:"post", url:"request-trade?by=<?php echo $session_requestById; ?>&to=<?php echo $session_requestToId; ?>", data:"action=cancelTrade", success:function(data){ if(data == false) { alert('not cancelled'); } else { alert('cancelled success'); } } }); } } }); }); </script>
  11. This should all be working but I think I might be overlooking something. Problem 1. I am using ajax to process a form. I don't think the problem is with ajax(works with other queries), but rather with php. Here is my simple query. $stmt = $db->prepare("SELECT * FROM records WHERE request_by = :request_by, request_to = :request_to AND session = :session"); $stmt->bindParam(':request_by', $byUserid); $stmt->bindParam(':request_to', $toUserid); $stmt->bindValue(':session', 1); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); if(count($result) > 0) { $success = 'This was successful.'; } else { $error = 'There was a problem.'; } This above query gives me this error. Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' request_to = '7' AND session = '1'' at line 1 Problem 2. Say the main page is "index.php" with submit form and I am using ajax via url: process.php. Well on "index.php" page, I have foreach loop that gets me a "$toUserid" for each record. I would like to use that "$toUserid" in "process.php" page. I tried setting it as a session but still it won't give me that exact userid. It'll give me the same userid as the user I am currently logged in. What exactly I am doing wrong and how I can i fix it?
  12. I am not very advanced in web programming I need help.. I am using an API and my sql database. I would to implement live/ dynamic updates in the text field where user will input their text, and the web should first check the database then the api live. I would also like to retrieve the user input without refreshing the page, so the retrieved information regarding the inputted text should be automatically loaded without refreshing the page. please help .
  13. Here's the code that deals with the client side: search.php <?php //testing if data is sent ok echo "<h1>Hello</h1><br>" . $_GET['search']; ?> This is the link I get after sending foo. http://www.family-line.dx.am/Community/index.php?&search=foo Is that mean it was sent, but I'm not processing it correctly? I'm new to the whole AJAX thing.
  14. Hi, I have the below code and jquery in wordpress. I would like the form to auto submit, but at the moment I just get a 0 in the place of the heart icon. it seems to refresh but the form is not submitting the query. Thank you in advance <form id="lastviewer" class="ajax-form" action="<?php echo AJAX_URL; ?>" method="POST"> <?php if(ThemexUser::islastviewed(ThemexUser::$data['active_user']['ID'])) { ?> <a href="#" title="<?php _e('Remove from lastviewed', 'lovestory'); ?>" data-title="<?php _e('Add to Last Viewed', 'lovestory'); ?>" class="icon-heart submit-button current"></a> <input type="hidden" class="toggle" name="user_action" value="remove_lastviewed" data-value="add_lastviewed" /> <?php } else { ?> <a href="#" title="<?php _e('Add to Last Viewed', 'lovestory'); ?>" data-title="<?php _e('Remove from Last Viewed', 'lovestory'); ?>" class="icon-heart submit-button"></a> <input type="hidden" class="toggle" name="user_action" value="add_lastviewed" data-value="remove_lastviewed" /> <?php } ?> <input type="hidden" name="user_lastviewed" value="<?php echo ThemexUser::$data['active_user']['ID']; ?>" /> <input type="hidden" class="nonce" value="<?php echo wp_create_nonce(THEMEX_PREFIX.'nonce'); ?>" /> <input type="hidden" class="action" value="<?php echo THEMEX_PREFIX; ?>update_user" /> </form> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { window.setInterval(function() { AutoPost(); }, 3000); }); function AutoPost() { $.ajax({ type: "POST", url: "<?php echo AJAX_URL; ?>", success: function(data) { $("#lastviewer").html(data) ; } }); } </script>
  15. Hi, I'm a novice and have the below code in a Wordpress theme. I'm trying to get the form to submit automatically so it logs an entry into the MySql db as though the person clicked the heart icon (submit). Ideally I subsequently want to hide the heart icon so on load maybe after 3 seconds the entry is auto fired to the MySql DB. I have got as far as the manual click adding the entry, however can't get to to auto submit, any gel would be appreciated. Thank you in advance. ////PHP Form///// <form class="ajax-form" action="<?php echo AJAX_URL; ?>" method="POST"> <?php if(ThemexUser::islastviewed(ThemexUser::$data['active_user']['ID'])) { ?> <a href="#" title="<?php _e('Remove from lastviewed', 'lovestory'); ?>" data-title="<?php _e('Add to Last Viewed', 'lovestory'); ?>" class="icon-heart submit-button current"></a> <input type="hidden" class="toggle" name="user_action" value="remove_lastviewed" data-value="add_lastviewed" /> <?php } else { ?> <a href="#" title="<?php _e('Add to Last Viewed', 'lovestory'); ?>" data-title="<?php _e('Remove from Last Viewed', 'lovestory'); ?>" class="icon-heart submit-button"></a> <input type="hidden" class="toggle" name="user_action" value="add_lastviewed" data-value="remove_lastviewed" /> <?php } ?> <input type="hidden" name="user_lastviewed" value="<?php echo ThemexUser::$data['active_user']['ID']; ?>" /> <input type="hidden" class="nonce" value="<?php echo wp_create_nonce(THEMEX_PREFIX.'nonce'); ?>" /> <input type="hidden" class="action" value="<?php echo THEMEX_PREFIX; ?>update_user" /> </form> ////Ajax///// //Elements var themeElements = { ajaxForm: '.ajax-form', } //AJAX Form $(themeElements.ajaxForm).each(function() { var form=$(this); form.submit(function() { var message=form.find('.message'), loader=form.find('.loader'), toggle=form.find('.toggle'), button=form.find(themeElements.submitButton), title=form.find(themeElements.submitButton).data('title'); var data={ action: form.find('.action').val(), nonce: form.find('.nonce').val(), data: form.serialize() } loader.show(); button.addClass('disabled').toggleClass('current'); if(!message.hasClass('static')) { message.slideUp(300, function() { $(themeElements.colorboxLink).colorbox.resize(); }); } jQuery.post(form.attr('action'), data, function(response) { if(jQuery('.redirect', response).length) { if(jQuery('.redirect', response).attr('href')) { window.location.href=jQuery('.redirect',response).attr('href'); } else { window.location.reload(); } message.remove(); } if(title) { button.data('title', button.attr('title')); button.attr('title', title); } toggle.each(function() { var value=toggle.val(); toggle.val(toggle.data('value')); toggle.data('value', value); }); loader.hide(); button.removeClass('disabled'); if(response!='' && response!='0' && response!='-1') { if(message.hasClass('popup')) { $.colorbox({html:'<div class="popup">'+response+'</div>'}); } else if(message.hasClass('static')) { message.append(response); } else { message.html(response).slideDown(300, function() { $(themeElements.colorboxLink).colorbox.resize(); }); } } form.find('.temporary').val(''); form.find('.scroll').each(function() { $(this).scrollTop($(this)[0].scrollHeight); }); }); return false; }); }); Thank you
  16. I have a problem, where i need to know when user leave or close tha browser tab. I tryd to make a ajax post, after unload, make a POST into kill_browser.php and after 1 minute when session_expire, php code will be execute and save time into database. But it not seems to work :/ I'm glad if some 1 can say what im doing wrong, or is there eny better way to detect it. @home.php var leaved = 'leaved'; $(window).unload( function(){ $.ajax({ url: 'kill_browser.php', global: false, type: 'POST', data: leaved, async: false, success: function() { console.log('leaved'); } }); }); @kill_browser.php <?php require('class/connection.php'); $conn = new connection(); session_cache_limiter('private'); $cache_limiter = session_cache_limiter(); session_cache_expire(1); $cache_expire = session_cache_expire(); session_start(); $_SESSION['leaved'] = $_POST['leaved']; if($_SESSION['leaved'] == null || $_SESSION['leaved'] == " "){ $conn->logOut($_SESSION['userID'], $_SESSION['userIP'], $_SESSION['LAST_GENERATED_ID']); session_regenerate_id(true); unset($_SESSION); session_destroy(); header('location:index.php'); } ?>
  17. I have created a login form. I am sending values through Ajax for form validation. However, I am having problem with the code that I am unable to store values in Sessions & Cookies. I have added a "Remember me" checkbox into login form. I want to validate Boolean value using Javascript Checked property and send the data to PHP for validation. If user clicks on remember me checkbox then the data should be stored in either Sessions & Cookies. If it is not checked then data should be stored only in Sessions. I am posting here my login form code, Ajax code & PHP code. Could you guys help me to point out my mistake what I am doing wrong in this code? Login Form: <input type="checkbox" id="cb" name="cb"> <label for="cb">Remember me</label> Ajax Code: function login(){var e = _("email").value; var pass = _("password").value; var cb = _("cb").value; if(e == "" || pass == ""){ _("status").innerHTML = "Please fill out the form"; } else { _("loginbtn").style.display = "none"; _("status").innerHTML = 'please wait ...'; var ajax = ajaxObj("POST", "handlers/login_handler.php"); ajax.onreadystatechange = function() { if(ajaxReturn(ajax) == true) { if(ajax.responseText == "login_failed"){ _("status").innerHTML = "Login failed, please try again."; _("loginbtn").style.display = "block"; } else { window.location = "message.php?msg=Hello "+ajax.responseText; } } } ajax.send("e="+e+"&pass="+pass+"&cb="+cb); } } PHP Code: $cb = cleanstr($_POST['cb']); if(isset($cb) && ($cb == true)) { // IF USER CLICKED ON REMEMBER ME CHECKBOX CREATE THEIR SESSIONS AND COOKIES $_SESSION['userid'] = $db_id; $_SESSION['username'] = $db_username; $_SESSION['password'] = $db_pass; setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE); setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE); setcookie("pass", $db_pass, strtotime( '+30 days' ), "/", "", "", TRUE); // UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS $sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE id='$db_id' LIMIT 1"; $query = mysqli_query($con, $sql); echo $db_username; exit(); } else { // IF USER HAS NOT CLICKED ON REMEMBER ME CHECKBOX CREATE THEIR SESSIONS ONLY $_SESSION['userid'] = $db_id; $_SESSION['username'] = $db_username; $_SESSION['password'] = $db_pass; // UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS $sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE id='$db_id' LIMIT 1"; $query = mysqli_query($con, $sql); echo $db_username; exit(); }
  18. For eg. I have a page with a query that retrives records from the database and I want to have options of filtering out the shown records by date, time, likes, views..etc; how would I go about doing that? The way I am thinking is having a html form with those filter inputs and using a relative query based on the filter selection to retrive the results. What you think?
  19. Below is my code that is suppose to insert and show records from database using ajax. Retrieving the records from the database works. However it won't insert a record. I do not get any errors. The page simply refreshes when I hit submit button. Can you see what might be wrong in my code? index.php <script> $(document).ready(function(){ function showComment(){ $.ajax({ type:"post", url:"process.php", data:"action=showcomment", success:function(data){ $(".wrapper").html(data); } }); } showComment(); $("#submit").click(function(){ var name=$("#name").val(); var message=$("#details").val(); $.ajax({ type:"post", url:"process.php", data:"name="+name+"&details="+message+"&action=addcomment", success:function(data){ showComment(); } }); }); }); </script> $id = $_GET['id']; $title = $_GET['title']; $_SESSION['id'] = $id; $_SESSION['title'] = $title; <div class="wrapper"></div> <form action="" method="post" enctype="multipart/form-data"> <div class="newfield"> <label for="title">Name <span class="highlight">*</span></label> <input id="name" type="text" name="name"> </div> <div class="newfield"> <label for="details">Details <span class="highlight">*</span></label> <textarea id="details" name="details""></textarea> </div> <input type="submit" name="submit" id="submit" value="Submit Tale"> </form> process.php <?php require_once '/core/init.php'; $id = $_SESSION['id']; $action = $_POST['action']; if($action == 'showcomment') { try { $get = $db->prepare("SELECT * FROM sub_posts WHERE id = :id"); $get->bindParam('id', $id); $get->execute(); $getStmt = $get->fetchAll(PDO::FETCH_ASSOC); if(count($getStmt) > 0) { foreach($getStmt as $row) { $new_name = $row['name']; $new_details = $row['details']; ?> <ul> <li> <?php echo $new_name; ?> </li> <li> <?php echo $new_details; ?> </li> </ul> <?php } } else { // no records found. } } catch(Exception $e) { die($e->getMessage()); } } else if($action == 'addcomment') { $name = $_GET['name']; $details = $_GET['details']; try { $insert = $db->prepare("INSERT INTO sub_posts(id, name, details) VALUES(:id, :name, :details)"); $insert->bindParam('id', $id); $insert->bindParam('name', $name); $insert->bindParam('details', $details); $insert->execute(); if($insert == false){ echo 'record could not be inserted.'; } else { echo 'record has been inserted.'; } } catch(Exception $e) { die($e->getMessage()); } } else { echo 'no results.'; }
  20. I have seen a couple of other threads relatively similar but I still find my problem unique so I hope you guys give me a chance. What I want to do: use proxy to bypass same origin policy and to save these values (that changes and need to be checked by timer) into variables that can be modified. A server contains data.asp which looks something like this and updates from time to time (although with a bit more data): { "Title":"Tile of song" ,"Artist":"The artist" ,"Album":"The album" ,"CDCover":"/covers/randomcover.jpg" } The method I have tried is like the one on http://qnimate.com/same-origin-policy-in-nutshell/#Same_Origin_Policy_for_AJAX. In case you guys don't want to follow the link I've posted the data here as well. <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","http://www.qnimate.com/ajaxdata.php",true); xmlhttp.send(); } </script> </head> <body> <button type="button" onclick="loadXMLDoc()">Request data</button> <div id="myDiv"></div> And the proxy file: <?php echo file_get_contents('http://www.qscutter.com/ajaxdata.txt'); ?> So what I want to do is store the data into variables that I can alter, not show it inside a div using innerHTML. Preferably check this ever so often for changes as well. Suggestions? I can add that I have the permission from the server owner to retrieve the information and to use it but no possibility to add script to their server, hence the proxy bypass attempt.
  21. All I am trying to do is add a record on a page without the page refreshing. For that ajax is used. Here is the code. It does not add the record to mysql table. Can anyone tell me what I am doing wrong? record.php <!DOCTYPE HTML> <html lang="en"> <head> <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script> <script type="text/javascript" > $(function() { $(".submit_button").click(function() { var textcontent = $("#content").val(); var name = $("#name").val(); var dataString = 'content='+ textcontent + '&name='+name; if(textcontent=='') { alert("Enter some text.."); $("#content").focus(); } else { $("#flash").show(); $("#flash").fadeIn(400).html('<span class="load">Loading..</span>'); $.ajax({ type: "POST", url: "action.php", data: dataString, cache: true, success: function(html){ $("#show").after(html); document.getElementById('content').value=''; $("#flash").hide(); $("#content").focus(); } }); } return false; }); }); </script> </head> <body> <?php $record_id = $_GET['id']; // getting ID of current page record ?> <form action="" method="post" enctype="multipart/form-data"> <div class="field"> <label for="title">Name *</label> <input type="text" name="name" id="name" value="" maxlength="20" placeholder="Your name"> </div> <div class="field"> <label for="content">content *</label> <textarea id="content" name="content" maxlength="500" placeholder="Details..."></textarea> </div> <input type="submit" name="submit" value="submit" class="submit_button"> </form> <div id="flash"></div> <div id="show"></div> </body> </html> action.php if(isset($_POST['submit'])) { if(empty($_POST['name']) || empty($_POST['content'])) { $error = 'Please fill in the required fields!'; } else { try { $name = trim($_POST['name']); $content = trim($_POST['content']); $stmt = $db->prepare("INSERT INTO records(record_id, name, content) VALUES(:recordid, :name, :content"); $stmt->execute(array( 'recordid' => $record_id, 'name' => $name, 'content' => $content )); if(!$stmt){ $error = 'Please fill in the required fields.'; } else { $success = 'Your post has been submitted.'; } } catch(Exception $e) { die($e->getMessage()); } } }
  22. Here goes. I am trying to retrieve info. from mySql database and update 3 textfields. I also have 4 selects on the form that need populating during the running of the program. My problem is using console I can see the info - Customer name - but it does not appear in the text field. The onchange request in the DIV container seems to be where it fails. Here are the files I am using: 1. add_an_order.php <html> <head> <title>Add an Order</title> <link href = "css/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="include/jquery-1.11.1.min.js"></script> </head> <body> <div id="header"><img src="images/logo.png" /></div> <div id="nav"> <div id="nav_wrapper"> <ul> <li><a href="index.php">Orders</a></li><li> <a href="customers.php">Customers</a></li><li> <a href="contacts.php">Contacts</a></li><li> <a href="batteries.php">Batteries</a></li><li> <a href="#">Queries</a> </li> </ul> </div> </div> <div id="main"> <?php echo '<h3 id="menOpt">Add an Order</h3><hr>'; // Check for a form submission. /* if ($_SERVER['REQUEST_METHOD'] == 'POST') { $errors = array(); $required_fields = array('customer_name', 'customer_address', 'city', 'telephone'); foreach ($required_fields as $fieldname) { if (!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) { $errors[] = strtoupper($fieldname); } } if (empty($errors)) { include ('include/dbconnect.php'); $name = mysqli_real_escape_string($con, trim(strip_tags($_POST['customer_name']))); $contact = mysqli_real_escape_string($con, trim(strip_tags($_POST['contact']))); $address = mysqli_real_escape_string($con, trim(strip_tags($_POST['customer_address']))); $city = mysqli_real_escape_string($con, trim(strip_tags($_POST['city']))); $telephone = mysqli_real_escape_string($con, trim(strip_tags($_POST['telephone']))); $telephone = preg_replace('/[^0-9]/', '', $telephone); if (isset($_POST['deepc'])) { $deepc = 1; } else { $deepc = 0; } if (isset($_POST['problemc'])) { $problemc = 1; } else { $problemc = 0; } $problem = mysqli_real_escape_string($con, trim(strip_tags($_POST['problem']))); if (isset($_POST['blacklist'])) { $blacklist = 1; } else { $blacklist = 0; } if (isset($_POST['pickup'])) { $pickup = 1; } else { $pickup = 0; } $query = "INSERT INTO customers ( customer_name, contact, customer_address, city, telephone, deep_cycle, problem_customer, problem, blacklist, pickup) VALUES ('$name', '$contact', '$address', '$city', '$telephone', $deepc, $problemc, '$problem', $blacklist, $pickup)"; $r = mysqli_query($con, $query); if (mysqli_affected_rows($con) == 1) { echo '<p class="success">Customer has been successfully added.</p>'; } else { $message = "Could not add customer."; $message .= "<br />" . mysqli_error($con); } mysqli_close($con); } else { // We have errors. $message = count($errors) . " error(s) on the form."; } } // End: if ($_SERVER['REQUEST_METHOD'] == 'POST'). */ // Leave PHP and display the form. ?> <?php if (!empty($message)) { echo '<p class="error">' . $message . '</p>'; } ?> <?php // Output list of fields that have errors. if (!empty($errors)) { echo '<p class="error">'; foreach ($errors as $error) { echo $error . '<br />'; } echo '</p>'; } ?> <div class="container"> <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <fieldset> <label>Business: <span class="important"> *</span><select name="customer_name" id="customer_name" onchange="request_fill(this.value)" value="<?php if (isset($_POST['customer_name'])) echo $_POST['customer_name']; ?>" ></select></label> <label>Address: <input type="text" name="address" id="add_a" value="<?php if (isset($_POST['customer_address'])) echo $_POST['customer_address']; ?>" /></label> <label>City: <input type="text" name="city" id="city" value="<?php if (isset($_POST['city'])) echo $_POST['city']; ?>" /></label> <label>Phone: <input type="text" name="telephone" value="<?php if (isset($_POST['telephone'])) echo $_POST['telephone']; ?>" /></label> <label>Manufacturer: <span class="important"> *</span><select name="manufacturer" id="manufacturer" onchange="request_mod(this.value)" value="<?php if (isset($_POST['manufacturer'])) echo $_POST['manufacturer']; ?>" ></select></label> <label>Model: <span class="important"> *</span><select name="model" id="model" onchange="form_yr(this.value)" value="<?php if (isset($_POST['model'])) echo $_POST['model']; ?>" ></select></label> <label>Year: <span class="important"> *</span><select name="battery" id="bat_disp" value="<?php if (isset($_POST['battery'])) echo $_POST['year'] ?>" ></select></label> <label>Quantity: <span class="important"> *</span><input type="text" name="quantity" id="quantity" value="<?php if (isset($_POST['quantity'])) echo $_POST['quantity']; ?>" /></label> <label>Warranty ? <input type="checkbox" name="warranty" <?php if ($_POST['warranty']) echo " checked"; ?> /></label> <label>Exchange ? <input type="checkbox" name="exchange" <?php if ($_POST['exchange']) echo " checked"; ?> /></label> <input type="submit" name="submit" value="Add Order" /> or <a href="index.php">Cancel</a> </fieldset> </form> </div> <script type="text/javascript" src="include/functions.js"></script> <script> $(document).ready(function() { $('.container').hide(); $('.container').fadeIn(1000); request_cust(); request_man(); }); </script> <?php include ('include/footer.php'); 2. request_fill function request_fill() { var cust2 = 'customer'; var ad = document.getElementById("add_a"); var hr = new XMLHttpRequest(); hr.open("POST", "battery_parser.php", true); hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); hr.onreadystatechange = function() { if(hr.readyState == 4 && hr.status == 200) { var dataArray = hr.responseText; ad.innerHTML = dataArray[1]; } } hr.send("&cust2="+cust2); } 3. battery_parser.php <?php include_once("include/dbconnect.php"); if (isset($_POST['cust2'])) { $cust2 = $_POST['cust2']; $sql = "SELECT customer_address FROM customers WHERE customer_id = 2"; $query = mysqli_query($con, $sql); $dataString = ''; while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){ $add = $row["customer_address"]; $dataString = $add; } mysqli_close($con); echo $dataString; exit(); } else { exit(); } ?>
  23. Hello fellow programmers I recently bought a chat site without investigating (i know stupid me). this chat is made in Php / Mysql language and ajax, My question is, is there a possibility to convert the mysql to an IRC server. I dont know how to explane it 100% but is it possible to make the webchat thats coded in ajax & mysql work for a IRC server I have knowledge of mysql / php only is this above my level. My problem is that mysql is no option for chats, I need this webchat work with IRC but I have no idea where i should start. Maby someone can kick me in the right direction Thanks for your time & help Greets BTW this is the chatsite more people bought (this aint my site) but 100% the same : http://tinyurl.com/kk4gchd
  24. In my shopping cart i want an alert message when the maximum number of 5 for the item has been reached or ask them to delete the item if the press - when the item quantity is at 1. i have it working in php: //add to quantity of item if (isset($_POST['itemadd'])){ $additem = $_POST['additem']; $sqladd = "SELECT quantity FROM orders WHERE id = '$additem'"; $query_add = mysqli_query($db_conx, $sqladd); while($row = mysqli_fetch_array($query_add, MYSQLI_ASSOC)){ $itemqty = $row['quantity']; if ($itemqty < 5){ $addqty = $itemqty + 1; $adding = "UPDATE orders SET quantity = '$addqty' WHERE id = '$additem'"; $add_query = mysqli_query($db_conx, $adding); header('Location: http://www.quichlicious.co.uk/cart.php'); //print $additem; exit(); } else { $usemes = "You have reached maximum quantity"; } } But rather than display the message in a div i would like a javascript alert box to pop up, i tried the following code: <script type="text/javascript"> function CheckQtyPlus(){ var qty = '<?php echo $qty; ?>'; alert("message here"+qty); } </script> but i get the same quantity number for every item in the cart, i had this error with the php update but i got round that by querying sql to give me the quantity of an item by the items id. can the same thing be done in javascript / ajax? $qty by the way is referenced earlier in the script to get information for the cart table to display items. thanks Michael
  25. I have a page that functions like this: The user begins by loading ajaxtest.php, then using a drop-down menu, selects a user, after which a DIV on ajaxtest.php is populated with the user's selction to getuser.php?q=John%Doe Here's a visual representation of what is currently happening, along with the part I don't understand. getuser.php consists largely of a a large HTML table which interacts through PHP with my SQL database. Several of the fields in this table are editable, and after the user changes one of these fields, he can press an "update" button, which calls an AJAX script in update.js and runs update.php, which contains all my SQL queries to update the database, without the user being redirected to this update.php page. All of this is processing perfectly - the user makes some sort of edit, hits "update", and the database gets updated without any redirection or refresh. Here's what I can't figure out though. Once the user makes a change, and hits "update," the database updates, but the end user doesn't see those changes that he made. I can't just do a simple page refresh, because the action is taking place on getuser.php, but getuser.php is loaded inside of a #DIV on ajaxtest.php. If I use something like window.location.reload(), this just refreshes ajaxtest.php and puts the user back to the starting point of having to select a user. This is not what I want. I don't want to refresh ajaxtest.php, I want to "refresh" ajaxtest.php with getuser.php?q=John%Doe insidethe DIV on ajaxtest.php. It seems like this is very common - several forums have this capability, where a user has a page loaded, adds a comment, and sees that comment immediately without a full page refresh. I just don't know how to do it, and I've tried at lengths to search the web for an answer with no luck. Can someone walk me through how to do this?
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.